-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidateResponse.ts
More file actions
53 lines (50 loc) · 1.66 KB
/
validateResponse.ts
File metadata and controls
53 lines (50 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import type middy from '@middy/core'
import {
formatTypeBoxErrors,
validateWithTypeBox,
} from '@nrfcloud/validate-with-typebox'
import type { TSchema } from '@sinclair/typebox'
import type { ValueError } from '@sinclair/typebox/errors'
import { parseHeaders } from './parseHeaders.ts'
import { tryAsJSON } from './tryAsJSON.ts'
import { ValidationFailedError } from './validateInput.ts'
export class ResponseValidationFailedError extends ValidationFailedError {
constructor(errors: ValueError[]) {
super(errors, 'Response validation failed')
this.name = 'ResponseValidationFailedError'
}
}
/**
* Validate responses created with `aResponse`
*/
export const validateResponse = <ResponseSchema extends TSchema>(
schema: ResponseSchema,
): middy.MiddlewareObj => {
const validator = validateWithTypeBox(schema)
return {
after: async (req) => {
const body = req.response?.body
const headers = parseHeaders(req.response.headers)
const contentType = headers.get('content-type') ?? ''
if ((body?.length ?? 0) === 0) {
console.debug(`[validateResponse]`, `Response body is empty`)
}
if ((contentType?.includes('application/json') ?? false) === false) {
console.debug(`[validateResponse]`, `Response body is not JSON`)
}
const maybeValid = validator(tryAsJSON(req.response.body))
if ('errors' in maybeValid) {
console.error(
`[validateResponse]`,
`Response validation failed`,
req.response.body,
formatTypeBoxErrors(maybeValid.errors),
schema.title,
)
throw new ResponseValidationFailedError(maybeValid.errors)
}
console.debug(`[validateResponse]`, `Response is valid`, schema.title)
return undefined
},
}
}