/* * Common types and interfaces */ import type { Types } from 'mongoose'; import { isValidObjectId } from '../utils/objectid-utils'; type ObjectId = Types.ObjectId; // Foreign key field export type Ref = string | ObjectId | T & { _id: string | ObjectId }; export type Populated = { [P in keyof T]: P extends K ? T[P] extends null ? null : T[P] extends Ref ? R : T[P] : T[P]; }; export type Nullable = T | null | undefined; export const isRef = (obj: unknown): obj is Ref => { return obj != null && ( (typeof obj === 'string' && isValidObjectId(obj)) || (typeof obj === 'object' && '_bsontype' in obj && obj._bsontype === 'ObjectID') || (typeof obj === 'object' && '_id' in obj) ); }; export const isPopulated = (ref: Ref): ref is T & { _id: string | ObjectId } => { return ref != null && typeof ref !== 'string' && !('_bsontype' in ref && ref._bsontype === 'ObjectID'); }; export const getIdForRef = (ref: Ref): string | ObjectId => { return isPopulated(ref) ? ref._id : ref; }; export const getIdStringForRef = (ref: Ref): string => { return getIdForRef(ref).toString(); };