common.ts 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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 (
  12. obj != null &&
  13. ((typeof obj === 'string' && isValidObjectId(obj)) ||
  14. (typeof obj === 'object' &&
  15. '_bsontype' in obj &&
  16. obj._bsontype === 'ObjectID') ||
  17. (typeof obj === 'object' && '_id' in obj))
  18. );
  19. };
  20. export const isPopulated = <T>(
  21. ref: Ref<T>,
  22. ): ref is T & { _id: string | ObjectId } => {
  23. return (
  24. ref != null &&
  25. typeof ref !== 'string' &&
  26. !('_bsontype' in ref && ref._bsontype === 'ObjectID')
  27. );
  28. };
  29. export const getIdForRef = <T>(ref: Ref<T>): string | ObjectId => {
  30. return isPopulated(ref) ? ref._id : ref;
  31. };
  32. export const getIdStringForRef = <T>(ref: Ref<T>): string => {
  33. return getIdForRef(ref).toString();
  34. };