compare-objectId.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import mongoose from 'mongoose';
  2. import { ObjectIdLike } from '~/server/interfaces/mongoose-utils';
  3. type IObjectId = mongoose.Types.ObjectId;
  4. const ObjectId = mongoose.Types.ObjectId;
  5. /**
  6. * Check if array contains all specified ObjectIds
  7. * @param arr array that potentially contains potentialSubset
  8. * @param potentialSubset array that is potentially a subset of arr
  9. * @returns Whether or not arr includes all elements of potentialSubset
  10. */
  11. export const includesObjectIds = (arr: ObjectIdLike[], potentialSubset: ObjectIdLike[]): boolean => {
  12. const _arr = arr.map(i => i.toString());
  13. const _potentialSubset = potentialSubset.map(i => i.toString());
  14. return _potentialSubset.every(id => _arr.includes(id));
  15. };
  16. /**
  17. * Exclude ObjectIds which exist in testIds from targetIds
  18. * @param targetIds Array of mongoose.Types.ObjectId
  19. * @param testIds Array of mongoose.Types.ObjectId
  20. * @returns Array of mongoose.Types.ObjectId
  21. */
  22. export const excludeTestIdsFromTargetIds = <T extends { toString: any } = IObjectId>(
  23. targetIds: T[], testIds: ObjectIdLike[],
  24. ): T[] => {
  25. // cast to string
  26. const arr1 = targetIds.map(e => e.toString());
  27. const arr2 = testIds.map(e => e.toString());
  28. // filter
  29. const excluded = arr1.filter(e => !arr2.includes(e));
  30. // cast to ObjectId
  31. const shouldReturnString = (arr: any[]): arr is string[] => {
  32. return typeof arr[0] === 'string';
  33. };
  34. return shouldReturnString(targetIds) ? excluded : excluded.map(e => new ObjectId(e));
  35. };