overwrite-function.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { parseISO } from 'date-fns/parseISO';
  2. import isIsoDate from 'is-iso-date';
  3. import {
  4. Types, type Document, type Schema,
  5. } from 'mongoose';
  6. const { ObjectId } = Types;
  7. export type OverwriteFunction = (value: unknown, ctx: { document: Document, propertyName: string, schema?: Schema }) => unknown;
  8. /**
  9. * keep original value
  10. * automatically convert ObjectId
  11. *
  12. * @param value value from imported document
  13. * @param ctx context object
  14. * @return new value for the document
  15. *
  16. * @see https://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-cast
  17. */
  18. export const keepOriginal: OverwriteFunction = (value, { document, schema, propertyName }) => {
  19. // Model
  20. if (schema != null && schema.path(propertyName) != null) {
  21. const schemaType = schema.path(propertyName);
  22. // force to set schema to the document
  23. // cz: SchemaArray.cast requires the document to have 'schema' property
  24. // ref: https://github.com/Automattic/mongoose/blob/6.11.4/lib/schema/array.js#L334
  25. document.schema = schema;
  26. return schemaType.cast(value, document, true);
  27. }
  28. // _id
  29. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  30. if (propertyName === '_id' && ObjectId.isValid(value as any)) {
  31. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  32. return new ObjectId(value as any);
  33. }
  34. // Date
  35. if (isIsoDate(value)) {
  36. return parseISO(value as string);
  37. }
  38. return value;
  39. };