attachment-serializer.ts 1.4 KB

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