|
| 1 | +import '#internal/nitro/virtual/polyfill' |
| 2 | +import type { Handler, HandlerResponse, HandlerContext, HandlerEvent } from '@netlify/functions/dist/main' |
| 3 | +import type { APIGatewayProxyEventHeaders } from 'aws-lambda' |
| 4 | +import { withQuery } from 'ufo' |
| 5 | +import { createRouter as createMatcher } from 'radix3' |
| 6 | +import { nitroApp } from '../app' |
| 7 | +import { useRuntimeConfig } from '../config' |
| 8 | + |
| 9 | +export const handler: Handler = async function handler (event, context) { |
| 10 | + const config = useRuntimeConfig() |
| 11 | + const routerOptions = createMatcher({ routes: config.nitro.routes }) |
| 12 | + |
| 13 | + const query = { ...event.queryStringParameters, ...event.multiValueQueryStringParameters } |
| 14 | + const url = withQuery(event.path, query) |
| 15 | + const routeOptions = routerOptions.lookup(url) || {} |
| 16 | + |
| 17 | + if (routeOptions.static || routeOptions.swr) { |
| 18 | + const builder = await import('@netlify/functions').then(r => r.builder || r.default.builder) |
| 19 | + const ttl = typeof routeOptions.swr === 'number' ? routeOptions.swr : 60 |
| 20 | + const swrHandler = routeOptions.swr |
| 21 | + ? ((event, context) => lambda(event, context).then(r => ({ ...r, ttl }))) as Handler |
| 22 | + : lambda |
| 23 | + return builder(swrHandler)(event, context) as any |
| 24 | + } |
| 25 | + |
| 26 | + return lambda(event, context) |
| 27 | +} |
| 28 | + |
| 29 | +async function lambda (event: HandlerEvent, context: HandlerContext): Promise<HandlerResponse> { |
| 30 | + const query = { ...event.queryStringParameters, ...(event).multiValueQueryStringParameters } |
| 31 | + const url = withQuery((event).path, query) |
| 32 | + const method = (event).httpMethod || 'get' |
| 33 | + |
| 34 | + const r = await nitroApp.localCall({ |
| 35 | + event, |
| 36 | + url, |
| 37 | + context, |
| 38 | + headers: normalizeIncomingHeaders(event.headers), |
| 39 | + method, |
| 40 | + query, |
| 41 | + body: event.body // TODO: handle event.isBase64Encoded |
| 42 | + }) |
| 43 | + |
| 44 | + return { |
| 45 | + statusCode: r.status, |
| 46 | + headers: normalizeOutgoingHeaders(r.headers), |
| 47 | + body: r.body.toString() |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +function normalizeIncomingHeaders (headers?: APIGatewayProxyEventHeaders) { |
| 52 | + return Object.fromEntries(Object.entries(headers || {}).map(([key, value]) => [key.toLowerCase(), value!])) |
| 53 | +} |
| 54 | + |
| 55 | +function normalizeOutgoingHeaders (headers: Record<string, string | string[] | undefined>) { |
| 56 | + return Object.fromEntries(Object.entries(headers) |
| 57 | + .filter(([key]) => !['set-cookie'].includes(key)) |
| 58 | + .map(([k, v]) => [k, Array.isArray(v) ? v.join(',') : v!])) |
| 59 | +} |
0 commit comments