Serialize and deserialize data.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
1.2 KiB

  1. import { fastifyPlugin } from 'fastify-plugin';
  2. import * as oatmeal from '@modal-sh/oatmeal-core';
  3. import { FastifyReply, FastifyRequest} from 'fastify';
  4. const JSON_TYPES = [
  5. 'application/json',
  6. ] as const
  7. interface SendX {
  8. (contentType?: string, data?: unknown): void;
  9. }
  10. const sendX: SendX = function sendX(this: FastifyReply, contentType?: string, data?: unknown) {
  11. if (typeof contentType !== 'undefined' && typeof data !== 'undefined') {
  12. const content = oatmeal.serialize(data, { type: contentType })
  13. // TODO add error handling when payload can't be serialized
  14. this.type(contentType).send(content);
  15. return;
  16. }
  17. this.send();
  18. }
  19. export const fastifyOatmeal = fastifyPlugin(async (fastify) => {
  20. oatmeal.AVAILABLE_TYPES
  21. .filter((type) => !JSON_TYPES.includes(type as typeof JSON_TYPES[number]))
  22. .forEach((type) => {
  23. fastify.addContentTypeParser(type, { parseAs: 'buffer' }, async (_: FastifyRequest, body: Buffer) => {
  24. return oatmeal.deserialize(body.toString('utf-8'), { type });
  25. // TODO add error handling when body can't be deserialized
  26. });
  27. });
  28. fastify.decorateReply('sendX', sendX);
  29. });
  30. declare module 'fastify' {
  31. interface FastifyReply {
  32. sendX: SendX;
  33. }
  34. }