feat(bridge): implement Fastify bridge API for WordPress (BIT-350) #1

Merged
spark merged 2 commits from task/BIT-350-bridge-api into main 2026-03-23 14:55:51 +00:00
16 changed files with 2301 additions and 0 deletions

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
# Bridge server port (default: 3200)
PORT=3200
# Host/domain used when no Host header is present (dev fallback)
DEFAULT_HOST=localhost
# Absolute path to config/domains/ directory
DOMAINS_CONFIG_PATH=../config/domains
# Redis connection URL (optional; if unset, in-process Map cache is used)
REDIS_URL=redis://127.0.0.1:6379
# Cache TTLs (seconds)
CACHE_FRESH_TTL=60
CACHE_STALE_TTL=300
# Rate limit: max requests per window per IP
RATE_LIMIT_MAX=100
RATE_LIMIT_WINDOW_MS=60000
# Log level: fatal | error | warn | info | debug | trace
LOG_LEVEL=info
+3
View File
@@ -0,0 +1,3 @@
node_modules/
dist/
.env
+1255
View File
File diff suppressed because it is too large. Load diff
+24
View File
@@ -0,0 +1,24 @@
{
"name": "news-bridge",
"version": "1.0.0",
"description": "WordPress REST API bridge for the news platform",
"type": "module",
"main": "dist/server.js",
"scripts": {
"dev": "tsx watch src/server.ts",
"build": "tsc",
"start": "node dist/server.js",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@fastify/cors": "^9.0.1",
"@fastify/rate-limit": "^9.1.0",
"fastify": "^4.28.1",
"ioredis": "^5.4.1"
},
"devDependencies": {
"@types/node": "^20.14.0",
"tsx": "^4.15.0",
"typescript": "^5.4.5"
}
}
+58
View File
@@ -0,0 +1,58 @@
import { existsSync, readFileSync } from 'node:fs';
import { resolve, join } from 'node:path';
import type { DomainConfig } from '../types.js';
const DOMAINS_DIR = resolve(
process.env['DOMAINS_CONFIG_PATH'] ?? join(process.cwd(), '..', 'config', 'domains'),
);
const config_cache = new Map<string, DomainConfig>();
function load_domain_file(host: string): DomainConfig | null {
const file_path = join(DOMAINS_DIR, `${host}.json`);
if (!existsSync(file_path)) return null;
try {
const raw = readFileSync(file_path, 'utf-8');
return JSON.parse(raw) as DomainConfig;
} catch (err) {
throw new Error(`Failed to parse domain config for "${host}": ${(err as Error).message}`);
}
}
/**
* Resolve and return the DomainConfig for a given Host header value.
* Falls back to DEFAULT_HOST (env) then "localhost" if no match found.
*
* Configs are cached in-process after first read; restart bridge to reload.
*/
export function get_domain_config(host_header: string): DomainConfig {
// Strip port number (e.g. "localhost:3200" → "localhost")
const host = host_header.replace(/:\d+$/, '').toLowerCase();
const cached = config_cache.get(host);
if (cached) return cached;
const config = load_domain_file(host);
if (config) {
config_cache.set(host, config);
return config;
}
// Fall back to DEFAULT_HOST
const default_host = (process.env['DEFAULT_HOST'] ?? 'localhost').toLowerCase();
if (host !== default_host) {
const fallback = get_domain_config(default_host);
config_cache.set(host, fallback);
return fallback;
}
throw new Error(
`No domain config found for "${host}" and no fallback available. ` +
`Expected file: ${join(DOMAINS_DIR, `${host}.json`)}`,
);
}
/** Clear the in-process config cache (useful in tests). */
export function clear_domain_cache(): void {
config_cache.clear();
}
+136
View File
@@ -0,0 +1,136 @@
import type { FastifyInstance, FastifyRequest } from 'fastify';
import { get_domain_config } from '../config/domain.js';
import { WpClient } from '../services/wp-client.js';
import { swr_fetch } from '../services/cache.js';
import type { ArticleListItem, PaginatedResponse } from '../types.js';
type ArticleListQuery = {
category?: string;
page?: string;
per_page?: string;
search?: string;
};
type SlugParams = {
slug: string;
};
type RelatedQuery = {
limit?: string;
};
async function resolve_category_id(
client: WpClient,
category_slug: string,
cache_key_prefix: string,
): Promise<number | undefined> {
try {
const cats = await swr_fetch(`${cache_key_prefix}:categories:all`, () => client.get_categories());
const match = cats.find(c => c.slug === category_slug);
return match?.id;
} catch {
return undefined;
}
}
export async function articles_routes(app: FastifyInstance): Promise<void> {
// GET /articles — paginated list, optional category/search filter
app.get(
'/articles',
async (req: FastifyRequest<{ Querystring: ArticleListQuery }>, reply) => {
const host = req.hostname ?? 'localhost';
const config = get_domain_config(host);
const client = new WpClient(config.wp_endpoint);
const cache_prefix = `${host}:wp`;
const page = parseInt(req.query.page ?? '1', 10);
const per_page = Math.min(parseInt(req.query.per_page ?? '12', 10), 100);
const search = req.query.search;
let categories: number | undefined;
if (req.query.category) {
categories = await resolve_category_id(client, req.query.category, cache_prefix);
}
const cache_key = `${cache_prefix}:posts:p${page}:pp${per_page}:cat${categories ?? ''}:q${search ?? ''}`;
const result = await swr_fetch<PaginatedResponse<ArticleListItem>>(
cache_key,
async () => {
const { items, total } = await client.get_posts({ page, per_page, categories, search });
return {
items,
total,
page,
per_page,
total_pages: Math.ceil(total / per_page),
};
},
);
return reply.send(result);
},
);
// GET /articles/:slug — single article
app.get(
'/articles/:slug',
async (req: FastifyRequest<{ Params: SlugParams }>, reply) => {
const host = req.hostname ?? 'localhost';
const config = get_domain_config(host);
const client = new WpClient(config.wp_endpoint);
const { slug } = req.params;
const article = await swr_fetch(
`${host}:wp:post:${slug}`,
() => client.get_post_by_slug(slug),
);
return reply.send(article);
},
);
// GET /articles/:slug/related — related articles (same category, excluding current)
app.get(
'/articles/:slug/related',
async (req: FastifyRequest<{ Params: SlugParams; Querystring: RelatedQuery }>, reply) => {
const host = req.hostname ?? 'localhost';
const config = get_domain_config(host);
const client = new WpClient(config.wp_endpoint);
const { slug } = req.params;
const limit = Math.min(parseInt(req.query.limit ?? '4', 10), 10);
// Fetch the article first to get its category
const article = await swr_fetch(
`${host}:wp:post:${slug}`,
() => client.get_post_by_slug(slug),
);
const related = await swr_fetch<ArticleListItem[]>(
`${host}:wp:related:${slug}:${limit}`,
async () => {
const posts = await client.get_posts_by_category_id(article.category.id, limit + 1);
return posts.filter(p => p.slug !== slug).slice(0, limit);
},
);
return reply.send(related);
},
);
// GET /api/posts — alias for /articles (issue-spec route)
app.get(
'/api/posts',
async (req: FastifyRequest<{ Querystring: ArticleListQuery }>, reply) => {
return reply.redirect(`/articles?${new URLSearchParams(req.query as Record<string, string>).toString()}`);
},
);
// GET /api/posts/:slug — alias for /articles/:slug
app.get(
'/api/posts/:slug',
async (req: FastifyRequest<{ Params: SlugParams }>, reply) => {
return reply.redirect(`/articles/${req.params.slug}`);
},
);
}
+116
View File
@@ -0,0 +1,116 @@
import type { FastifyInstance, FastifyRequest } from 'fastify';
import { get_domain_config } from '../config/domain.js';
import { WpClient } from '../services/wp-client.js';
import { swr_fetch } from '../services/cache.js';
import type { ArticleListItem, PaginatedResponse } from '../types.js';
type SlugParams = {
slug: string;
};
type CategoryPostsQuery = {
page?: string;
per_page?: string;
};
export async function categories_routes(app: FastifyInstance): Promise<void> {
// GET /categories — all categories
app.get('/categories', async (req: FastifyRequest, reply) => {
const host = req.hostname ?? 'localhost';
const config = get_domain_config(host);
const client = new WpClient(config.wp_endpoint);
const categories = await swr_fetch(
`${host}:wp:categories:all`,
() => client.get_categories(),
);
return reply.send(categories);
});
// GET /categories/:slug — single category + its posts
app.get(
'/categories/:slug',
async (req: FastifyRequest<{ Params: SlugParams; Querystring: CategoryPostsQuery }>, reply) => {
const host = req.hostname ?? 'localhost';
const config = get_domain_config(host);
const client = new WpClient(config.wp_endpoint);
const { slug } = req.params;
const page = parseInt(req.query.page ?? '1', 10);
const per_page = Math.min(parseInt(req.query.per_page ?? '12', 10), 100);
const category = await swr_fetch(
`${host}:wp:category:${slug}`,
() => client.get_category_by_slug(slug),
);
const posts_result = await swr_fetch<PaginatedResponse<ArticleListItem>>(
`${host}:wp:category:${slug}:posts:p${page}:pp${per_page}`,
async () => {
const { items, total } = await client.get_posts({
page,
per_page,
categories: category.id,
});
return {
items,
total,
page,
per_page,
total_pages: Math.ceil(total / per_page),
};
},
);
return reply.send({ ...category, posts: posts_result });
},
);
// GET /api/categories and /api/categories/:slug — aliases per issue spec
app.get('/api/categories', async (req: FastifyRequest, reply) => {
return reply.redirect('/categories');
});
app.get(
'/api/categories/:slug',
async (req: FastifyRequest<{ Params: SlugParams }>, reply) => {
return reply.redirect(`/categories/${req.params.slug}`);
},
);
// GET /api/tags — all tags
app.get('/api/tags', async (req: FastifyRequest, reply) => {
const host = req.hostname ?? 'localhost';
const config = get_domain_config(host);
const client = new WpClient(config.wp_endpoint);
const tags = await swr_fetch(
`${host}:wp:tags:all`,
() => client.get_tags(),
);
return reply.send(tags);
});
// GET /api/media/:id — image metadata
app.get(
'/api/media/:id',
async (req: FastifyRequest<{ Params: { id: string } }>, reply) => {
const host = req.hostname ?? 'localhost';
const config = get_domain_config(host);
const client = new WpClient(config.wp_endpoint);
const media_id = parseInt(req.params.id, 10);
if (isNaN(media_id) || media_id <= 0) {
return reply.code(400).send({ error: 'Invalid media ID' });
}
const media = await swr_fetch(
`${host}:wp:media:${media_id}`,
() => client.get_media(media_id),
);
return reply.send(media);
},
);
}
+7
View File
@@ -0,0 +1,7 @@
import type { FastifyInstance } from 'fastify';
export async function health_routes(app: FastifyInstance): Promise<void> {
app.get('/health', async (_req, reply) => {
return reply.send({ status: 'ok', timestamp: new Date().toISOString() });
});
}
+94
View File
@@ -0,0 +1,94 @@
import type { FastifyInstance, FastifyRequest } from 'fastify';
import { get_domain_config } from '../config/domain.js';
import { WpClient } from '../services/wp-client.js';
import { swr_fetch } from '../services/cache.js';
import type { ArticleListItem, HomepageData } from '../types.js';
// Number of articles per section
const HERO_COUNT = 3;
const TRENDING_COUNT = 5;
const FEATURED_COUNT = 4;
const LATEST_COUNT = 12;
const BY_CATEGORY_COUNT = 4;
export async function homepage_routes(app: FastifyInstance): Promise<void> {
app.get('/homepage', async (req: FastifyRequest, reply) => {
const host = req.hostname ?? 'localhost';
const config = get_domain_config(host);
const client = new WpClient(config.wp_endpoint);
const data = await swr_fetch<HomepageData>(
`${host}:homepage`,
async () => {
// Fetch in parallel where possible
const [sticky_posts, latest_result, categories_list] = await Promise.all([
client.get_sticky_posts(HERO_COUNT).catch((): ArticleListItem[] => []),
client.get_posts({ per_page: LATEST_COUNT + TRENDING_COUNT }),
client.get_categories().catch(() => []),
]);
const all_latest = latest_result.items;
// Hero = sticky posts (or first N from latest if none)
const hero = sticky_posts.length >= HERO_COUNT
? sticky_posts.slice(0, HERO_COUNT)
: [...sticky_posts, ...all_latest.slice(0, HERO_COUNT - sticky_posts.length)];
// Trending = most recent posts marked is_trending (first N for now; can swap with view-count logic later)
const trending: ArticleListItem[] = all_latest
.slice(0, TRENDING_COUNT)
.map(p => ({ ...p, is_trending: true }));
// Featured = first FEATURED_COUNT from latest
const featured: ArticleListItem[] = all_latest.slice(0, FEATURED_COUNT).map(p => ({ ...p, is_featured: true }));
// Latest = all fetched
const latest = all_latest.slice(0, LATEST_COUNT);
// Per-category sections using domain config categories
const category_slugs = config.categories.map(c => c.slug);
const by_category: Record<string, ArticleListItem[]> = {};
const category_posts = await Promise.allSettled(
category_slugs.map(async (slug) => {
const cat = categories_list.find(c => c.slug === slug);
if (!cat) return { slug, items: [] as ArticleListItem[] };
const items = await client.get_posts_by_category_id(cat.id, BY_CATEGORY_COUNT);
return { slug, items };
}),
);
for (const result of category_posts) {
if (result.status === 'fulfilled') {
by_category[result.value.slug] = result.value.items;
}
}
return { hero, trending, featured, latest, by_category };
},
);
return reply.send(data);
});
// GET /trending — convenience endpoint
app.get(
'/trending',
async (req: FastifyRequest<{ Querystring: { limit?: string } }>, reply) => {
const host = req.hostname ?? 'localhost';
const config = get_domain_config(host);
const client = new WpClient(config.wp_endpoint);
const limit = Math.min(parseInt(req.query.limit ?? '5', 10), 20);
const items = await swr_fetch<ArticleListItem[]>(
`${host}:trending:${limit}`,
async () => {
const { items: posts } = await client.get_posts({ per_page: limit });
return posts.map(p => ({ ...p, is_trending: true }));
},
);
return reply.send(items);
},
);
}
+10
View File
@@ -0,0 +1,10 @@
import type { FastifyInstance, FastifyRequest } from 'fastify';
import { get_domain_config } from '../config/domain.js';
export async function site_config_routes(app: FastifyInstance): Promise<void> {
app.get('/api/site-config', async (req: FastifyRequest, reply) => {
const host = req.hostname ?? 'localhost';
const config = get_domain_config(host);
return reply.send(config);
});
}
+74
View File
@@ -0,0 +1,74 @@
import Fastify from 'fastify';
import cors from '@fastify/cors';
import rate_limit from '@fastify/rate-limit';
import { health_routes } from './routes/health.js';
import { site_config_routes } from './routes/site-config.js';
import { articles_routes } from './routes/articles.js';
import { categories_routes } from './routes/categories.js';
import { homepage_routes } from './routes/homepage.js';
const PORT = parseInt(process.env['PORT'] ?? '3200', 10);
const LOG_LEVEL = process.env['LOG_LEVEL'] ?? 'info';
const app = Fastify({
logger: {
level: LOG_LEVEL,
transport: process.env['NODE_ENV'] !== 'production'
? { target: 'pino-pretty', options: { colorize: true } }
: undefined,
},
disableRequestLogging: false,
});
await app.register(cors, { origin: true });
await app.register(rate_limit, {
global: true,
max: parseInt(process.env['RATE_LIMIT_MAX'] ?? '100', 10),
timeWindow: parseInt(process.env['RATE_LIMIT_WINDOW_MS'] ?? '60000', 10),
keyGenerator: (req) => req.ip,
});
// Global error handler — map known error types to HTTP status codes
app.setErrorHandler((err, req, reply) => {
const msg = err.message ?? 'Internal server error';
const is_not_found = msg.includes('not found') || msg.includes('Not Found');
const is_wp_down = msg.startsWith('WP API') || err.name === 'TimeoutError' || msg.includes('fetch failed');
if (is_not_found) {
return reply.code(404).send({ error: msg });
}
if (is_wp_down) {
app.log.warn({ url: req.url, err: msg }, 'WP upstream unavailable');
return reply.code(503).send({ error: 'Upstream unavailable', detail: msg });
}
if (err.statusCode && err.statusCode < 500) {
return reply.code(err.statusCode).send({ error: msg });
}
app.log.error({ url: req.url, err }, 'Unhandled error');
return reply.code(500).send({ error: 'Internal server error' });
});
// Register route plugins
await app.register(health_routes);
await app.register(site_config_routes);
await app.register(articles_routes);
await app.register(categories_routes);
await app.register(homepage_routes);
// 404 fallback
app.setNotFoundHandler((_req, reply) => {
return reply.code(404).send({ error: 'Route not found' });
});
try {
await app.listen({ port: PORT, host: '0.0.0.0' });
app.log.info(`Bridge API running on port ${PORT}`);
} catch (err) {
app.log.error(err);
process.exit(1);
}
+139
View File
@@ -0,0 +1,139 @@
import { Redis } from 'ioredis';
interface CacheEntry {
data: unknown;
stale_at: number;
expires_at: number;
}
const FRESH_TTL_MS = (parseInt(process.env['CACHE_FRESH_TTL'] ?? '60', 10)) * 1000;
const STALE_TTL_MS = (parseInt(process.env['CACHE_STALE_TTL'] ?? '300', 10)) * 1000;
// In-process fallback map (used when Redis is unavailable or not configured)
const local_map = new Map<string, CacheEntry>();
let redis_client: Redis | null = null;
function get_redis(): Redis | null {
const url = process.env['REDIS_URL'];
if (!url) return null;
if (redis_client) return redis_client;
redis_client = new Redis(url, {
lazyConnect: true,
enableOfflineQueue: false,
maxRetriesPerRequest: 1,
});
redis_client.on('error', (err: Error) => {
// Log but do not crash — fall back to local cache
console.error('[cache] Redis error, falling back to in-process cache:', err.message);
});
return redis_client;
}
async function read_redis(key: string): Promise<CacheEntry | null> {
const redis = get_redis();
if (!redis) return null;
try {
const raw = await redis.get(key);
if (!raw) return null;
return JSON.parse(raw) as CacheEntry;
} catch {
return null;
}
}
async function write_redis(key: string, entry: CacheEntry): Promise<void> {
const redis = get_redis();
if (!redis) return;
try {
const ttl_seconds = Math.ceil((entry.expires_at - Date.now()) / 1000);
if (ttl_seconds <= 0) return;
await redis.set(key, JSON.stringify(entry), 'EX', ttl_seconds);
} catch {
// ignore write failures
}
}
async function read_local(key: string): Promise<CacheEntry | null> {
return local_map.get(key) ?? null;
}
function write_local(key: string, entry: CacheEntry): void {
local_map.set(key, entry);
}
async function get_entry(key: string): Promise<CacheEntry | null> {
const redis_entry = await read_redis(key);
if (redis_entry) return redis_entry;
return read_local(key);
}
async function set_entry(key: string, data: unknown): Promise<void> {
const now = Date.now();
const entry: CacheEntry = {
data,
stale_at: now + FRESH_TTL_MS,
expires_at: now + STALE_TTL_MS,
};
write_local(key, entry);
await write_redis(key, entry);
}
/**
* Stale-while-revalidate cache.
*
* - Returns fresh data immediately if available.
* - Returns stale data and revalidates in the background if TTL exceeded but hard-expiry not reached.
* - Fetches synchronously if cold or hard-expired.
* - On fetch error, returns last known stale value (serve from cache) or throws.
*/
export async function swr_fetch<T>(
key: string,
fetcher: () => Promise<T>,
): Promise<T> {
const now = Date.now();
const entry = await get_entry(key);
if (entry && now < entry.stale_at) {
return entry.data as T;
}
if (entry && now < entry.expires_at) {
// Revalidate in background; return stale immediately
revalidate(key, fetcher).catch(() => null);
return entry.data as T;
}
return revalidate<T>(key, fetcher, entry);
}
async function revalidate<T>(
key: string,
fetcher: () => Promise<T>,
stale_entry?: CacheEntry | null,
): Promise<T> {
try {
const data = await fetcher();
await set_entry(key, data);
return data;
} catch (err) {
if (stale_entry) {
// WP is down but we have something in cache — serve it
return stale_entry.data as T;
}
throw err;
}
}
/** Invalidate a key from all layers. */
export async function cache_invalidate(key: string): Promise<void> {
local_map.delete(key);
const redis = get_redis();
if (redis) {
try { await redis.del(key); } catch { /* ignore */ }
}
}
+195
View File
@@ -0,0 +1,195 @@
import type {
Article,
ArticleListItem,
Author,
Category,
Tag,
WpMedia,
WpPost,
WpTerm,
WpUser,
} from '../types.js';
const EMBED = '_embed=wp:featuredmedia,author,wp:term';
function strip_html(html: string): string {
return html.replace(/<[^>]+>/g, '').replace(/&[a-z]+;/gi, ' ').trim();
}
function estimate_reading_time(html: string): number {
const words = strip_html(html).split(/\s+/).filter(Boolean).length;
return Math.max(1, Math.round(words / 200));
}
function pick_image_url(media: WpMedia): string {
const sizes = media.media_details?.sizes ?? {};
return (
sizes['medium_large']?.source_url ??
sizes['large']?.source_url ??
sizes['medium']?.source_url ??
media.source_url
);
}
function normalize_author(user?: WpUser): Author {
if (!user) {
return { id: 0, name: 'Unknown', slug: 'unknown', avatar: null };
}
const avatars = user.avatar_urls ?? {};
const avatar = avatars['96'] ?? avatars['48'] ?? null;
return { id: user.id, name: user.name, slug: user.slug, avatar };
}
function normalize_category(term?: WpTerm): Category {
if (!term) {
return { id: 0, slug: 'uncategorised', name: 'Uncategorised', description: '', count: 0 };
}
return {
id: term.id,
slug: term.slug,
name: term.name,
description: strip_html(term.description),
count: term.count,
};
}
function normalize_tag(term: WpTerm): Tag {
return { id: term.id, slug: term.slug, name: term.name };
}
function normalize_post_list_item(post: WpPost): ArticleListItem {
const author = normalize_author(post._embedded?.author?.[0]);
// wp:term[0] = categories, wp:term[1] = tags
const category_terms = post._embedded?.['wp:term']?.[0] ?? [];
const category = normalize_category(category_terms[0]);
let featured_image: string | null = null;
let featured_image_alt = '';
const media = post._embedded?.['wp:featuredmedia']?.[0];
if (media && media.source_url) {
featured_image = pick_image_url(media);
featured_image_alt = media.alt_text || strip_html(post.title.rendered);
}
return {
id: post.id,
slug: post.slug,
title: strip_html(post.title.rendered),
excerpt: strip_html(post.excerpt.rendered),
featured_image,
featured_image_alt,
author,
category,
published_at: post.date,
reading_time: estimate_reading_time(post.content.rendered),
is_featured: post.sticky,
is_trending: false, // determined by call-site / view count; WP has no native field
};
}
function normalize_post(post: WpPost): Article {
const list_item = normalize_post_list_item(post);
const tag_terms = post._embedded?.['wp:term']?.[1] ?? [];
const tags: Tag[] = tag_terms.map(normalize_tag);
return {
...list_item,
content: post.content.rendered,
updated_at: post.modified,
tags,
};
}
export class WpClient {
private readonly base: string;
constructor(wp_endpoint: string) {
// wp_endpoint from config is e.g. "http://localhost:8080/wp-json"
this.base = wp_endpoint.replace(/\/$/, '');
}
private async fetch_json<T>(path: string): Promise<{ data: T; headers: Headers }> {
const url = `${this.base}${path}`;
const res = await fetch(url, {
headers: { Accept: 'application/json' },
signal: AbortSignal.timeout(8000),
});
if (!res.ok) {
throw new Error(`WP API ${res.status} ${res.statusText}: ${url}`);
}
const data = (await res.json()) as T;
return { data, headers: res.headers };
}
async get_posts(params: {
page?: number;
per_page?: number;
categories?: number;
search?: string;
} = {}): Promise<{ items: ArticleListItem[]; total: number }> {
const qs = new URLSearchParams({ [EMBED]: '' });
if (params.page) qs.set('page', String(params.page));
if (params.per_page) qs.set('per_page', String(params.per_page));
if (params.categories) qs.set('categories', String(params.categories));
if (params.search) qs.set('search', params.search);
const path = `/wp/v2/posts?${qs.toString().replace('%3D=', '=')}`;
const { data, headers } = await this.fetch_json<WpPost[]>(path);
const total = parseInt(headers.get('x-wp-total') ?? '0', 10);
return { items: data.map(normalize_post_list_item), total };
}
async get_post_by_slug(slug: string): Promise<Article> {
const qs = new URLSearchParams({ slug, [EMBED]: '' });
const path = `/wp/v2/posts?${qs.toString().replace('%3D=', '=')}`;
const { data } = await this.fetch_json<WpPost[]>(path);
const post = data[0];
if (!post) throw new Error(`Post not found: ${slug}`);
return normalize_post(post);
}
async get_categories(): Promise<Category[]> {
const { data } = await this.fetch_json<WpTerm[]>('/wp/v2/categories?per_page=100&hide_empty=true');
return data.map(normalize_category);
}
async get_category_by_slug(slug: string): Promise<Category> {
const { data } = await this.fetch_json<WpTerm[]>(`/wp/v2/categories?slug=${encodeURIComponent(slug)}`);
const term = data[0];
if (!term) throw new Error(`Category not found: ${slug}`);
return normalize_category(term);
}
async get_tags(): Promise<Tag[]> {
const { data } = await this.fetch_json<WpTerm[]>('/wp/v2/tags?per_page=100&hide_empty=true');
return data.map(normalize_tag);
}
async get_media(id: number): Promise<WpMedia> {
const { data } = await this.fetch_json<WpMedia>(`/wp/v2/media/${id}`);
return data;
}
async get_sticky_posts(limit = 3): Promise<ArticleListItem[]> {
const qs = new URLSearchParams({ sticky: 'true', per_page: String(limit), [EMBED]: '' });
const path = `/wp/v2/posts?${qs.toString().replace('%3D=', '=')}`;
const { data } = await this.fetch_json<WpPost[]>(path);
return data.map(p => ({ ...normalize_post_list_item(p), is_featured: true }));
}
async get_posts_by_category_id(
category_id: number,
per_page = 4,
): Promise<ArticleListItem[]> {
const qs = new URLSearchParams({
categories: String(category_id),
per_page: String(per_page),
[EMBED]: '',
});
const path = `/wp/v2/posts?${qs.toString().replace('%3D=', '=')}`;
const { data } = await this.fetch_json<WpPost[]>(path);
return data.map(normalize_post_list_item);
}
}
+127
View File
@@ -0,0 +1,127 @@
export interface DomainConfig {
site_name: string;
tagline: string;
theme: string;
logo: string;
favicon: string;
primary_color: string;
secondary_color: string;
accent_color: string;
categories: CategoryConfig[];
bridge_endpoint: string;
wp_endpoint: string;
locale: string;
timezone: string;
ads_enabled: boolean;
analytics_id: string | null;
}
export interface CategoryConfig {
slug: string;
label: string;
}
export interface Author {
id: number;
name: string;
slug: string;
avatar: string | null;
}
export interface Category {
id: number;
slug: string;
name: string;
description: string;
count: number;
}
export interface Tag {
id: number;
slug: string;
name: string;
}
export interface ArticleListItem {
id: number;
slug: string;
title: string;
excerpt: string;
featured_image: string | null;
featured_image_alt: string;
author: Author;
category: Category;
published_at: string;
reading_time: number;
is_featured: boolean;
is_trending: boolean;
}
export interface Article extends ArticleListItem {
content: string;
updated_at: string;
tags: Tag[];
}
export interface PaginatedResponse<T> {
items: T[];
total: number;
page: number;
per_page: number;
total_pages: number;
}
export interface HomepageData {
hero: ArticleListItem[];
trending: ArticleListItem[];
featured: ArticleListItem[];
latest: ArticleListItem[];
by_category: Record<string, ArticleListItem[]>;
}
// Raw WordPress REST API types (minimal subset we use)
export interface WpPost {
id: number;
date: string;
modified: string;
slug: string;
status: string;
title: { rendered: string };
excerpt: { rendered: string };
content: { rendered: string };
featured_media: number;
sticky: boolean;
categories: number[];
tags: number[];
_embedded?: {
author?: WpUser[];
'wp:term'?: WpTerm[][];
'wp:featuredmedia'?: WpMedia[];
};
}
export interface WpUser {
id: number;
name: string;
slug: string;
avatar_urls?: Record<string, string>;
}
export interface WpTerm {
id: number;
link: string;
name: string;
slug: string;
taxonomy: string;
description: string;
count: number;
}
export interface WpMedia {
id: number;
source_url: string;
alt_text: string;
media_details?: {
sizes?: Record<string, { source_url: string }>;
};
}
+18
View File
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
+23
View File
@@ -0,0 +1,23 @@
{
"site_name": "Sports News (Dev)",
"tagline": "The latest sports news, live scores and transfers",
"theme": "sports",
"logo": "/assets/logo.svg",
"favicon": "/favicon.svg",
"primary_color": "#e63946",
"secondary_color": "#1d3557",
"accent_color": "#f1faee",
"categories": [
{ "slug": "football", "label": "Football" },
{ "slug": "basketball", "label": "Basketball" },
{ "slug": "formula1", "label": "Formula 1" },
{ "slug": "tennis", "label": "Tennis" },
{ "slug": "mma", "label": "MMA" }
],
"bridge_endpoint": "http://localhost:3200",
"wp_endpoint": "http://localhost:8080/wp-json",
"locale": "en-US",
"timezone": "Europe/Lisbon",
"ads_enabled": false,
"analytics_id": null
}