|
| 1 | +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +import { type Router, type Request, type Response, type NextFunction, Router as createRouter } from 'express'; |
| 4 | +import { type ObjectKernel, HttpDispatcher, HttpDispatcherResult } from '@objectstack/runtime'; |
| 5 | + |
| 6 | +export interface ExpressAdapterOptions { |
| 7 | + kernel: ObjectKernel; |
| 8 | + prefix?: string; |
| 9 | +} |
| 10 | + |
| 11 | +/** |
| 12 | + * Auth service interface with handleRequest method |
| 13 | + */ |
| 14 | +interface AuthService { |
| 15 | + handleRequest(request: Request): Promise<globalThis.Response>; |
| 16 | +} |
| 17 | + |
| 18 | +/** |
| 19 | + * Creates an Express Router with all ObjectStack route dispatchers. |
| 20 | + * Provides Auth, GraphQL, Metadata, Data, and Storage routes. |
| 21 | + * |
| 22 | + * @example |
| 23 | + * ```ts |
| 24 | + * import express from 'express'; |
| 25 | + * import { createExpressRouter } from '@objectstack/express'; |
| 26 | + * |
| 27 | + * const app = express(); |
| 28 | + * app.use('/api', createExpressRouter({ kernel })); |
| 29 | + * app.listen(3000); |
| 30 | + * ``` |
| 31 | + */ |
| 32 | +export function createExpressRouter(options: ExpressAdapterOptions): Router { |
| 33 | + const router = createRouter(); |
| 34 | + const dispatcher = new HttpDispatcher(options.kernel); |
| 35 | + const prefix = options.prefix || '/api'; |
| 36 | + |
| 37 | + const sendResult = (result: HttpDispatcherResult, res: Response) => { |
| 38 | + if (result.handled) { |
| 39 | + if (result.response) { |
| 40 | + if (result.response.headers) { |
| 41 | + Object.entries(result.response.headers).forEach(([k, v]) => res.set(k, v as string)); |
| 42 | + } |
| 43 | + return res.status(result.response.status).json(result.response.body); |
| 44 | + } |
| 45 | + if (result.result) { |
| 46 | + const response = result.result; |
| 47 | + if (response.type === 'redirect' && response.url) { |
| 48 | + return res.redirect(response.url); |
| 49 | + } |
| 50 | + if (response.type === 'stream' && response.stream) { |
| 51 | + if (response.headers) { |
| 52 | + Object.entries(response.headers).forEach(([k, v]) => res.set(k, v as string)); |
| 53 | + } |
| 54 | + response.stream.pipe(res); |
| 55 | + return; |
| 56 | + } |
| 57 | + return res.status(200).json(response); |
| 58 | + } |
| 59 | + } |
| 60 | + return res.status(404).json({ success: false, error: { message: 'Not Found', code: 404 } }); |
| 61 | + }; |
| 62 | + |
| 63 | + const errorResponse = (err: any, res: Response) => { |
| 64 | + return res.status(err.statusCode || 500).json({ |
| 65 | + success: false, |
| 66 | + error: { |
| 67 | + message: err.message || 'Internal Server Error', |
| 68 | + code: err.statusCode || 500, |
| 69 | + }, |
| 70 | + }); |
| 71 | + }; |
| 72 | + |
| 73 | + // --- Discovery --- |
| 74 | + router.get('/', (_req: Request, res: Response) => { |
| 75 | + res.json({ data: dispatcher.getDiscoveryInfo(prefix) }); |
| 76 | + }); |
| 77 | + |
| 78 | + // --- Auth --- |
| 79 | + router.all('/auth/{*path}', async (req: Request, res: Response) => { |
| 80 | + try { |
| 81 | + const path = (req.params as any).path; |
| 82 | + const method = req.method; |
| 83 | + |
| 84 | + // Try AuthPlugin service first |
| 85 | + const authService = typeof options.kernel.getService === 'function' |
| 86 | + ? options.kernel.getService<AuthService>('auth') |
| 87 | + : null; |
| 88 | + |
| 89 | + if (authService && typeof authService.handleRequest === 'function') { |
| 90 | + const protocol = req.protocol || 'http'; |
| 91 | + const host = req.get?.('host') || req.headers?.host || 'localhost'; |
| 92 | + const url = `${protocol}://${host}${req.originalUrl || req.url}`; |
| 93 | + const headers = new Headers(); |
| 94 | + if (req.headers) { |
| 95 | + Object.entries(req.headers).forEach(([k, v]) => { |
| 96 | + if (typeof v === 'string') headers.set(k, v); |
| 97 | + else if (Array.isArray(v)) headers.set(k, v.join(', ')); |
| 98 | + }); |
| 99 | + } |
| 100 | + const init: RequestInit = { method, headers }; |
| 101 | + if (method !== 'GET' && method !== 'HEAD' && req.body) { |
| 102 | + init.body = JSON.stringify(req.body); |
| 103 | + if (!headers.has('content-type')) { |
| 104 | + headers.set('content-type', 'application/json'); |
| 105 | + } |
| 106 | + } |
| 107 | + const webRequest = new Request(url, init); |
| 108 | + const response = await authService.handleRequest(webRequest); |
| 109 | + res.status(response.status); |
| 110 | + response.headers.forEach((v: string, k: string) => res.set(k, v)); |
| 111 | + const text = await response.text(); |
| 112 | + return res.send(text); |
| 113 | + } |
| 114 | + |
| 115 | + // Fallback to dispatcher |
| 116 | + const body = method === 'GET' || method === 'HEAD' ? {} : req.body || {}; |
| 117 | + const result = await dispatcher.handleAuth(path, method, body, { request: req, response: res }); |
| 118 | + return sendResult(result, res); |
| 119 | + } catch (err: any) { |
| 120 | + return errorResponse(err, res); |
| 121 | + } |
| 122 | + }); |
| 123 | + |
| 124 | + // --- GraphQL --- |
| 125 | + router.post('/graphql', async (req: Request, res: Response) => { |
| 126 | + try { |
| 127 | + const result = await dispatcher.handleGraphQL(req.body, { request: req }); |
| 128 | + return res.json(result); |
| 129 | + } catch (err: any) { |
| 130 | + return errorResponse(err, res); |
| 131 | + } |
| 132 | + }); |
| 133 | + |
| 134 | + // --- Metadata --- |
| 135 | + router.all('/meta/{*path}', async (req: Request, res: Response) => { |
| 136 | + try { |
| 137 | + const subPath = '/' + (req.params as any).path; |
| 138 | + const method = req.method; |
| 139 | + const body = (method === 'PUT' || method === 'POST') ? req.body : undefined; |
| 140 | + const result = await dispatcher.handleMetadata(subPath, { request: req }, method, body); |
| 141 | + return sendResult(result, res); |
| 142 | + } catch (err: any) { |
| 143 | + return errorResponse(err, res); |
| 144 | + } |
| 145 | + }); |
| 146 | + |
| 147 | + router.all('/meta', async (req: Request, res: Response) => { |
| 148 | + try { |
| 149 | + const method = req.method; |
| 150 | + const body = (method === 'PUT' || method === 'POST') ? req.body : undefined; |
| 151 | + const result = await dispatcher.handleMetadata('', { request: req }, method, body); |
| 152 | + return sendResult(result, res); |
| 153 | + } catch (err: any) { |
| 154 | + return errorResponse(err, res); |
| 155 | + } |
| 156 | + }); |
| 157 | + |
| 158 | + // --- Data --- |
| 159 | + router.all('/data/{*path}', async (req: Request, res: Response) => { |
| 160 | + try { |
| 161 | + const subPath = '/' + (req.params as any).path; |
| 162 | + const method = req.method; |
| 163 | + const body = (method === 'POST' || method === 'PATCH') ? req.body : {}; |
| 164 | + const result = await dispatcher.handleData(subPath, method, body, req.query, { request: req }); |
| 165 | + return sendResult(result, res); |
| 166 | + } catch (err: any) { |
| 167 | + return errorResponse(err, res); |
| 168 | + } |
| 169 | + }); |
| 170 | + |
| 171 | + // --- Storage --- |
| 172 | + router.all('/storage/{*path}', async (req: Request, res: Response) => { |
| 173 | + try { |
| 174 | + const subPath = '/' + (req.params as any).path; |
| 175 | + const method = req.method; |
| 176 | + const file = (req as any).file || (req as any).files?.file; |
| 177 | + const result = await dispatcher.handleStorage(subPath, method, file, { request: req }); |
| 178 | + return sendResult(result, res); |
| 179 | + } catch (err: any) { |
| 180 | + return errorResponse(err, res); |
| 181 | + } |
| 182 | + }); |
| 183 | + |
| 184 | + return router; |
| 185 | +} |
| 186 | + |
| 187 | +/** |
| 188 | + * Middleware that attaches the ObjectStack kernel to the request. |
| 189 | + */ |
| 190 | +export function objectStackMiddleware(kernel: ObjectKernel) { |
| 191 | + return (req: Request, _res: Response, next: NextFunction) => { |
| 192 | + (req as any).objectStack = kernel; |
| 193 | + next(); |
| 194 | + }; |
| 195 | +} |
0 commit comments