import { Document } from 'mongoose';
import type { IAttachment, IUser } from '~/interfaces';
import { isPopulated, isRef, type Ref } from '../../interfaces/common';
import { serializeUserSecurely, type IUserSerializedSecurely } from './user-serializer';
export type IAttachmentSerializedSecurely = Omit & { creator?: Ref> };
const omitInsecureAttributes = (attachment: A): IAttachmentSerializedSecurely => {
const leanDoc = (attachment instanceof Document)
? attachment.toObject()
: attachment;
const { creator, ...rest } = leanDoc;
const secureCreator = creator == null
? undefined
: serializeUserSecurely(creator);
return {
creator: secureCreator,
...rest,
};
};
export function serializeAttachmentSecurely(attachment?: A): IAttachmentSerializedSecurely;
export function serializeAttachmentSecurely(attachment?: Ref): Ref>;
export function serializeAttachmentSecurely(attachment?: A | Ref)
: undefined | IAttachmentSerializedSecurely | Ref> {
if (attachment == null) return attachment;
if (isRef(attachment) && !isPopulated(attachment)) return attachment;
return omitInsecureAttributes(attachment);
}