attachment-serializer.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { Document } from 'mongoose';
  2. import type { IAttachment, IUser } from '~/interfaces';
  3. import { isPopulated, isRef, type Ref } from '../../interfaces/common';
  4. import {
  5. type IUserSerializedSecurely,
  6. serializeUserSecurely,
  7. } from './user-serializer';
  8. export type IAttachmentSerializedSecurely<A extends IAttachment> = Omit<
  9. A,
  10. 'creator'
  11. > & { creator?: Ref<IUserSerializedSecurely<IUser>> };
  12. const omitInsecureAttributes = <A extends IAttachment>(
  13. attachment: A,
  14. ): IAttachmentSerializedSecurely<A> => {
  15. const leanDoc =
  16. attachment instanceof Document ? attachment.toObject<A>() : attachment;
  17. const { creator, ...rest } = leanDoc;
  18. const secureCreator =
  19. creator == null ? undefined : serializeUserSecurely(creator);
  20. return {
  21. creator: secureCreator,
  22. ...rest,
  23. };
  24. };
  25. export function serializeAttachmentSecurely<A extends IAttachment>(
  26. attachment?: A,
  27. ): IAttachmentSerializedSecurely<A>;
  28. export function serializeAttachmentSecurely<A extends IAttachment>(
  29. attachment?: Ref<A>,
  30. ): Ref<IAttachmentSerializedSecurely<A>>;
  31. export function serializeAttachmentSecurely<A extends IAttachment>(
  32. attachment?: A | Ref<A>,
  33. ):
  34. | undefined
  35. | IAttachmentSerializedSecurely<A>
  36. | Ref<IAttachmentSerializedSecurely<A>> {
  37. if (attachment == null) return attachment;
  38. if (isRef(attachment) && !isPopulated(attachment)) return attachment;
  39. return omitInsecureAttributes(attachment);
  40. }