construct-convert-map.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import mongoose from 'mongoose';
  2. import type { OverwriteFunction } from './overwrite-function';
  3. import { keepOriginal } from './overwrite-function';
  4. export type ConvertMap = {
  5. [collectionName: string]: {
  6. [propertyName: string]: OverwriteFunction,
  7. }
  8. }
  9. /**
  10. * Special conversion functions for problematic fields
  11. * Add entries here for fields that require custom handling during import
  12. */
  13. const SPECIAL_CONVERT_FUNCTIONS: Record<string, Record<string, OverwriteFunction>> = {
  14. activities: {
  15. snapshot: (value: unknown) => value, // Skip SubdocumentPath casting to avoid Mongoose errors
  16. },
  17. // Add more collections and fields as needed:
  18. // otherCollection: {
  19. // problematicField: (value: unknown) => customProcessing(value),
  20. // },
  21. };
  22. /**
  23. * Get special conversion function for a specific collection.field combination
  24. */
  25. const getSpecialConvertFunction = (collectionName: string, propertyName: string): OverwriteFunction | null => {
  26. return SPECIAL_CONVERT_FUNCTIONS[collectionName]?.[propertyName] ?? null;
  27. };
  28. /**
  29. * Initialize convert map. set keepOriginal as default
  30. */
  31. export const constructConvertMap = (): ConvertMap => {
  32. const convertMap: ConvertMap = {};
  33. mongoose.modelNames().forEach((modelName) => {
  34. const model = mongoose.model(modelName);
  35. if (model.collection == null) {
  36. return;
  37. }
  38. const collectionName = model.collection.name;
  39. convertMap[collectionName] = {};
  40. for (const key of Object.keys(model.schema.paths)) {
  41. const specialHandler = getSpecialConvertFunction(collectionName, key);
  42. convertMap[collectionName][key] = specialHandler ?? keepOriginal;
  43. }
  44. });
  45. return convertMap;
  46. };