|
- import { fastifyPlugin } from 'fastify-plugin';
- import * as oatmeal from '@modal-sh/oatmeal-core';
- import { FastifyReply, FastifyRequest} from 'fastify';
-
- const JSON_TYPES = [
- 'application/json',
- ] as const
-
- interface SendX {
- (contentType?: string, data?: unknown): void;
- }
-
- const sendX: SendX = function sendX(this: FastifyReply, contentType?: string, data?: unknown) {
- if (typeof contentType !== 'undefined' && typeof data !== 'undefined') {
- const content = oatmeal.serialize(data, { type: contentType })
- // TODO add error handling when payload can't be serialized
- this.type(contentType).send(content);
- return;
- }
- this.send();
- }
-
- export const fastifyOatmeal = fastifyPlugin(async (fastify) => {
- oatmeal.AVAILABLE_TYPES
- .filter((type) => !JSON_TYPES.includes(type as typeof JSON_TYPES[number]))
- .forEach((type) => {
- fastify.addContentTypeParser(type, { parseAs: 'buffer' }, async (_: FastifyRequest, body: Buffer) => {
- return oatmeal.deserialize(body.toString('utf-8'), { type });
- // TODO add error handling when body can't be deserialized
- });
- });
-
- fastify.decorateReply('sendX', sendX);
- });
-
- declare module 'fastify' {
- interface FastifyReply {
- sendX: SendX;
- }
- }
|