26 lines
708 B
TypeScript
Executable File
26 lines
708 B
TypeScript
Executable File
import type { FastifyInstance } from 'fastify';
|
|
|
|
export function registerJsonBodyParser(app: FastifyInstance) {
|
|
app.addContentTypeParser('application/json', { parseAs: 'string' }, (request, body, done) => {
|
|
const rawBody = typeof body === 'string' ? body : '';
|
|
const normalizedBody = rawBody.trim();
|
|
|
|
if (!normalizedBody) {
|
|
done(null, {});
|
|
return;
|
|
}
|
|
|
|
try {
|
|
done(null, JSON.parse(normalizedBody));
|
|
} catch {
|
|
const error = new Error('Body is not valid JSON.') as Error & {
|
|
statusCode?: number;
|
|
code?: string;
|
|
};
|
|
error.statusCode = 400;
|
|
error.code = 'FST_ERR_CTP_INVALID_JSON_BODY';
|
|
done(error, undefined);
|
|
}
|
|
});
|
|
}
|