common.ts 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. /*
  2. * Common types and interfaces
  3. */
  4. import type { Types } from 'mongoose';
  5. import { isValidObjectId } from '../utils/objectid-utils';
  6. type ObjectId = Types.ObjectId;
  7. // Foreign key field
  8. export type Ref<T> = string | ObjectId | T & { _id: string | ObjectId };
  9. export type Nullable<T> = T | null | undefined;
  10. export const isRef = <T>(obj: unknown): obj is Ref<T> => {
  11. return obj != null
  12. && (
  13. (typeof obj === 'string' && isValidObjectId(obj))
  14. || (typeof obj === 'object' && '_bsontype' in obj && obj._bsontype === 'ObjectID')
  15. || (typeof obj === 'object' && '_id' in obj)
  16. );
  17. };
  18. export const isPopulated = <T>(ref: Ref<T>): ref is T & { _id: string | ObjectId } => {
  19. return ref != null
  20. && typeof ref !== 'string'
  21. && !('_bsontype' in ref && ref._bsontype === 'ObjectID');
  22. };
  23. export const getIdForRef = <T>(ref: Ref<T>): string | ObjectId => {
  24. return isPopulated(ref)
  25. ? ref._id
  26. : ref;
  27. };
  28. export const getIdStringForRef = <T>(ref: Ref<T>): string => {
  29. return getIdForRef(ref).toString();
  30. };