|
| 1 | +import express from 'express' |
| 2 | +import fs from 'fs' |
| 3 | +import path from 'path' |
| 4 | + |
| 5 | +import { getApiResources } from './getApiResources.mjs' |
| 6 | + |
| 7 | +/** |
| 8 | + * Local API runner that mirrors API Gateway + Lambda wiring from the |
| 9 | + * synthesized CDK template. |
| 10 | + */ |
| 11 | +const templateFilePath = process.argv[2] |
| 12 | +if (!templateFilePath) { |
| 13 | + console.error('Please provide the path to the CloudFormation template as a command line argument.') |
| 14 | + process.exit(1) |
| 15 | +} |
| 16 | + |
| 17 | +const stageName = process.env.STAGE_NAME || 'dev' |
| 18 | +const port = parseInt(process.env.API_LOCAL_PORT || '4001', 10) |
| 19 | +const staticConfigPath = path.resolve(process.cwd(), 'static.config.json') |
| 20 | + |
| 21 | +/** |
| 22 | + * Resolves a local `MMT_HOST` value from env or `static.config.json`. |
| 23 | + * `MMT_HOST` is used for browser origin (CORS handling) |
| 24 | + * |
| 25 | + * @returns {string} |
| 26 | + */ |
| 27 | +const resolveMmtHost = () => { |
| 28 | + if (process.env.MMT_HOST) return process.env.MMT_HOST |
| 29 | + |
| 30 | + try { |
| 31 | + const file = fs.readFileSync(staticConfigPath, 'utf8') |
| 32 | + const staticConfig = JSON.parse(file) |
| 33 | + if (staticConfig?.application?.mmtHost) return staticConfig.application.mmtHost |
| 34 | + } catch (error) { |
| 35 | + console.warn(`Unable to read mmtHost from static.config.json: ${error}`) |
| 36 | + } |
| 37 | + |
| 38 | + return 'http://localhost:5173' |
| 39 | +} |
| 40 | + |
| 41 | +const localEnvDefaults = { |
| 42 | + COOKIE_DOMAIN: '.localhost', |
| 43 | + JWT_SECRET: 'local-secret', |
| 44 | + JWT_VALID_TIME: '900', |
| 45 | + MMT_HOST: resolveMmtHost() |
| 46 | +} |
| 47 | + |
| 48 | +// Local stack always runs in offline mode. |
| 49 | +process.env.IS_OFFLINE = 'true' |
| 50 | + |
| 51 | +Object.entries(localEnvDefaults).forEach(([key, value]) => { |
| 52 | + if (!process.env[key]) { |
| 53 | + process.env[key] = value |
| 54 | + } |
| 55 | +}) |
| 56 | + |
| 57 | +const app = express() |
| 58 | + |
| 59 | +/** |
| 60 | + * Adds permissive local CORS behavior for API Gateway emulation. |
| 61 | + * |
| 62 | + * In offline mode we mirror the incoming browser origin so localhost and |
| 63 | + * tunneled origins continue to work with credentials/cookies. |
| 64 | + */ |
| 65 | +app.use((request, response, next) => { |
| 66 | + if (process.env.IS_OFFLINE !== 'true') { |
| 67 | + next() |
| 68 | + |
| 69 | + return |
| 70 | + } |
| 71 | + |
| 72 | + const requestOrigin = request.headers.origin |
| 73 | + const allowOrigin = requestOrigin || process.env.MMT_HOST || 'http://localhost:5173' |
| 74 | + const requestedHeaders = request.headers['access-control-request-headers'] |
| 75 | + |
| 76 | + response.setHeader('Access-Control-Allow-Origin', allowOrigin) |
| 77 | + response.setHeader('Vary', 'Origin') |
| 78 | + response.setHeader('Access-Control-Allow-Credentials', 'true') |
| 79 | + response.setHeader('Access-Control-Allow-Headers', requestedHeaders || 'Content-Type,Authorization,Origin,User-Agent,Accept') |
| 80 | + response.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,PATCH,OPTIONS') |
| 81 | + |
| 82 | + if (request.method === 'OPTIONS') { |
| 83 | + response.status(204).end() |
| 84 | + |
| 85 | + return |
| 86 | + } |
| 87 | + |
| 88 | + next() |
| 89 | +}) |
| 90 | + |
| 91 | +app.use(express.json({ limit: '10mb' })) |
| 92 | +app.use(express.urlencoded({ extended: true })) |
| 93 | + |
| 94 | +/** |
| 95 | + * Wraps a parsed API method definition and invokes its Lambda handler using |
| 96 | + * API Gateway-like event objects. |
| 97 | + * |
| 98 | + * @param {{ httpMethod: string, lambdaFunction: { functionName: string, path: string } }} method |
| 99 | + * @returns {(request: import('express').Request, response: import('express').Response) => Promise<void>} |
| 100 | + */ |
| 101 | +const lambdaProxyWrapper = (method) => async (request, response) => { |
| 102 | + const { lambdaFunction } = method |
| 103 | + const { |
| 104 | + path: handlerPath |
| 105 | + } = lambdaFunction |
| 106 | + |
| 107 | + const event = { |
| 108 | + body: typeof request.body === 'object' ? JSON.stringify(request.body) : request.body, |
| 109 | + headers: request.headers, |
| 110 | + httpMethod: request.method, |
| 111 | + pathParameters: request.params, |
| 112 | + queryStringParameters: request.query, |
| 113 | + requestContext: {} |
| 114 | + } |
| 115 | + |
| 116 | + const { default: handler } = (await import(handlerPath)).default |
| 117 | + const lambdaResponse = await handler(event, {}) |
| 118 | + |
| 119 | + const { |
| 120 | + body, |
| 121 | + headers = {}, |
| 122 | + statusCode = 200 |
| 123 | + } = lambdaResponse || {} |
| 124 | + |
| 125 | + response.status(statusCode) |
| 126 | + Object.entries(headers).forEach(([headerName, headerValue]) => { |
| 127 | + response.setHeader(headerName, headerValue) |
| 128 | + }) |
| 129 | + |
| 130 | + response.send(body) |
| 131 | +} |
| 132 | + |
| 133 | +/** |
| 134 | + * Registers a route on the Express app for the given HTTP method and path. |
| 135 | + * |
| 136 | + * @param {string} httpMethod |
| 137 | + * @param {string} routePath |
| 138 | + * @param {(request: import('express').Request, response: import('express').Response) => Promise<void>} handler |
| 139 | + */ |
| 140 | +const registerRoute = (httpMethod, routePath, handler) => { |
| 141 | + const lowerMethod = httpMethod.toLowerCase() |
| 142 | + app[lowerMethod](routePath, handler) |
| 143 | +} |
| 144 | + |
| 145 | +/** |
| 146 | + * Discovers API routes from the synthesized template and registers |
| 147 | + * stage-prefixed local paths (for example `/dev/users`). |
| 148 | + * |
| 149 | + * @returns {Promise<void>} |
| 150 | + */ |
| 151 | +const addRoutes = async () => { |
| 152 | + const apiResources = getApiResources(templateFilePath) |
| 153 | + const keys = Object.keys(apiResources).sort() |
| 154 | + |
| 155 | + keys.forEach((resourcePath) => { |
| 156 | + const { fullPath, methods } = apiResources[resourcePath] |
| 157 | + |
| 158 | + methods.forEach((method) => { |
| 159 | + const routePath = `/${fullPath.replace(/\/\{(.*?)\}/g, '/:$1')}` |
| 160 | + const stagePath = `/${stageName}${routePath}` |
| 161 | + |
| 162 | + console.log(`Adding route: ${method.httpMethod.padEnd(6)} - ${stagePath}`) |
| 163 | + registerRoute(method.httpMethod, stagePath, lambdaProxyWrapper(method)) |
| 164 | + }) |
| 165 | + }) |
| 166 | +} |
| 167 | + |
| 168 | +/** |
| 169 | + * Boots the local API server after dynamically registering all routes. |
| 170 | + */ |
| 171 | +addRoutes().then(() => { |
| 172 | + app.listen(port, () => { |
| 173 | + console.log(`Local API listening on http://localhost:${port}`) |
| 174 | + }) |
| 175 | +}) |
0 commit comments