19 lines
533 B
TypeScript
19 lines
533 B
TypeScript
import type { Request } from 'express'
|
|
import { ValidationError } from './errors'
|
|
|
|
export function getRawBodyString(req: Request) {
|
|
if (!Buffer.isBuffer(req.body)) {
|
|
throw new ValidationError('Webhook route must be mounted with express.raw before JSON parsing')
|
|
}
|
|
return req.body.toString('utf8')
|
|
}
|
|
|
|
export function parseRawJsonBody<T = unknown>(req: Request): T {
|
|
const rawBody = getRawBodyString(req)
|
|
try {
|
|
return JSON.parse(rawBody) as T
|
|
} catch {
|
|
throw new ValidationError('Malformed webhook JSON')
|
|
}
|
|
}
|