objectid-transformer.ts 776 B

123456789101112131415161718192021222324
  1. // !!! Do NOT import 'mongoose' to reduce bundle size !!!
  2. import { objectIdUtils } from '@growi/core/dist/utils';
  3. import type ObjectId from 'bson-objectid';
  4. import superjson from 'superjson';
  5. export const registerTransformerForObjectId = (): void => {
  6. superjson.registerCustom<ObjectId|string, string>(
  7. {
  8. isApplicable: (v): v is ObjectId => {
  9. if (v == null) {
  10. return false;
  11. }
  12. // Only evaluate types for string and ObjectId
  13. if (typeof v !== 'string' && typeof v.toHexString !== 'function') {
  14. return false;
  15. }
  16. return objectIdUtils.isValidObjectId(v);
  17. },
  18. serialize: v => (typeof v === 'string' ? v : v.toHexString()),
  19. deserialize: v => v,
  20. },
  21. 'ObjectidTransformer',
  22. );
  23. };