|
| 1 | +import type { |
| 2 | + APIGatewayProxyEventV2, |
| 3 | + APIGatewayProxyStructuredResultV2, |
| 4 | + Context, |
| 5 | +} from 'aws-lambda' |
| 6 | +import type { MiddlewareObj } from '@middy/core' |
| 7 | +import type { Static, TSchema } from '@sinclair/typebox' |
| 8 | +import { |
| 9 | + formatTypeBoxErrors, |
| 10 | + validateWithTypeBox, |
| 11 | +} from '@hello.nrfcloud.com/proto' |
| 12 | +import { HttpStatusCode } from '@hello.nrfcloud.com/proto/hello' |
| 13 | +import { tryAsJSON } from '../tryAsJSON.js' |
| 14 | +import { aProblem } from '../aProblem.js' |
| 15 | + |
| 16 | +export const validateInput = <Schema extends TSchema>( |
| 17 | + schema: Schema, |
| 18 | + mapInput?: (e: APIGatewayProxyEventV2) => unknown, |
| 19 | +): MiddlewareObj< |
| 20 | + APIGatewayProxyEventV2, |
| 21 | + APIGatewayProxyStructuredResultV2, |
| 22 | + Error, |
| 23 | + Context & ValidInput<Schema> |
| 24 | +> => { |
| 25 | + const v = validateWithTypeBox(schema) |
| 26 | + return { |
| 27 | + before: async (req) => { |
| 28 | + let reqBody = {} |
| 29 | + if ( |
| 30 | + (req.event.headers?.['content-type'] ?? '').includes( |
| 31 | + 'application/json', |
| 32 | + ) && |
| 33 | + parseInt(req.event.headers?.['content-length'] ?? '0', 10) > 0 |
| 34 | + ) { |
| 35 | + reqBody = tryAsJSON(req.event.body) ?? {} |
| 36 | + } |
| 37 | + const input = mapInput?.(req.event) ?? { |
| 38 | + ...(req.event.pathParameters ?? {}), |
| 39 | + ...(req.event.queryStringParameters ?? {}), |
| 40 | + ...reqBody, |
| 41 | + } |
| 42 | + console.debug(`[validateInput]`, 'input', JSON.stringify(input)) |
| 43 | + const maybeValidInput = v(input) |
| 44 | + if ('errors' in maybeValidInput) { |
| 45 | + console.debug( |
| 46 | + `[validateInput]`, |
| 47 | + `Input not valid`, |
| 48 | + JSON.stringify(maybeValidInput.errors), |
| 49 | + ) |
| 50 | + return aProblem({ |
| 51 | + title: 'Validation failed', |
| 52 | + status: HttpStatusCode.BAD_REQUEST, |
| 53 | + detail: formatTypeBoxErrors(maybeValidInput.errors), |
| 54 | + }) |
| 55 | + } |
| 56 | + console.debug(`[validateInput]`, `Input valid`) |
| 57 | + req.context.validInput = maybeValidInput.value |
| 58 | + return undefined |
| 59 | + }, |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +export type ValidInput<Schema extends TSchema> = { |
| 64 | + validInput: Static<Schema> |
| 65 | +} |
0 commit comments