Initial import
This commit is contained in:
25
etc/servers/work-server/src/json-body.ts
Executable file
25
etc/servers/work-server/src/json-body.ts
Executable file
@@ -0,0 +1,25 @@
|
||||
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);
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user