@payloadcms/db-mongodb 3.0.0-canary.e198dc5 → 3.0.0-canary.e1fc0e0

Sign up to get free protection for your applications and to get access to all the features.
@@ -6,7 +6,7 @@ const migrationTemplate = ({ downSQL, imports, upSQL })=>`import {
6
6
  MigrateUpArgs,
7
7
  MigrateDownArgs,
8
8
  } from '@payloadcms/db-mongodb'
9
- ${imports}
9
+ ${imports ? imports : ''}
10
10
 
11
11
  export async function up({ payload, req }: MigrateUpArgs): Promise<void> {
12
12
  ${upSQL ?? ` // Migration code`}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/createMigration.ts"],"sourcesContent":["import type { CreateMigration, MigrationTemplateArgs } from 'payload'\n\nimport fs from 'fs'\nimport path from 'path'\nimport { getPredefinedMigration } from 'payload'\nimport { fileURLToPath } from 'url'\n\nconst migrationTemplate = ({ downSQL, imports, upSQL }: MigrationTemplateArgs): string => `import {\n MigrateUpArgs,\n MigrateDownArgs,\n} from '@payloadcms/db-mongodb'\n${imports}\n\nexport async function up({ payload, req }: MigrateUpArgs): Promise<void> {\n${upSQL ?? ` // Migration code`}\n}\n\nexport async function down({ payload, req }: MigrateDownArgs): Promise<void> {\n${downSQL ?? ` // Migration code`}\n}\n`\n\nexport const createMigration: CreateMigration = async function createMigration({\n file,\n migrationName,\n payload,\n}) {\n const filename = fileURLToPath(import.meta.url)\n const dirname = path.dirname(filename)\n\n const dir = payload.db.migrationDir\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir)\n }\n const predefinedMigration = await getPredefinedMigration({\n dirname,\n file,\n migrationName,\n payload,\n })\n\n const migrationFileContent = migrationTemplate(predefinedMigration)\n\n const [yyymmdd, hhmmss] = new Date().toISOString().split('T')\n const formattedDate = yyymmdd.replace(/\\D/g, '')\n const formattedTime = hhmmss.split('.')[0].replace(/\\D/g, '')\n\n const timestamp = `${formattedDate}_${formattedTime}`\n\n const formattedName = migrationName?.replace(/\\W/g, '_')\n const fileName = migrationName ? `${timestamp}_${formattedName}.ts` : `${timestamp}_migration.ts`\n const filePath = `${dir}/${fileName}`\n fs.writeFileSync(filePath, migrationFileContent)\n payload.logger.info({ msg: `Migration created at ${filePath}` })\n}\n"],"names":["fs","path","getPredefinedMigration","fileURLToPath","migrationTemplate","downSQL","imports","upSQL","createMigration","file","migrationName","payload","filename","url","dirname","dir","db","migrationDir","existsSync","mkdirSync","predefinedMigration","migrationFileContent","yyymmdd","hhmmss","Date","toISOString","split","formattedDate","replace","formattedTime","timestamp","formattedName","fileName","filePath","writeFileSync","logger","info","msg"],"mappings":"AAEA,OAAOA,QAAQ,KAAI;AACnB,OAAOC,UAAU,OAAM;AACvB,SAASC,sBAAsB,QAAQ,UAAS;AAChD,SAASC,aAAa,QAAQ,MAAK;AAEnC,MAAMC,oBAAoB,CAAC,EAAEC,OAAO,EAAEC,OAAO,EAAEC,KAAK,EAAyB,GAAa,CAAC;;;;AAI3F,EAAED,QAAQ;;;AAGV,EAAEC,SAAS,CAAC,mBAAmB,CAAC,CAAC;;;;AAIjC,EAAEF,WAAW,CAAC,mBAAmB,CAAC,CAAC;;AAEnC,CAAC;AAED,OAAO,MAAMG,kBAAmC,eAAeA,gBAAgB,EAC7EC,IAAI,EACJC,aAAa,EACbC,OAAO,EACR;IACC,MAAMC,WAAWT,cAAc,YAAYU,GAAG;IAC9C,MAAMC,UAAUb,KAAKa,OAAO,CAACF;IAE7B,MAAMG,MAAMJ,QAAQK,EAAE,CAACC,YAAY;IACnC,IAAI,CAACjB,GAAGkB,UAAU,CAACH,MAAM;QACvBf,GAAGmB,SAAS,CAACJ;IACf;IACA,MAAMK,sBAAsB,MAAMlB,uBAAuB;QACvDY;QACAL;QACAC;QACAC;IACF;IAEA,MAAMU,uBAAuBjB,kBAAkBgB;IAE/C,MAAM,CAACE,SAASC,OAAO,GAAG,IAAIC,OAAOC,WAAW,GAAGC,KAAK,CAAC;IACzD,MAAMC,gBAAgBL,QAAQM,OAAO,CAAC,OAAO;IAC7C,MAAMC,gBAAgBN,OAAOG,KAAK,CAAC,IAAI,CAAC,EAAE,CAACE,OAAO,CAAC,OAAO;IAE1D,MAAME,YAAY,CAAC,EAAEH,cAAc,CAAC,EAAEE,cAAc,CAAC;IAErD,MAAME,gBAAgBrB,eAAekB,QAAQ,OAAO;IACpD,MAAMI,WAAWtB,gBAAgB,CAAC,EAAEoB,UAAU,CAAC,EAAEC,cAAc,GAAG,CAAC,GAAG,CAAC,EAAED,UAAU,aAAa,CAAC;IACjG,MAAMG,WAAW,CAAC,EAAElB,IAAI,CAAC,EAAEiB,SAAS,CAAC;IACrChC,GAAGkC,aAAa,CAACD,UAAUZ;IAC3BV,QAAQwB,MAAM,CAACC,IAAI,CAAC;QAAEC,KAAK,CAAC,qBAAqB,EAAEJ,SAAS,CAAC;IAAC;AAChE,EAAC"}
1
+ {"version":3,"sources":["../src/createMigration.ts"],"sourcesContent":["import type { CreateMigration, MigrationTemplateArgs } from 'payload'\n\nimport fs from 'fs'\nimport path from 'path'\nimport { getPredefinedMigration } from 'payload'\nimport { fileURLToPath } from 'url'\n\nconst migrationTemplate = ({ downSQL, imports, upSQL }: MigrationTemplateArgs): string => `import {\n MigrateUpArgs,\n MigrateDownArgs,\n} from '@payloadcms/db-mongodb'\n${imports ? imports : ''}\n\nexport async function up({ payload, req }: MigrateUpArgs): Promise<void> {\n${upSQL ?? ` // Migration code`}\n}\n\nexport async function down({ payload, req }: MigrateDownArgs): Promise<void> {\n${downSQL ?? ` // Migration code`}\n}\n`\n\nexport const createMigration: CreateMigration = async function createMigration({\n file,\n migrationName,\n payload,\n}) {\n const filename = fileURLToPath(import.meta.url)\n const dirname = path.dirname(filename)\n\n const dir = payload.db.migrationDir\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir)\n }\n const predefinedMigration = await getPredefinedMigration({\n dirname,\n file,\n migrationName,\n payload,\n })\n\n const migrationFileContent = migrationTemplate(predefinedMigration)\n\n const [yyymmdd, hhmmss] = new Date().toISOString().split('T')\n const formattedDate = yyymmdd.replace(/\\D/g, '')\n const formattedTime = hhmmss.split('.')[0].replace(/\\D/g, '')\n\n const timestamp = `${formattedDate}_${formattedTime}`\n\n const formattedName = migrationName?.replace(/\\W/g, '_')\n const fileName = migrationName ? `${timestamp}_${formattedName}.ts` : `${timestamp}_migration.ts`\n const filePath = `${dir}/${fileName}`\n fs.writeFileSync(filePath, migrationFileContent)\n payload.logger.info({ msg: `Migration created at ${filePath}` })\n}\n"],"names":["fs","path","getPredefinedMigration","fileURLToPath","migrationTemplate","downSQL","imports","upSQL","createMigration","file","migrationName","payload","filename","url","dirname","dir","db","migrationDir","existsSync","mkdirSync","predefinedMigration","migrationFileContent","yyymmdd","hhmmss","Date","toISOString","split","formattedDate","replace","formattedTime","timestamp","formattedName","fileName","filePath","writeFileSync","logger","info","msg"],"mappings":"AAEA,OAAOA,QAAQ,KAAI;AACnB,OAAOC,UAAU,OAAM;AACvB,SAASC,sBAAsB,QAAQ,UAAS;AAChD,SAASC,aAAa,QAAQ,MAAK;AAEnC,MAAMC,oBAAoB,CAAC,EAAEC,OAAO,EAAEC,OAAO,EAAEC,KAAK,EAAyB,GAAa,CAAC;;;;AAI3F,EAAED,UAAUA,UAAU,GAAG;;;AAGzB,EAAEC,SAAS,CAAC,mBAAmB,CAAC,CAAC;;;;AAIjC,EAAEF,WAAW,CAAC,mBAAmB,CAAC,CAAC;;AAEnC,CAAC;AAED,OAAO,MAAMG,kBAAmC,eAAeA,gBAAgB,EAC7EC,IAAI,EACJC,aAAa,EACbC,OAAO,EACR;IACC,MAAMC,WAAWT,cAAc,YAAYU,GAAG;IAC9C,MAAMC,UAAUb,KAAKa,OAAO,CAACF;IAE7B,MAAMG,MAAMJ,QAAQK,EAAE,CAACC,YAAY;IACnC,IAAI,CAACjB,GAAGkB,UAAU,CAACH,MAAM;QACvBf,GAAGmB,SAAS,CAACJ;IACf;IACA,MAAMK,sBAAsB,MAAMlB,uBAAuB;QACvDY;QACAL;QACAC;QACAC;IACF;IAEA,MAAMU,uBAAuBjB,kBAAkBgB;IAE/C,MAAM,CAACE,SAASC,OAAO,GAAG,IAAIC,OAAOC,WAAW,GAAGC,KAAK,CAAC;IACzD,MAAMC,gBAAgBL,QAAQM,OAAO,CAAC,OAAO;IAC7C,MAAMC,gBAAgBN,OAAOG,KAAK,CAAC,IAAI,CAAC,EAAE,CAACE,OAAO,CAAC,OAAO;IAE1D,MAAME,YAAY,CAAC,EAAEH,cAAc,CAAC,EAAEE,cAAc,CAAC;IAErD,MAAME,gBAAgBrB,eAAekB,QAAQ,OAAO;IACpD,MAAMI,WAAWtB,gBAAgB,CAAC,EAAEoB,UAAU,CAAC,EAAEC,cAAc,GAAG,CAAC,GAAG,CAAC,EAAED,UAAU,aAAa,CAAC;IACjG,MAAMG,WAAW,CAAC,EAAElB,IAAI,CAAC,EAAEiB,SAAS,CAAC;IACrChC,GAAGkC,aAAa,CAACD,UAAUZ;IAC3BV,QAAQwB,MAAM,CAACC,IAAI,CAAC;QAAEC,KAAK,CAAC,qBAAqB,EAAEJ,SAAS,CAAC;IAAC;AAChE,EAAC"}
@@ -136,6 +136,9 @@ const fieldToSchemaMap = {
136
136
  },
137
137
  collapsible: (field, schema, config, buildSchemaOptions)=>{
138
138
  field.fields.forEach((subField)=>{
139
+ if (fieldIsVirtual(subField)) {
140
+ return;
141
+ }
139
142
  const addFieldSchema = fieldToSchemaMap[subField.type];
140
143
  if (addFieldSchema) {
141
144
  addFieldSchema(subField, schema, config, buildSchemaOptions);
@@ -349,6 +352,9 @@ const fieldToSchemaMap = {
349
352
  },
350
353
  row: (field, schema, config, buildSchemaOptions)=>{
351
354
  field.fields.forEach((subField)=>{
355
+ if (fieldIsVirtual(subField)) {
356
+ return;
357
+ }
352
358
  const addFieldSchema = fieldToSchemaMap[subField.type];
353
359
  if (addFieldSchema) {
354
360
  addFieldSchema(subField, schema, config, buildSchemaOptions);
@@ -378,6 +384,9 @@ const fieldToSchemaMap = {
378
384
  tabs: (field, schema, config, buildSchemaOptions)=>{
379
385
  field.tabs.forEach((tab)=>{
380
386
  if (tabHasName(tab)) {
387
+ if (fieldIsVirtual(tab)) {
388
+ return;
389
+ }
381
390
  const baseSchema = {
382
391
  type: buildSchema(config, tab.fields, {
383
392
  disableUnique: buildSchemaOptions.disableUnique,
@@ -394,6 +403,9 @@ const fieldToSchemaMap = {
394
403
  });
395
404
  } else {
396
405
  tab.fields.forEach((subField)=>{
406
+ if (fieldIsVirtual(subField)) {
407
+ return;
408
+ }
397
409
  const addFieldSchema = fieldToSchemaMap[subField.type];
398
410
  if (addFieldSchema) {
399
411
  addFieldSchema(subField, schema, config, buildSchemaOptions);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/models/buildSchema.ts"],"sourcesContent":["import type { IndexOptions, Schema, SchemaOptions, SchemaTypeOptions } from 'mongoose'\nimport type {\n ArrayField,\n Block,\n BlocksField,\n CheckboxField,\n CodeField,\n CollapsibleField,\n DateField,\n EmailField,\n Field,\n FieldAffectingData,\n GroupField,\n JSONField,\n NonPresentationalField,\n NumberField,\n PointField,\n RadioField,\n RelationshipField,\n RichTextField,\n RowField,\n SanitizedConfig,\n SanitizedLocalizationConfig,\n SelectField,\n Tab,\n TabsField,\n TextareaField,\n TextField,\n UploadField,\n} from 'payload'\n\nimport mongoose from 'mongoose'\nimport {\n fieldAffectsData,\n fieldIsLocalized,\n fieldIsPresentationalOnly,\n fieldIsVirtual,\n tabHasName,\n} from 'payload/shared'\n\nexport type BuildSchemaOptions = {\n allowIDField?: boolean\n disableUnique?: boolean\n draftsEnabled?: boolean\n indexSortableFields?: boolean\n options?: SchemaOptions\n}\n\ntype FieldSchemaGenerator = (\n field: Field,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n) => void\n\n/**\n * get a field's defaultValue only if defined and not dynamic so that it can be set on the field schema\n * @param field\n */\nconst formatDefaultValue = (field: FieldAffectingData) =>\n typeof field.defaultValue !== 'undefined' && typeof field.defaultValue !== 'function'\n ? field.defaultValue\n : undefined\n\nconst formatBaseSchema = (field: FieldAffectingData, buildSchemaOptions: BuildSchemaOptions) => {\n const { disableUnique, draftsEnabled, indexSortableFields } = buildSchemaOptions\n const schema: SchemaTypeOptions<unknown> = {\n default: formatDefaultValue(field),\n index: field.index || (!disableUnique && field.unique) || indexSortableFields || false,\n required: false,\n unique: (!disableUnique && field.unique) || false,\n }\n\n if (\n schema.unique &&\n (field.localized ||\n draftsEnabled ||\n (fieldAffectsData(field) &&\n field.type !== 'group' &&\n field.type !== 'tab' &&\n field.required !== true))\n ) {\n schema.sparse = true\n }\n\n if (field.hidden) {\n schema.hidden = true\n }\n\n return schema\n}\n\nconst localizeSchema = (\n entity: NonPresentationalField | Tab,\n schema,\n localization: false | SanitizedLocalizationConfig,\n) => {\n if (fieldIsLocalized(entity) && localization && Array.isArray(localization.locales)) {\n return {\n type: localization.localeCodes.reduce(\n (localeSchema, locale) => ({\n ...localeSchema,\n [locale]: schema,\n }),\n {\n _id: false,\n },\n ),\n localized: true,\n }\n }\n return schema\n}\n\nexport const buildSchema = (\n config: SanitizedConfig,\n configFields: Field[],\n buildSchemaOptions: BuildSchemaOptions = {},\n): Schema => {\n const { allowIDField, options } = buildSchemaOptions\n let fields = {}\n\n let schemaFields = configFields\n\n if (!allowIDField) {\n const idField = schemaFields.find((field) => fieldAffectsData(field) && field.name === 'id')\n if (idField) {\n fields = {\n _id: idField.type === 'number' ? Number : String,\n }\n schemaFields = schemaFields.filter(\n (field) => !(fieldAffectsData(field) && field.name === 'id'),\n )\n }\n }\n\n const schema = new mongoose.Schema(fields, options)\n\n schemaFields.forEach((field) => {\n if (fieldIsVirtual(field)) {\n return\n }\n\n if (!fieldIsPresentationalOnly(field)) {\n const addFieldSchema: FieldSchemaGenerator = fieldToSchemaMap[field.type]\n\n if (addFieldSchema) {\n addFieldSchema(field, schema, config, buildSchemaOptions)\n }\n }\n })\n\n return schema\n}\n\nconst fieldToSchemaMap: Record<string, FieldSchemaGenerator> = {\n array: (\n field: ArrayField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ) => {\n const baseSchema = {\n ...formatBaseSchema(field, buildSchemaOptions),\n type: [\n buildSchema(config, field.fields, {\n allowIDField: true,\n disableUnique: buildSchemaOptions.disableUnique,\n draftsEnabled: buildSchemaOptions.draftsEnabled,\n options: {\n _id: false,\n id: false,\n minimize: false,\n },\n }),\n ],\n }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n blocks: (\n field: BlocksField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const fieldSchema = {\n type: [new mongoose.Schema({}, { _id: false, discriminatorKey: 'blockType' })],\n }\n\n schema.add({\n [field.name]: localizeSchema(field, fieldSchema, config.localization),\n })\n\n field.blocks.forEach((blockItem: Block) => {\n const blockSchema = new mongoose.Schema({}, { _id: false, id: false })\n\n blockItem.fields.forEach((blockField) => {\n const addFieldSchema: FieldSchemaGenerator = fieldToSchemaMap[blockField.type]\n if (addFieldSchema) {\n addFieldSchema(blockField, blockSchema, config, buildSchemaOptions)\n }\n })\n\n if (field.localized && config.localization) {\n config.localization.localeCodes.forEach((localeCode) => {\n // @ts-expect-error Possible incorrect typing in mongoose types, this works\n schema.path(`${field.name}.${localeCode}`).discriminator(blockItem.slug, blockSchema)\n })\n } else {\n // @ts-expect-error Possible incorrect typing in mongoose types, this works\n schema.path(field.name).discriminator(blockItem.slug, blockSchema)\n }\n })\n },\n checkbox: (\n field: CheckboxField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema = { ...formatBaseSchema(field, buildSchemaOptions), type: Boolean }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n code: (\n field: CodeField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema = { ...formatBaseSchema(field, buildSchemaOptions), type: String }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n collapsible: (\n field: CollapsibleField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n field.fields.forEach((subField: Field) => {\n const addFieldSchema: FieldSchemaGenerator = fieldToSchemaMap[subField.type]\n\n if (addFieldSchema) {\n addFieldSchema(subField, schema, config, buildSchemaOptions)\n }\n })\n },\n date: (\n field: DateField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema = { ...formatBaseSchema(field, buildSchemaOptions), type: Date }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n email: (\n field: EmailField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema = { ...formatBaseSchema(field, buildSchemaOptions), type: String }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n group: (\n field: GroupField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const formattedBaseSchema = formatBaseSchema(field, buildSchemaOptions)\n\n // carry indexSortableFields through to versions if drafts enabled\n const indexSortableFields =\n buildSchemaOptions.indexSortableFields &&\n field.name === 'version' &&\n buildSchemaOptions.draftsEnabled\n\n const baseSchema = {\n ...formattedBaseSchema,\n type: buildSchema(config, field.fields, {\n disableUnique: buildSchemaOptions.disableUnique,\n draftsEnabled: buildSchemaOptions.draftsEnabled,\n indexSortableFields,\n options: {\n _id: false,\n id: false,\n minimize: false,\n },\n }),\n }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n json: (\n field: JSONField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema = {\n ...formatBaseSchema(field, buildSchemaOptions),\n type: mongoose.Schema.Types.Mixed,\n }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n number: (\n field: NumberField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema = {\n ...formatBaseSchema(field, buildSchemaOptions),\n type: field.hasMany ? [Number] : Number,\n }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n point: (\n field: PointField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema: SchemaTypeOptions<unknown> = {\n type: {\n type: String,\n enum: ['Point'],\n },\n coordinates: {\n type: [Number],\n default: formatDefaultValue(field),\n required: false,\n },\n }\n if (buildSchemaOptions.disableUnique && field.unique && field.localized) {\n baseSchema.coordinates.sparse = true\n }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n\n if (field.index === true || field.index === undefined) {\n const indexOptions: IndexOptions = {}\n if (!buildSchemaOptions.disableUnique && field.unique) {\n indexOptions.sparse = true\n indexOptions.unique = true\n }\n if (field.localized && config.localization) {\n config.localization.locales.forEach((locale) => {\n schema.index({ [`${field.name}.${locale.code}`]: '2dsphere' }, indexOptions)\n })\n } else {\n schema.index({ [field.name]: '2dsphere' }, indexOptions)\n }\n }\n },\n radio: (\n field: RadioField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema = {\n ...formatBaseSchema(field, buildSchemaOptions),\n type: String,\n enum: field.options.map((option) => {\n if (typeof option === 'object') {\n return option.value\n }\n return option\n }),\n }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n relationship: (\n field: RelationshipField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ) => {\n const hasManyRelations = Array.isArray(field.relationTo)\n let schemaToReturn: { [key: string]: any } = {}\n\n if (field.localized && config.localization) {\n schemaToReturn = {\n type: config.localization.localeCodes.reduce((locales, locale) => {\n let localeSchema: { [key: string]: any } = {}\n\n if (hasManyRelations) {\n localeSchema = {\n ...formatBaseSchema(field, buildSchemaOptions),\n _id: false,\n type: mongoose.Schema.Types.Mixed,\n relationTo: { type: String, enum: field.relationTo },\n value: {\n type: mongoose.Schema.Types.Mixed,\n refPath: `${field.name}.${locale}.relationTo`,\n },\n }\n } else {\n localeSchema = {\n ...formatBaseSchema(field, buildSchemaOptions),\n type: mongoose.Schema.Types.Mixed,\n ref: field.relationTo,\n }\n }\n\n return {\n ...locales,\n [locale]: field.hasMany\n ? { type: [localeSchema], default: formatDefaultValue(field) }\n : localeSchema,\n }\n }, {}),\n localized: true,\n }\n } else if (hasManyRelations) {\n schemaToReturn = {\n ...formatBaseSchema(field, buildSchemaOptions),\n _id: false,\n type: mongoose.Schema.Types.Mixed,\n relationTo: { type: String, enum: field.relationTo },\n value: {\n type: mongoose.Schema.Types.Mixed,\n refPath: `${field.name}.relationTo`,\n },\n }\n\n if (field.hasMany) {\n schemaToReturn = {\n type: [schemaToReturn],\n default: formatDefaultValue(field),\n }\n }\n } else {\n schemaToReturn = {\n ...formatBaseSchema(field, buildSchemaOptions),\n type: mongoose.Schema.Types.Mixed,\n ref: field.relationTo,\n }\n\n if (field.hasMany) {\n schemaToReturn = {\n type: [schemaToReturn],\n default: formatDefaultValue(field),\n }\n }\n }\n\n schema.add({\n [field.name]: schemaToReturn,\n })\n },\n richText: (\n field: RichTextField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema = {\n ...formatBaseSchema(field, buildSchemaOptions),\n type: mongoose.Schema.Types.Mixed,\n }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n row: (\n field: RowField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n field.fields.forEach((subField: Field) => {\n const addFieldSchema: FieldSchemaGenerator = fieldToSchemaMap[subField.type]\n\n if (addFieldSchema) {\n addFieldSchema(subField, schema, config, buildSchemaOptions)\n }\n })\n },\n select: (\n field: SelectField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema = {\n ...formatBaseSchema(field, buildSchemaOptions),\n type: String,\n enum: field.options.map((option) => {\n if (typeof option === 'object') {\n return option.value\n }\n return option\n }),\n }\n\n if (buildSchemaOptions.draftsEnabled || !field.required) {\n baseSchema.enum.push(null)\n }\n\n schema.add({\n [field.name]: localizeSchema(\n field,\n field.hasMany ? [baseSchema] : baseSchema,\n config.localization,\n ),\n })\n },\n tabs: (\n field: TabsField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n field.tabs.forEach((tab) => {\n if (tabHasName(tab)) {\n const baseSchema = {\n type: buildSchema(config, tab.fields, {\n disableUnique: buildSchemaOptions.disableUnique,\n draftsEnabled: buildSchemaOptions.draftsEnabled,\n options: {\n _id: false,\n id: false,\n minimize: false,\n },\n }),\n }\n\n schema.add({\n [tab.name]: localizeSchema(tab, baseSchema, config.localization),\n })\n } else {\n tab.fields.forEach((subField: Field) => {\n const addFieldSchema: FieldSchemaGenerator = fieldToSchemaMap[subField.type]\n\n if (addFieldSchema) {\n addFieldSchema(subField, schema, config, buildSchemaOptions)\n }\n })\n }\n })\n },\n text: (\n field: TextField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema = {\n ...formatBaseSchema(field, buildSchemaOptions),\n type: field.hasMany ? [String] : String,\n }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n textarea: (\n field: TextareaField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema = { ...formatBaseSchema(field, buildSchemaOptions), type: String }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n upload: (\n field: UploadField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const hasManyRelations = Array.isArray(field.relationTo)\n let schemaToReturn: { [key: string]: any } = {}\n\n if (field.localized && config.localization) {\n schemaToReturn = {\n type: config.localization.localeCodes.reduce((locales, locale) => {\n let localeSchema: { [key: string]: any } = {}\n\n if (hasManyRelations) {\n localeSchema = {\n ...formatBaseSchema(field, buildSchemaOptions),\n _id: false,\n type: mongoose.Schema.Types.Mixed,\n relationTo: { type: String, enum: field.relationTo },\n value: {\n type: mongoose.Schema.Types.Mixed,\n refPath: `${field.name}.${locale}.relationTo`,\n },\n }\n } else {\n localeSchema = {\n ...formatBaseSchema(field, buildSchemaOptions),\n type: mongoose.Schema.Types.Mixed,\n ref: field.relationTo,\n }\n }\n\n return {\n ...locales,\n [locale]: field.hasMany\n ? { type: [localeSchema], default: formatDefaultValue(field) }\n : localeSchema,\n }\n }, {}),\n localized: true,\n }\n } else if (hasManyRelations) {\n schemaToReturn = {\n ...formatBaseSchema(field, buildSchemaOptions),\n _id: false,\n type: mongoose.Schema.Types.Mixed,\n relationTo: { type: String, enum: field.relationTo },\n value: {\n type: mongoose.Schema.Types.Mixed,\n refPath: `${field.name}.relationTo`,\n },\n }\n\n if (field.hasMany) {\n schemaToReturn = {\n type: [schemaToReturn],\n default: formatDefaultValue(field),\n }\n }\n } else {\n schemaToReturn = {\n ...formatBaseSchema(field, buildSchemaOptions),\n type: mongoose.Schema.Types.Mixed,\n ref: field.relationTo,\n }\n\n if (field.hasMany) {\n schemaToReturn = {\n type: [schemaToReturn],\n default: formatDefaultValue(field),\n }\n }\n }\n\n schema.add({\n [field.name]: schemaToReturn,\n })\n },\n}\n"],"names":["mongoose","fieldAffectsData","fieldIsLocalized","fieldIsPresentationalOnly","fieldIsVirtual","tabHasName","formatDefaultValue","field","defaultValue","undefined","formatBaseSchema","buildSchemaOptions","disableUnique","draftsEnabled","indexSortableFields","schema","default","index","unique","required","localized","type","sparse","hidden","localizeSchema","entity","localization","Array","isArray","locales","localeCodes","reduce","localeSchema","locale","_id","buildSchema","config","configFields","allowIDField","options","fields","schemaFields","idField","find","name","Number","String","filter","Schema","forEach","addFieldSchema","fieldToSchemaMap","array","baseSchema","id","minimize","add","blocks","fieldSchema","discriminatorKey","blockItem","blockSchema","blockField","localeCode","path","discriminator","slug","checkbox","Boolean","code","collapsible","subField","date","Date","email","group","formattedBaseSchema","json","Types","Mixed","number","hasMany","point","enum","coordinates","indexOptions","radio","map","option","value","relationship","hasManyRelations","relationTo","schemaToReturn","refPath","ref","richText","row","select","push","tabs","tab","text","textarea","upload"],"mappings":"AA+BA,OAAOA,cAAc,WAAU;AAC/B,SACEC,gBAAgB,EAChBC,gBAAgB,EAChBC,yBAAyB,EACzBC,cAAc,EACdC,UAAU,QACL,iBAAgB;AAiBvB;;;CAGC,GACD,MAAMC,qBAAqB,CAACC,QAC1B,OAAOA,MAAMC,YAAY,KAAK,eAAe,OAAOD,MAAMC,YAAY,KAAK,aACvED,MAAMC,YAAY,GAClBC;AAEN,MAAMC,mBAAmB,CAACH,OAA2BI;IACnD,MAAM,EAAEC,aAAa,EAAEC,aAAa,EAAEC,mBAAmB,EAAE,GAAGH;IAC9D,MAAMI,SAAqC;QACzCC,SAASV,mBAAmBC;QAC5BU,OAAOV,MAAMU,KAAK,IAAK,CAACL,iBAAiBL,MAAMW,MAAM,IAAKJ,uBAAuB;QACjFK,UAAU;QACVD,QAAQ,AAAC,CAACN,iBAAiBL,MAAMW,MAAM,IAAK;IAC9C;IAEA,IACEH,OAAOG,MAAM,IACZX,CAAAA,MAAMa,SAAS,IACdP,iBACCZ,iBAAiBM,UAChBA,MAAMc,IAAI,KAAK,WACfd,MAAMc,IAAI,KAAK,SACfd,MAAMY,QAAQ,KAAK,IAAI,GAC3B;QACAJ,OAAOO,MAAM,GAAG;IAClB;IAEA,IAAIf,MAAMgB,MAAM,EAAE;QAChBR,OAAOQ,MAAM,GAAG;IAClB;IAEA,OAAOR;AACT;AAEA,MAA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M;wBAACwE;qBAAe;oBACtB7E,SAASV,mBAAmBC;gBAC9B;YACF;QACF;QAEAQ,OAAOyC,GAAG,CAAC;YACT,CAACjD,MAAMqC,IAAI,CAAC,EAAEiD;QAChB;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/models/buildSchema.ts"],"sourcesContent":["import type { IndexOptions, Schema, SchemaOptions, SchemaTypeOptions } from 'mongoose'\nimport type {\n ArrayField,\n Block,\n BlocksField,\n CheckboxField,\n CodeField,\n CollapsibleField,\n DateField,\n EmailField,\n Field,\n FieldAffectingData,\n GroupField,\n JSONField,\n NonPresentationalField,\n NumberField,\n PointField,\n RadioField,\n RelationshipField,\n RichTextField,\n RowField,\n SanitizedConfig,\n SanitizedLocalizationConfig,\n SelectField,\n Tab,\n TabsField,\n TextareaField,\n TextField,\n UploadField,\n} from 'payload'\n\nimport mongoose from 'mongoose'\nimport {\n fieldAffectsData,\n fieldIsLocalized,\n fieldIsPresentationalOnly,\n fieldIsVirtual,\n tabHasName,\n} from 'payload/shared'\n\nexport type BuildSchemaOptions = {\n allowIDField?: boolean\n disableUnique?: boolean\n draftsEnabled?: boolean\n indexSortableFields?: boolean\n options?: SchemaOptions\n}\n\ntype FieldSchemaGenerator = (\n field: Field,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n) => void\n\n/**\n * get a field's defaultValue only if defined and not dynamic so that it can be set on the field schema\n * @param field\n */\nconst formatDefaultValue = (field: FieldAffectingData) =>\n typeof field.defaultValue !== 'undefined' && typeof field.defaultValue !== 'function'\n ? field.defaultValue\n : undefined\n\nconst formatBaseSchema = (field: FieldAffectingData, buildSchemaOptions: BuildSchemaOptions) => {\n const { disableUnique, draftsEnabled, indexSortableFields } = buildSchemaOptions\n const schema: SchemaTypeOptions<unknown> = {\n default: formatDefaultValue(field),\n index: field.index || (!disableUnique && field.unique) || indexSortableFields || false,\n required: false,\n unique: (!disableUnique && field.unique) || false,\n }\n\n if (\n schema.unique &&\n (field.localized ||\n draftsEnabled ||\n (fieldAffectsData(field) &&\n field.type !== 'group' &&\n field.type !== 'tab' &&\n field.required !== true))\n ) {\n schema.sparse = true\n }\n\n if (field.hidden) {\n schema.hidden = true\n }\n\n return schema\n}\n\nconst localizeSchema = (\n entity: NonPresentationalField | Tab,\n schema,\n localization: false | SanitizedLocalizationConfig,\n) => {\n if (fieldIsLocalized(entity) && localization && Array.isArray(localization.locales)) {\n return {\n type: localization.localeCodes.reduce(\n (localeSchema, locale) => ({\n ...localeSchema,\n [locale]: schema,\n }),\n {\n _id: false,\n },\n ),\n localized: true,\n }\n }\n return schema\n}\n\nexport const buildSchema = (\n config: SanitizedConfig,\n configFields: Field[],\n buildSchemaOptions: BuildSchemaOptions = {},\n): Schema => {\n const { allowIDField, options } = buildSchemaOptions\n let fields = {}\n\n let schemaFields = configFields\n\n if (!allowIDField) {\n const idField = schemaFields.find((field) => fieldAffectsData(field) && field.name === 'id')\n if (idField) {\n fields = {\n _id: idField.type === 'number' ? Number : String,\n }\n schemaFields = schemaFields.filter(\n (field) => !(fieldAffectsData(field) && field.name === 'id'),\n )\n }\n }\n\n const schema = new mongoose.Schema(fields, options)\n\n schemaFields.forEach((field) => {\n if (fieldIsVirtual(field)) {\n return\n }\n\n if (!fieldIsPresentationalOnly(field)) {\n const addFieldSchema: FieldSchemaGenerator = fieldToSchemaMap[field.type]\n\n if (addFieldSchema) {\n addFieldSchema(field, schema, config, buildSchemaOptions)\n }\n }\n })\n\n return schema\n}\n\nconst fieldToSchemaMap: Record<string, FieldSchemaGenerator> = {\n array: (\n field: ArrayField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ) => {\n const baseSchema = {\n ...formatBaseSchema(field, buildSchemaOptions),\n type: [\n buildSchema(config, field.fields, {\n allowIDField: true,\n disableUnique: buildSchemaOptions.disableUnique,\n draftsEnabled: buildSchemaOptions.draftsEnabled,\n options: {\n _id: false,\n id: false,\n minimize: false,\n },\n }),\n ],\n }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n blocks: (\n field: BlocksField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const fieldSchema = {\n type: [new mongoose.Schema({}, { _id: false, discriminatorKey: 'blockType' })],\n }\n\n schema.add({\n [field.name]: localizeSchema(field, fieldSchema, config.localization),\n })\n\n field.blocks.forEach((blockItem: Block) => {\n const blockSchema = new mongoose.Schema({}, { _id: false, id: false })\n\n blockItem.fields.forEach((blockField) => {\n const addFieldSchema: FieldSchemaGenerator = fieldToSchemaMap[blockField.type]\n if (addFieldSchema) {\n addFieldSchema(blockField, blockSchema, config, buildSchemaOptions)\n }\n })\n\n if (field.localized && config.localization) {\n config.localization.localeCodes.forEach((localeCode) => {\n // @ts-expect-error Possible incorrect typing in mongoose types, this works\n schema.path(`${field.name}.${localeCode}`).discriminator(blockItem.slug, blockSchema)\n })\n } else {\n // @ts-expect-error Possible incorrect typing in mongoose types, this works\n schema.path(field.name).discriminator(blockItem.slug, blockSchema)\n }\n })\n },\n checkbox: (\n field: CheckboxField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema = { ...formatBaseSchema(field, buildSchemaOptions), type: Boolean }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n code: (\n field: CodeField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema = { ...formatBaseSchema(field, buildSchemaOptions), type: String }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n collapsible: (\n field: CollapsibleField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n field.fields.forEach((subField: Field) => {\n if (fieldIsVirtual(subField)) {\n return\n }\n\n const addFieldSchema: FieldSchemaGenerator = fieldToSchemaMap[subField.type]\n\n if (addFieldSchema) {\n addFieldSchema(subField, schema, config, buildSchemaOptions)\n }\n })\n },\n date: (\n field: DateField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema = { ...formatBaseSchema(field, buildSchemaOptions), type: Date }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n email: (\n field: EmailField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema = { ...formatBaseSchema(field, buildSchemaOptions), type: String }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n group: (\n field: GroupField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const formattedBaseSchema = formatBaseSchema(field, buildSchemaOptions)\n\n // carry indexSortableFields through to versions if drafts enabled\n const indexSortableFields =\n buildSchemaOptions.indexSortableFields &&\n field.name === 'version' &&\n buildSchemaOptions.draftsEnabled\n\n const baseSchema = {\n ...formattedBaseSchema,\n type: buildSchema(config, field.fields, {\n disableUnique: buildSchemaOptions.disableUnique,\n draftsEnabled: buildSchemaOptions.draftsEnabled,\n indexSortableFields,\n options: {\n _id: false,\n id: false,\n minimize: false,\n },\n }),\n }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n json: (\n field: JSONField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema = {\n ...formatBaseSchema(field, buildSchemaOptions),\n type: mongoose.Schema.Types.Mixed,\n }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n number: (\n field: NumberField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema = {\n ...formatBaseSchema(field, buildSchemaOptions),\n type: field.hasMany ? [Number] : Number,\n }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n point: (\n field: PointField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema: SchemaTypeOptions<unknown> = {\n type: {\n type: String,\n enum: ['Point'],\n },\n coordinates: {\n type: [Number],\n default: formatDefaultValue(field),\n required: false,\n },\n }\n if (buildSchemaOptions.disableUnique && field.unique && field.localized) {\n baseSchema.coordinates.sparse = true\n }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n\n if (field.index === true || field.index === undefined) {\n const indexOptions: IndexOptions = {}\n if (!buildSchemaOptions.disableUnique && field.unique) {\n indexOptions.sparse = true\n indexOptions.unique = true\n }\n if (field.localized && config.localization) {\n config.localization.locales.forEach((locale) => {\n schema.index({ [`${field.name}.${locale.code}`]: '2dsphere' }, indexOptions)\n })\n } else {\n schema.index({ [field.name]: '2dsphere' }, indexOptions)\n }\n }\n },\n radio: (\n field: RadioField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema = {\n ...formatBaseSchema(field, buildSchemaOptions),\n type: String,\n enum: field.options.map((option) => {\n if (typeof option === 'object') {\n return option.value\n }\n return option\n }),\n }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n relationship: (\n field: RelationshipField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ) => {\n const hasManyRelations = Array.isArray(field.relationTo)\n let schemaToReturn: { [key: string]: any } = {}\n\n if (field.localized && config.localization) {\n schemaToReturn = {\n type: config.localization.localeCodes.reduce((locales, locale) => {\n let localeSchema: { [key: string]: any } = {}\n\n if (hasManyRelations) {\n localeSchema = {\n ...formatBaseSchema(field, buildSchemaOptions),\n _id: false,\n type: mongoose.Schema.Types.Mixed,\n relationTo: { type: String, enum: field.relationTo },\n value: {\n type: mongoose.Schema.Types.Mixed,\n refPath: `${field.name}.${locale}.relationTo`,\n },\n }\n } else {\n localeSchema = {\n ...formatBaseSchema(field, buildSchemaOptions),\n type: mongoose.Schema.Types.Mixed,\n ref: field.relationTo,\n }\n }\n\n return {\n ...locales,\n [locale]: field.hasMany\n ? { type: [localeSchema], default: formatDefaultValue(field) }\n : localeSchema,\n }\n }, {}),\n localized: true,\n }\n } else if (hasManyRelations) {\n schemaToReturn = {\n ...formatBaseSchema(field, buildSchemaOptions),\n _id: false,\n type: mongoose.Schema.Types.Mixed,\n relationTo: { type: String, enum: field.relationTo },\n value: {\n type: mongoose.Schema.Types.Mixed,\n refPath: `${field.name}.relationTo`,\n },\n }\n\n if (field.hasMany) {\n schemaToReturn = {\n type: [schemaToReturn],\n default: formatDefaultValue(field),\n }\n }\n } else {\n schemaToReturn = {\n ...formatBaseSchema(field, buildSchemaOptions),\n type: mongoose.Schema.Types.Mixed,\n ref: field.relationTo,\n }\n\n if (field.hasMany) {\n schemaToReturn = {\n type: [schemaToReturn],\n default: formatDefaultValue(field),\n }\n }\n }\n\n schema.add({\n [field.name]: schemaToReturn,\n })\n },\n richText: (\n field: RichTextField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema = {\n ...formatBaseSchema(field, buildSchemaOptions),\n type: mongoose.Schema.Types.Mixed,\n }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n row: (\n field: RowField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n field.fields.forEach((subField: Field) => {\n if (fieldIsVirtual(subField)) {\n return\n }\n\n const addFieldSchema: FieldSchemaGenerator = fieldToSchemaMap[subField.type]\n\n if (addFieldSchema) {\n addFieldSchema(subField, schema, config, buildSchemaOptions)\n }\n })\n },\n select: (\n field: SelectField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema = {\n ...formatBaseSchema(field, buildSchemaOptions),\n type: String,\n enum: field.options.map((option) => {\n if (typeof option === 'object') {\n return option.value\n }\n return option\n }),\n }\n\n if (buildSchemaOptions.draftsEnabled || !field.required) {\n baseSchema.enum.push(null)\n }\n\n schema.add({\n [field.name]: localizeSchema(\n field,\n field.hasMany ? [baseSchema] : baseSchema,\n config.localization,\n ),\n })\n },\n tabs: (\n field: TabsField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n field.tabs.forEach((tab) => {\n if (tabHasName(tab)) {\n if (fieldIsVirtual(tab)) {\n return\n }\n const baseSchema = {\n type: buildSchema(config, tab.fields, {\n disableUnique: buildSchemaOptions.disableUnique,\n draftsEnabled: buildSchemaOptions.draftsEnabled,\n options: {\n _id: false,\n id: false,\n minimize: false,\n },\n }),\n }\n\n schema.add({\n [tab.name]: localizeSchema(tab, baseSchema, config.localization),\n })\n } else {\n tab.fields.forEach((subField: Field) => {\n if (fieldIsVirtual(subField)) {\n return\n }\n const addFieldSchema: FieldSchemaGenerator = fieldToSchemaMap[subField.type]\n\n if (addFieldSchema) {\n addFieldSchema(subField, schema, config, buildSchemaOptions)\n }\n })\n }\n })\n },\n text: (\n field: TextField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema = {\n ...formatBaseSchema(field, buildSchemaOptions),\n type: field.hasMany ? [String] : String,\n }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n textarea: (\n field: TextareaField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const baseSchema = { ...formatBaseSchema(field, buildSchemaOptions), type: String }\n\n schema.add({\n [field.name]: localizeSchema(field, baseSchema, config.localization),\n })\n },\n upload: (\n field: UploadField,\n schema: Schema,\n config: SanitizedConfig,\n buildSchemaOptions: BuildSchemaOptions,\n ): void => {\n const hasManyRelations = Array.isArray(field.relationTo)\n let schemaToReturn: { [key: string]: any } = {}\n\n if (field.localized && config.localization) {\n schemaToReturn = {\n type: config.localization.localeCodes.reduce((locales, locale) => {\n let localeSchema: { [key: string]: any } = {}\n\n if (hasManyRelations) {\n localeSchema = {\n ...formatBaseSchema(field, buildSchemaOptions),\n _id: false,\n type: mongoose.Schema.Types.Mixed,\n relationTo: { type: String, enum: field.relationTo },\n value: {\n type: mongoose.Schema.Types.Mixed,\n refPath: `${field.name}.${locale}.relationTo`,\n },\n }\n } else {\n localeSchema = {\n ...formatBaseSchema(field, buildSchemaOptions),\n type: mongoose.Schema.Types.Mixed,\n ref: field.relationTo,\n }\n }\n\n return {\n ...locales,\n [locale]: field.hasMany\n ? { type: [localeSchema], default: formatDefaultValue(field) }\n : localeSchema,\n }\n }, {}),\n localized: true,\n }\n } else if (hasManyRelations) {\n schemaToReturn = {\n ...formatBaseSchema(field, buildSchemaOptions),\n _id: false,\n type: mongoose.Schema.Types.Mixed,\n relationTo: { type: String, enum: field.relationTo },\n value: {\n type: mongoose.Schema.Types.Mixed,\n refPath: `${field.name}.relationTo`,\n },\n }\n\n if (field.hasMany) {\n schemaToReturn = {\n type: [schemaToReturn],\n default: formatDefaultValue(field),\n }\n }\n } else {\n schemaToReturn = {\n ...formatBaseSchema(field, buildSchemaOptions),\n type: mongoose.Schema.Types.Mixed,\n ref: field.relationTo,\n }\n\n if (field.hasMany) {\n schemaToReturn = {\n type: [schemaToReturn],\n default: formatDefaultValue(field),\n }\n }\n }\n\n schema.add({\n [field.name]: schemaToReturn,\n })\n },\n}\n"],"names":["mongoose","fieldAffectsData","fieldIsLocalized","fieldIsPresentationalOnly","fieldIsVirtual","tabHasName","formatDefaultValue","field","defaultValue","undefined","formatBaseSchema","buildSchemaOptions","disableUnique","draftsEnabled","indexSortableFields","schema","default","index","unique","required","localized","type","sparse","hidden","localizeSchema","entity","localization","Array","isArray","locales","localeCodes","reduce","localeSchema","locale","_id","buildSchema","config","configFields","allowIDField","options","fields","schemaFields","idField","find","name","Number","String","filter","Schema","forEach","addFieldSchema","fieldToSchemaMap","array","baseSchema","id","minimize","add","blocks","fieldSchema","discriminatorKey","blockItem","blockSchema","blockField","localeCode","path","discriminator","slug","checkbox","Boolean","code","collapsible","subField","date","Date","email","group","formattedBaseSchema","json","Types","Mixed","number","hasMany","point","enum","coordinates","indexOptions","radio","map","option","value","relationship","hasManyRelations","relationTo","schemaToReturn","refPath","ref","richText","row","select","push","tabs","tab","text","textarea","upload"],"mappings":"AA+BA,OAAOA,cAAc,WAAU;AAC/B,SACEC,gBAAgB,EAChBC,gBAAgB,EAChBC,yBAAyB,EACzBC,cAAc,EACdC,UAAU,QACL,iBAAgB;AAiBvB;;;CAGC,GACD,MAAMC,qBAAqB,CAACC,QAC1B,OAAOA,MAAMC,YAAY,KAAK,eAAe,OAAOD,MAAMC,YAAY,KAAK,aACvED,MAAMC,YAAY,GAClBC;AAEN,MAAMC,mBAAmB,CAACH,OAA2BI;IACnD,MAAM,EAAEC,aAAa,EAAEC,aAAa,EAAEC,mBAAmB,EAAE,GAAGH;IAC9D,MAAMI,SAAqC;QACzCC,SAASV,mBAAmBC;QAC5BU,OAAOV,MAAMU,KAAK,IAAK,CAACL,iBAAiBL,MAAMW,MAAM,IAAKJ,uBAAuB;QACjFK,UAAU;QACVD,QAAQ,AAAC,CAACN,iBAAiBL,MAAMW,MAAM,IAAK;IAC9C;IAEA,IACEH,OAAOG,MAAM,IACZX,CAAAA,MAAMa,SAAS,IACdP,iBACCZ,iBAAiBM,UAChBA,MAAMc,IAAI,KAAK,WACfd,MAAMc,IAAI,KAAK,SACfd,MAAMY,QAAQ,KAAK,IAAI,GAC3B;QACAJ,OAAOO,MAAM,GAAG;IAClB;IAEA,IAAIf,MAAMgB,MAAM,EAAE;QAChBR,OAAOQ,MAAM,GAAG;IAClB;IAEA,OAAOR;AACT;AAEA,MAAMS,iBAAiB,CACrBC,QACAV,QACAW;IAEA,IAAIxB,iBAAiBuB,WAAWC,gBAAgBC,MAAMC,OAAO,CAACF,aAA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B;YAEA,IAAIrF,MAAM0E,OAAO,EAAE;gBACjBY,iBAAiB;oBACfxE,MAAM;wBAACwE;qBAAe;oBACtB7E,SAASV,mBAAmBC;gBAC9B;YACF;QACF;QAEAQ,OAAOyC,GAAG,CAAC;YACT,CAACjD,MAAMqC,IAAI,CAAC,EAAEiD;QAChB;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"queryDrafts.d.ts","sourceRoot":"","sources":["../src/queryDrafts.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAkB,WAAW,EAAE,MAAM,SAAS,CAAA;AAU1D,eAAO,MAAM,WAAW,EAAE,WAiGzB,CAAA"}
1
+ {"version":3,"file":"queryDrafts.d.ts","sourceRoot":"","sources":["../src/queryDrafts.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAkB,WAAW,EAAE,MAAM,SAAS,CAAA;AAW1D,eAAO,MAAM,WAAW,EAAE,WA+HzB,CAAA"}
@@ -1,8 +1,9 @@
1
1
  import { combineQueries, flattenWhereToOperators } from 'payload';
2
2
  import { buildSortParam } from './queries/buildSortParam.js';
3
+ import { buildJoinAggregation } from './utilities/buildJoinAggregation.js';
3
4
  import { sanitizeInternalFields } from './utilities/sanitizeInternalFields.js';
4
5
  import { withSession } from './withSession.js';
5
- export const queryDrafts = async function queryDrafts({ collection, limit, locale, page, pagination, req = {}, sort: sortArg, where }) {
6
+ export const queryDrafts = async function queryDrafts({ collection, joins, limit, locale, page, pagination, req = {}, sort: sortArg, where }) {
6
7
  const VersionModel = this.versions[collection];
7
8
  const collectionConfig = this.payload.collections[collection].config;
8
9
  const options = await withSession(this, req);
@@ -68,7 +69,23 @@ export const queryDrafts = async function queryDrafts({ collection, limit, local
68
69
  // limit must also be set here, it's ignored when pagination is false
69
70
  paginationOptions.options.limit = limit;
70
71
  }
71
- const result = await VersionModel.paginate(versionQuery, paginationOptions);
72
+ let result;
73
+ const aggregate = await buildJoinAggregation({
74
+ adapter: this,
75
+ collection,
76
+ collectionConfig,
77
+ joins,
78
+ limit,
79
+ locale,
80
+ query: versionQuery,
81
+ versions: true
82
+ });
83
+ // build join aggregation
84
+ if (aggregate) {
85
+ result = await VersionModel.aggregatePaginate(VersionModel.aggregate(aggregate), paginationOptions);
86
+ } else {
87
+ result = await VersionModel.paginate(versionQuery, paginationOptions);
88
+ }
72
89
  const docs = JSON.parse(JSON.stringify(result.docs));
73
90
  return {
74
91
  ...result,
@@ -76,9 +93,7 @@ export const queryDrafts = async function queryDrafts({ collection, limit, local
76
93
  doc = {
77
94
  _id: doc.parent,
78
95
  id: doc.parent,
79
- ...doc.version,
80
- createdAt: doc.createdAt,
81
- updatedAt: doc.updatedAt
96
+ ...doc.version
82
97
  };
83
98
  return sanitizeInternalFields(doc);
84
99
  })
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/queryDrafts.ts"],"sourcesContent":["import type { PaginateOptions } from 'mongoose'\nimport type { PayloadRequest, QueryDrafts } from 'payload'\n\nimport { combineQueries, flattenWhereToOperators } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { buildSortParam } from './queries/buildSortParam.js'\nimport { sanitizeInternalFields } from './utilities/sanitizeInternalFields.js'\nimport { withSession } from './withSession.js'\n\nexport const queryDrafts: QueryDrafts = async function queryDrafts(\n this: MongooseAdapter,\n { collection, limit, locale, page, pagination, req = {} as PayloadRequest, sort: sortArg, where },\n) {\n const VersionModel = this.versions[collection]\n const collectionConfig = this.payload.collections[collection].config\n const options = await withSession(this, req)\n\n let hasNearConstraint\n let sort\n\n if (where) {\n const constraints = flattenWhereToOperators(where)\n hasNearConstraint = constraints.some((prop) => Object.keys(prop).some((key) => key === 'near'))\n }\n\n if (!hasNearConstraint) {\n sort = buildSortParam({\n config: this.payload.config,\n fields: collectionConfig.fields,\n locale,\n sort: sortArg || collectionConfig.defaultSort,\n timestamps: true,\n })\n }\n\n const combinedWhere = combineQueries({ latest: { equals: true } }, where)\n\n const versionQuery = await VersionModel.buildQuery({\n locale,\n payload: this.payload,\n where: combinedWhere,\n })\n\n // useEstimatedCount is faster, but not accurate, as it ignores any filters. It is thus set to true if there are no filters.\n const useEstimatedCount =\n hasNearConstraint || !versionQuery || Object.keys(versionQuery).length === 0\n const paginationOptions: PaginateOptions = {\n forceCountFn: hasNearConstraint,\n lean: true,\n leanWithId: true,\n options,\n page,\n pagination,\n sort,\n useEstimatedCount,\n }\n\n if (this.collation) {\n const defaultLocale = 'en'\n paginationOptions.collation = {\n locale: locale && locale !== 'all' && locale !== '*' ? locale : defaultLocale,\n ...this.collation,\n }\n }\n\n if (\n !useEstimatedCount &&\n Object.keys(versionQuery).length === 0 &&\n this.disableIndexHints !== true\n ) {\n // Improve the performance of the countDocuments query which is used if useEstimatedCount is set to false by adding\n // a hint. By default, if no hint is provided, MongoDB does not use an indexed field to count the returned documents,\n // which makes queries very slow. This only happens when no query (filter) is provided. If one is provided, it uses\n // the correct indexed field\n paginationOptions.useCustomCountFn = () => {\n return Promise.resolve(\n VersionModel.countDocuments(versionQuery, {\n hint: { _id: 1 },\n }),\n )\n }\n }\n\n if (limit > 0) {\n paginationOptions.limit = limit\n // limit must also be set here, it's ignored when pagination is false\n paginationOptions.options.limit = limit\n }\n\n const result = await VersionModel.paginate(versionQuery, paginationOptions)\n const docs = JSON.parse(JSON.stringify(result.docs))\n\n return {\n ...result,\n docs: docs.map((doc) => {\n doc = {\n _id: doc.parent,\n id: doc.parent,\n ...doc.version,\n createdAt: doc.createdAt,\n updatedAt: doc.updatedAt,\n }\n\n return sanitizeInternalFields(doc)\n }),\n }\n}\n"],"names":["combineQueries","flattenWhereToOperators","buildSortParam","sanitizeInternalFields","withSession","queryDrafts","collection","limit","locale","page","pagination","req","sort","sortArg","where","VersionModel","versions","collectionConfig","payload","collections","config","options","hasNearConstraint","constraints","some","prop","Object","keys","key","fields","defaultSort","timestamps","combinedWhere","latest","equals","versionQuery","buildQuery","useEstimatedCount","length","paginationOptions","forceCountFn","lean","leanWithId","collation","defaultLocale","disableIndexHints","useCustomCountFn","Promise","resolve","countDocuments","hint","_id","result","paginate","docs","JSON","parse","stringify","map","doc","parent","id","version","createdAt","updatedAt"],"mappings":"AAGA,SAASA,cAAc,EAAEC,uBAAuB,QAAQ,UAAS;AAIjE,SAASC,cAAc,QAAQ,8BAA6B;AAC5D,SAASC,sBAAsB,QAAQ,wCAAuC;AAC9E,SAASC,WAAW,QAAQ,mBAAkB;AAE9C,OAAO,MAAMC,cAA2B,eAAeA,YAErD,EAAEC,UAAU,EAAEC,KAAK,EAAEC,MAAM,EAAEC,IAAI,EAAEC,UAAU,EAAEC,MAAM,CAAC,CAAmB,EAAEC,MAAMC,OAAO,EAAEC,KAAK,EAAE;IAEjG,MAAMC,eAAe,IAAI,CAACC,QAAQ,CAACV,WAAW;IAC9C,MAAMW,mBAAmB,IAAI,CAACC,OAAO,CAACC,WAAW,CAACb,WAAW,CAACc,MAAM;IACpE,MAAMC,UAAU,MAAMjB,YAAY,IAAI,EAAEO;IAExC,IAAIW;IACJ,IAAIV;IAEJ,IAAIE,OAAO;QACT,MAAMS,cAActB,wBAAwBa;QAC5CQ,oBAAoBC,YAAYC,IAAI,CAAC,CAACC,OAASC,OAAOC,IAAI,CAACF,MAAMD,IAAI,CAAC,CAACI,MAAQA,QAAQ;IACzF;IAEA,IAAI,CAACN,mBAAmB;QACtBV,OAAOV,eAAe;YACpBkB,QAAQ,IAAI,CAACF,OAAO,CAACE,MAAM;YAC3BS,QAAQZ,iBAAiBY,MAAM;YAC/BrB;YACAI,MAAMC,WAAWI,iBAAiBa,WAAW;YAC7CC,YAAY;QACd;IACF;IAEA,MAAMC,gBAAgBhC,eAAe;QAAEiC,QAAQ;YAAEC,QAAQ;QAAK;IAAE,GAAGpB;IAEnE,MAAMqB,eAAe,MAAMpB,aAAaqB,UAAU,CAAC;QACjD5B;QACAU,SAAS,IAAI,CAACA,OAAO;QACrBJ,OAAOkB;IACT;IAEA,4HAA4H;IAC5H,MAAMK,oBACJf,qBAAqB,CAACa,gBAAgBT,OAAOC,IAAI,CAACQ,cAAcG,MAAM,KAAK;IAC7E,MAAMC,oBAAqC;QACzCC,cAAclB;QACdmB,MAAM;QACNC,YAAY;QACZrB;QACAZ;QACAC;QACAE;QACAyB;IACF;IAEA,IAAI,IAAI,CAACM,SAAS,EAAE;QAClB,MAAMC,gBAAgB;QACtBL,kBAAkBI,SAAS,GAAG;YAC5BnC,QAAQA,UAAUA,WAAW,SAASA,WAAW,MAAMA,SAASoC;YAChE,GAAG,IAAI,CAACD,SAAS;QACnB;IACF;IAEA,IACE,CAACN,qBACDX,OAAOC,IAAI,CAACQ,cAAcG,MAAM,KAAK,KACrC,IAAI,CAACO,iBAAiB,KAAK,MAC3B;QACA,mHAAmH;QACnH,qHAAqH;QACrH,mHAAmH;QACnH,4BAA4B;QAC5BN,kBAAkBO,gBAAgB,GAAG;YACnC,OAAOC,QAAQC,OAAO,CACpBjC,aAAakC,cAAc,CAACd,cAAc;gBACxCe,MAAM;oBAAEC,KAAK;gBAAE;YACjB;QAEJ;IACF;IAEA,IAAI5C,QAAQ,GAAG;QACbgC,kBAAkBhC,KAAK,GAAGA;QAC1B,qEAAqE;QACrEgC,kBAAkBlB,OAAO,CAACd,KAAK,GAAGA;IACpC;IAEA,MAAM6C,SAAS,MAAMrC,aAAasC,QAAQ,CAAClB,cAAcI;IACzD,MAAMe,OAAOC,KAAKC,KAAK,CAACD,KAAKE,SAAS,CAACL,OAAOE,IAAI;IAElD,OAAO;QACL,GAAGF,MAAM;QACTE,MAAMA,KAAKI,GAAG,CAAC,CAACC;YACdA,MAAM;gBACJR,KAAKQ,IAAIC,MAAM;gBACfC,IAAIF,IAAIC,MAAM;gBACd,GAAGD,IAAIG,OAAO;gBACdC,WAAWJ,IAAII,SAAS;gBACxBC,WAAWL,IAAIK,SAAS;YAC1B;YAEA,OAAO7D,uBAAuBwD;QAChC;IACF;AACF,EAAC"}
1
+ {"version":3,"sources":["../src/queryDrafts.ts"],"sourcesContent":["import type { PaginateOptions } from 'mongoose'\nimport type { PayloadRequest, QueryDrafts } from 'payload'\n\nimport { combineQueries, flattenWhereToOperators } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { buildSortParam } from './queries/buildSortParam.js'\nimport { buildJoinAggregation } from './utilities/buildJoinAggregation.js'\nimport { sanitizeInternalFields } from './utilities/sanitizeInternalFields.js'\nimport { withSession } from './withSession.js'\n\nexport const queryDrafts: QueryDrafts = async function queryDrafts(\n this: MongooseAdapter,\n {\n collection,\n joins,\n limit,\n locale,\n page,\n pagination,\n req = {} as PayloadRequest,\n sort: sortArg,\n where,\n },\n) {\n const VersionModel = this.versions[collection]\n const collectionConfig = this.payload.collections[collection].config\n const options = await withSession(this, req)\n\n let hasNearConstraint\n let sort\n\n if (where) {\n const constraints = flattenWhereToOperators(where)\n hasNearConstraint = constraints.some((prop) => Object.keys(prop).some((key) => key === 'near'))\n }\n\n if (!hasNearConstraint) {\n sort = buildSortParam({\n config: this.payload.config,\n fields: collectionConfig.fields,\n locale,\n sort: sortArg || collectionConfig.defaultSort,\n timestamps: true,\n })\n }\n\n const combinedWhere = combineQueries({ latest: { equals: true } }, where)\n\n const versionQuery = await VersionModel.buildQuery({\n locale,\n payload: this.payload,\n where: combinedWhere,\n })\n\n // useEstimatedCount is faster, but not accurate, as it ignores any filters. It is thus set to true if there are no filters.\n const useEstimatedCount =\n hasNearConstraint || !versionQuery || Object.keys(versionQuery).length === 0\n const paginationOptions: PaginateOptions = {\n forceCountFn: hasNearConstraint,\n lean: true,\n leanWithId: true,\n options,\n page,\n pagination,\n sort,\n useEstimatedCount,\n }\n\n if (this.collation) {\n const defaultLocale = 'en'\n paginationOptions.collation = {\n locale: locale && locale !== 'all' && locale !== '*' ? locale : defaultLocale,\n ...this.collation,\n }\n }\n\n if (\n !useEstimatedCount &&\n Object.keys(versionQuery).length === 0 &&\n this.disableIndexHints !== true\n ) {\n // Improve the performance of the countDocuments query which is used if useEstimatedCount is set to false by adding\n // a hint. By default, if no hint is provided, MongoDB does not use an indexed field to count the returned documents,\n // which makes queries very slow. This only happens when no query (filter) is provided. If one is provided, it uses\n // the correct indexed field\n paginationOptions.useCustomCountFn = () => {\n return Promise.resolve(\n VersionModel.countDocuments(versionQuery, {\n hint: { _id: 1 },\n }),\n )\n }\n }\n\n if (limit > 0) {\n paginationOptions.limit = limit\n // limit must also be set here, it's ignored when pagination is false\n paginationOptions.options.limit = limit\n }\n\n let result\n\n const aggregate = await buildJoinAggregation({\n adapter: this,\n collection,\n collectionConfig,\n joins,\n limit,\n locale,\n query: versionQuery,\n versions: true,\n })\n\n // build join aggregation\n if (aggregate) {\n result = await VersionModel.aggregatePaginate(\n VersionModel.aggregate(aggregate),\n paginationOptions,\n )\n } else {\n result = await VersionModel.paginate(versionQuery, paginationOptions)\n }\n\n const docs = JSON.parse(JSON.stringify(result.docs))\n\n return {\n ...result,\n docs: docs.map((doc) => {\n doc = {\n _id: doc.parent,\n id: doc.parent,\n ...doc.version,\n }\n\n return sanitizeInternalFields(doc)\n }),\n }\n}\n"],"names":["combineQueries","flattenWhereToOperators","buildSortParam","buildJoinAggregation","sanitizeInternalFields","withSession","queryDrafts","collection","joins","limit","locale","page","pagination","req","sort","sortArg","where","VersionModel","versions","collectionConfig","payload","collections","config","options","hasNearConstraint","constraints","some","prop","Object","keys","key","fields","defaultSort","timestamps","combinedWhere","latest","equals","versionQuery","buildQuery","useEstimatedCount","length","paginationOptions","forceCountFn","lean","leanWithId","collation","defaultLocale","disableIndexHints","useCustomCountFn","Promise","resolve","countDocuments","hint","_id","result","aggregate","adapter","query","aggregatePaginate","paginate","docs","JSON","parse","stringify","map","doc","parent","id","version"],"mappings":"AAGA,SAASA,cAAc,EAAEC,uBAAuB,QAAQ,UAAS;AAIjE,SAASC,cAAc,QAAQ,8BAA6B;AAC5D,SAASC,oBAAoB,QAAQ,sCAAqC;AAC1E,SAASC,sBAAsB,QAAQ,wCAAuC;AAC9E,SAASC,WAAW,QAAQ,mBAAkB;AAE9C,OAAO,MAAMC,cAA2B,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,MAAMA,SAASoC;YAChE,GAAG,IAAI,CAACD,SAAS;QACnB;IACF;IAEA,IACE,CAACN,qBACDX,OAAOC,IAAI,CAACQ,cAAcG,MAAM,KAAK,KACrC,IAAI,CAACO,iBAAiB,KAAK,MAC3B;QACA,mHAAmH;QACnH,qHAAqH;QACrH,mHAAmH;QACnH,4BAA4B;QAC5BN,kBAAkBO,gBAAgB,GAAG;YACnC,OAAOC,QAAQC,OAAO,CACpBjC,aAAakC,cAAc,CAACd,cAAc;gBACxCe,MAAM;oBAAEC,KAAK;gBAAE;YACjB;QAEJ;IACF;IAEA,IAAI5C,QAAQ,GAAG;QACbgC,kBAAkBhC,KAAK,GAAGA;QAC1B,qEAAqE;QACrEgC,kBAAkBlB,OAAO,CAACd,KAAK,GAAGA;IACpC;IAEA,IAAI6C;IAEJ,MAAMC,YAAY,MAAMpD,qBAAqB;QAC3CqD,SAAS,IAAI;QACbjD;QACAY;QACAX;QACAC;QACAC;QACA+C,OAAOpB;QACPnB,UAAU;IACZ;IAEA,yBAAyB;IACzB,IAAIqC,WAAW;QACbD,SAAS,MAAMrC,aAAayC,iBAAiB,CAC3CzC,aAAasC,SAAS,CAACA,YACvBd;IAEJ,OAAO;QACLa,SAAS,MAAMrC,aAAa0C,QAAQ,CAACtB,cAAcI;IACrD;IAEA,MAAMmB,OAAOC,KAAKC,KAAK,CAACD,KAAKE,SAAS,CAACT,OAAOM,IAAI;IAElD,OAAO;QACL,GAAGN,MAAM;QACTM,MAAMA,KAAKI,GAAG,CAAC,CAACC;YACdA,MAAM;gBACJZ,KAAKY,IAAIC,MAAM;gBACfC,IAAIF,IAAIC,MAAM;gBACd,GAAGD,IAAIG,OAAO;YAChB;YAEA,OAAOhE,uBAAuB6D;QAChC;IACF;AACF,EAAC"}
@@ -9,7 +9,9 @@ type BuildJoinAggregationArgs = {
9
9
  limit?: number;
10
10
  locale: string;
11
11
  query?: Where;
12
+ /** whether the query is from drafts */
13
+ versions?: boolean;
12
14
  };
13
- export declare const buildJoinAggregation: ({ adapter, collection, collectionConfig, joins, limit, locale, query, }: BuildJoinAggregationArgs) => Promise<PipelineStage[] | undefined>;
15
+ export declare const buildJoinAggregation: ({ adapter, collection, collectionConfig, joins, limit, locale, query, versions, }: BuildJoinAggregationArgs) => Promise<PipelineStage[] | undefined>;
14
16
  export {};
15
17
  //# sourceMappingURL=buildJoinAggregation.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"buildJoinAggregation.d.ts","sourceRoot":"","sources":["../../src/utilities/buildJoinAggregation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAC7C,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,yBAAyB,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAE1F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAIlD,KAAK,wBAAwB,GAAG;IAC9B,OAAO,EAAE,eAAe,CAAA;IACxB,UAAU,EAAE,cAAc,CAAA;IAC1B,gBAAgB,EAAE,yBAAyB,CAAA;IAC3C,KAAK,EAAE,SAAS,CAAA;IAEhB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,MAAM,EAAE,MAAM,CAAA;IAEd,KAAK,CAAC,EAAE,KAAK,CAAA;CACd,CAAA;AAED,eAAO,MAAM,oBAAoB,4EAQ9B,wBAAwB,KAAG,OAAO,CAAC,aAAa,EAAE,GAAG,SAAS,CAmJhE,CAAA"}
1
+ {"version":3,"file":"buildJoinAggregation.d.ts","sourceRoot":"","sources":["../../src/utilities/buildJoinAggregation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAC7C,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,yBAAyB,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAE1F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAIlD,KAAK,wBAAwB,GAAG;IAC9B,OAAO,EAAE,eAAe,CAAA;IACxB,UAAU,EAAE,cAAc,CAAA;IAC1B,gBAAgB,EAAE,yBAAyB,CAAA;IAC3C,KAAK,EAAE,SAAS,CAAA;IAEhB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,MAAM,EAAE,MAAM,CAAA;IAEd,KAAK,CAAC,EAAE,KAAK,CAAA;IACb,uCAAuC;IACvC,QAAQ,CAAC,EAAE,OAAO,CAAA;CACnB,CAAA;AAED,eAAO,MAAM,oBAAoB,sFAS9B,wBAAwB,KAAG,OAAO,CAAC,aAAa,EAAE,GAAG,SAAS,CAmJhE,CAAA"}
@@ -1,5 +1,5 @@
1
1
  import { buildSortParam } from '../queries/buildSortParam.js';
2
- export const buildJoinAggregation = async ({ adapter, collection, collectionConfig, joins, limit, locale, query })=>{
2
+ export const buildJoinAggregation = async ({ adapter, collection, collectionConfig, joins, limit, locale, query, versions })=>{
3
3
  if (Object.keys(collectionConfig.joins).length === 0 || joins === false) {
4
4
  return;
5
5
  }
@@ -56,13 +56,13 @@ export const buildJoinAggregation = async ({ adapter, collection, collectionConf
56
56
  }
57
57
  if (adapter.payload.config.localization && locale === 'all') {
58
58
  adapter.payload.config.localization.localeCodes.forEach((code)=>{
59
- const as = `${join.schemaPath}${code}`;
59
+ const as = `${versions ? `version.${join.schemaPath}` : join.schemaPath}${code}`;
60
60
  aggregate.push({
61
61
  $lookup: {
62
62
  as: `${as}.docs`,
63
63
  foreignField: `${join.field.on}${code}`,
64
64
  from: slug,
65
- localField: '_id',
65
+ localField: versions ? 'parent' : '_id',
66
66
  pipeline
67
67
  }
68
68
  }, {
@@ -99,13 +99,13 @@ export const buildJoinAggregation = async ({ adapter, collection, collectionConf
99
99
  });
100
100
  } else {
101
101
  const localeSuffix = join.field.localized && adapter.payload.config.localization && locale ? `.${locale}` : '';
102
- const as = `${join.schemaPath}${localeSuffix}`;
102
+ const as = `${versions ? `version.${join.schemaPath}` : join.schemaPath}${localeSuffix}`;
103
103
  aggregate.push({
104
104
  $lookup: {
105
105
  as: `${as}.docs`,
106
106
  foreignField: `${join.field.on}${localeSuffix}`,
107
107
  from: slug,
108
- localField: '_id',
108
+ localField: versions ? 'parent' : '_id',
109
109
  pipeline
110
110
  }
111
111
  }, {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utilities/buildJoinAggregation.ts"],"sourcesContent":["import type { PipelineStage } from 'mongoose'\nimport type { CollectionSlug, JoinQuery, SanitizedCollectionConfig, Where } from 'payload'\n\nimport type { MongooseAdapter } from '../index.js'\n\nimport { buildSortParam } from '../queries/buildSortParam.js'\n\ntype BuildJoinAggregationArgs = {\n adapter: MongooseAdapter\n collection: CollectionSlug\n collectionConfig: SanitizedCollectionConfig\n joins: JoinQuery\n // the number of docs to get at the top collection level\n limit?: number\n locale: string\n // the where clause for the top collection\n query?: Where\n}\n\nexport const buildJoinAggregation = async ({\n adapter,\n collection,\n collectionConfig,\n joins,\n limit,\n locale,\n query,\n}: BuildJoinAggregationArgs): Promise<PipelineStage[] | undefined> => {\n if (Object.keys(collectionConfig.joins).length === 0 || joins === false) {\n return\n }\n\n const joinConfig = adapter.payload.collections[collection].config.joins\n const aggregate: PipelineStage[] = [\n {\n $sort: { createdAt: -1 },\n },\n ]\n\n if (query) {\n aggregate.push({\n $match: query,\n })\n }\n\n if (limit) {\n aggregate.push({\n $limit: limit,\n })\n }\n\n for (const slug of Object.keys(joinConfig)) {\n for (const join of joinConfig[slug]) {\n const joinModel = adapter.collections[join.field.collection]\n\n const {\n limit: limitJoin = 10,\n sort: sortJoin,\n where: whereJoin,\n } = joins?.[join.schemaPath] || {}\n\n const sort = buildSortParam({\n config: adapter.payload.config,\n fields: adapter.payload.collections[slug].config.fields,\n locale,\n sort: sortJoin || collectionConfig.defaultSort,\n timestamps: true,\n })\n const sortProperty = Object.keys(sort)[0]\n const sortDirection = sort[sortProperty] === 'asc' ? 1 : -1\n\n const $match = await joinModel.buildQuery({\n locale,\n payload: adapter.payload,\n where: whereJoin,\n })\n\n const pipeline: Exclude<PipelineStage, PipelineStage.Merge | PipelineStage.Out>[] = [\n { $match },\n {\n $sort: { [sortProperty]: sortDirection },\n },\n ]\n\n if (limitJoin > 0) {\n pipeline.push({\n $limit: limitJoin + 1,\n })\n }\n\n if (adapter.payload.config.localization && locale === 'all') {\n adapter.payload.config.localization.localeCodes.forEach((code) => {\n const as = `${join.schemaPath}${code}`\n\n aggregate.push(\n {\n $lookup: {\n as: `${as}.docs`,\n foreignField: `${join.field.on}${code}`,\n from: slug,\n localField: '_id',\n pipeline,\n },\n },\n {\n $addFields: {\n [`${as}.docs`]: {\n $map: {\n as: 'doc',\n in: '$$doc._id',\n input: `$${as}.docs`,\n },\n }, // Slicing the docs to match the limit\n [`${as}.hasNextPage`]: limitJoin\n ? { $gt: [{ $size: `$${as}.docs` }, limitJoin] }\n : false,\n // Boolean indicating if more docs than limit\n },\n },\n )\n if (limitJoin > 0) {\n aggregate.push({\n $addFields: {\n [`${as}.docs`]: {\n $slice: [`$${as}.docs`, limitJoin],\n },\n },\n })\n }\n })\n } else {\n const localeSuffix =\n join.field.localized && adapter.payload.config.localization && locale ? `.${locale}` : ''\n const as = `${join.schemaPath}${localeSuffix}`\n\n aggregate.push(\n {\n $lookup: {\n as: `${as}.docs`,\n foreignField: `${join.field.on}${localeSuffix}`,\n from: slug,\n localField: '_id',\n pipeline,\n },\n },\n {\n $addFields: {\n [`${as}.docs`]: {\n $map: {\n as: 'doc',\n in: '$$doc._id',\n input: `$${as}.docs`,\n },\n }, // Slicing the docs to match the limit\n [`${as}.hasNextPage`]: {\n $gt: [{ $size: `$${as}.docs` }, limitJoin || Number.MAX_VALUE],\n }, // Boolean indicating if more docs than limit\n },\n },\n )\n if (limitJoin > 0) {\n aggregate.push({\n $addFields: {\n [`${as}.docs`]: {\n $slice: [`$${as}.docs`, limitJoin],\n },\n },\n })\n }\n }\n }\n }\n\n return aggregate\n}\n"],"names":["buildSortParam","buildJoinAggregation","adapter","collection","collectionConfig","joins","limit","locale","query","Object","keys","length","joinConfig","payload","collections","config","aggregate","$sort","createdAt","push","$match","$limit","slug","join","joinModel","field","limitJoin","sort","sortJoin","where","whereJoin","schemaPath","fields","defaultSort","timestamps","sortProperty","sortDirection","buildQuery","pipeline","localization","localeCodes","forEach","code","as","$lookup","foreignField","on","from","localField","$addFields","$map","in","input","$gt","$size","$slice","localeSuffix","localized","Number","MAX_VALUE"],"mappings":"AAKA,SAASA,cAAc,QAAQ,+BAA8B;AAc7D,OAAO,MAAMC,uBAAuB,OAAO,EACzCC,OAAO,EACPC,UAAU,EACVC,gBAAgB,EAChBC,KAAK,EACLC,KAAK,EACLC,MAAM,EACNC,KAAK,EACoB;IACzB,IAAIC,OAAOC,IAAI,CAACN,iBAAiBC,KAAK,EAAEM,MAAM,KAAK,KAAKN,UAAU,OAAO;QACvE;IACF;IAEA,MAAMO,aAAaV,QAAQW,OAAO,CAACC,WAAW,CAACX,WAAW,CAACY,MAAM,CAACV,KAAK;IACvE,MAAMW,YAA6B;QACjC;YACEC,OAAO;gBAAEC,WAAW,CAAC;YAAE;QACzB;KACD;IAED,IAAIV,OAAO;QACTQ,UAAUG,IAAI,CAAC;YACbC,QAAQZ;QACV;IACF;IAEA,IAAIF,OAAO;QACTU,UAAUG,IAAI,CAAC;YACbE,QAAQf;QACV;IACF;IAEA,KAAK,MAAMgB,QAAQb,OAAOC,IAAI,CAACE,YAAa;QAC1C,KAAK,MAAMW,QAAQX,UAAU,CAACU,KAAK,CAAE;YACnC,MAAME,YAAYtB,QAAQY,WAAW,CAACS,KAAKE,KAAK,CAACtB,UAAU,CAAC;YAE5D,MAAM,EACJG,OAAOoB,YAAY,EAAE,EACrBC,MAAMC,QAAQ,EACdC,OAAOC,SAAS,EACjB,GAAGzB,OAAO,CAACkB,KAAKQ,UAAU,CAAC,IAAI,CAAC;YAEjC,MAAMJ,OAAO3B,eAAe;gBAC1Be,QAAQb,QAAQW,OAAO,CAACE,MAAM;gBAC9BiB,QAAQ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GAAG;oBACjBV,UAAUG,IAAI,CAAC;wBACb8B,YAAY;4BACV,CAAC,CAAC,EAAEN,GAAG,KAAK,CAAC,CAAC,EAAE;gCACdY,QAAQ;oCAAC,CAAC,CAAC,EAAEZ,GAAG,KAAK,CAAC;oCAAEjB;iCAAU;4BACpC;wBACF;oBACF;gBACF;YACF;QACF;IACF;IAEA,OAAOV;AACT,EAAC"}
1
+ {"version":3,"sources":["../../src/utilities/buildJoinAggregation.ts"],"sourcesContent":["import type { PipelineStage } from 'mongoose'\nimport type { CollectionSlug, JoinQuery, SanitizedCollectionConfig, Where } from 'payload'\n\nimport type { MongooseAdapter } from '../index.js'\n\nimport { buildSortParam } from '../queries/buildSortParam.js'\n\ntype BuildJoinAggregationArgs = {\n adapter: MongooseAdapter\n collection: CollectionSlug\n collectionConfig: SanitizedCollectionConfig\n joins: JoinQuery\n // the number of docs to get at the top collection level\n limit?: number\n locale: string\n // the where clause for the top collection\n query?: Where\n /** whether the query is from drafts */\n versions?: boolean\n}\n\nexport const buildJoinAggregation = async ({\n adapter,\n collection,\n collectionConfig,\n joins,\n limit,\n locale,\n query,\n versions,\n}: BuildJoinAggregationArgs): Promise<PipelineStage[] | undefined> => {\n if (Object.keys(collectionConfig.joins).length === 0 || joins === false) {\n return\n }\n\n const joinConfig = adapter.payload.collections[collection].config.joins\n const aggregate: PipelineStage[] = [\n {\n $sort: { createdAt: -1 },\n },\n ]\n\n if (query) {\n aggregate.push({\n $match: query,\n })\n }\n\n if (limit) {\n aggregate.push({\n $limit: limit,\n })\n }\n\n for (const slug of Object.keys(joinConfig)) {\n for (const join of joinConfig[slug]) {\n const joinModel = adapter.collections[join.field.collection]\n\n const {\n limit: limitJoin = 10,\n sort: sortJoin,\n where: whereJoin,\n } = joins?.[join.schemaPath] || {}\n\n const sort = buildSortParam({\n config: adapter.payload.config,\n fields: adapter.payload.collections[slug].config.fields,\n locale,\n sort: sortJoin || collectionConfig.defaultSort,\n timestamps: true,\n })\n const sortProperty = Object.keys(sort)[0]\n const sortDirection = sort[sortProperty] === 'asc' ? 1 : -1\n\n const $match = await joinModel.buildQuery({\n locale,\n payload: adapter.payload,\n where: whereJoin,\n })\n\n const pipeline: Exclude<PipelineStage, PipelineStage.Merge | PipelineStage.Out>[] = [\n { $match },\n {\n $sort: { [sortProperty]: sortDirection },\n },\n ]\n\n if (limitJoin > 0) {\n pipeline.push({\n $limit: limitJoin + 1,\n })\n }\n\n if (adapter.payload.config.localization && locale === 'all') {\n adapter.payload.config.localization.localeCodes.forEach((code) => {\n const as = `${versions ? `version.${join.schemaPath}` : join.schemaPath}${code}`\n\n aggregate.push(\n {\n $lookup: {\n as: `${as}.docs`,\n foreignField: `${join.field.on}${code}`,\n from: slug,\n localField: versions ? 'parent' : '_id',\n pipeline,\n },\n },\n {\n $addFields: {\n [`${as}.docs`]: {\n $map: {\n as: 'doc',\n in: '$$doc._id',\n input: `$${as}.docs`,\n },\n }, // Slicing the docs to match the limit\n [`${as}.hasNextPage`]: limitJoin\n ? { $gt: [{ $size: `$${as}.docs` }, limitJoin] }\n : false,\n // Boolean indicating if more docs than limit\n },\n },\n )\n if (limitJoin > 0) {\n aggregate.push({\n $addFields: {\n [`${as}.docs`]: {\n $slice: [`$${as}.docs`, limitJoin],\n },\n },\n })\n }\n })\n } else {\n const localeSuffix =\n join.field.localized && adapter.payload.config.localization && locale ? `.${locale}` : ''\n const as = `${versions ? `version.${join.schemaPath}` : join.schemaPath}${localeSuffix}`\n\n aggregate.push(\n {\n $lookup: {\n as: `${as}.docs`,\n foreignField: `${join.field.on}${localeSuffix}`,\n from: slug,\n localField: versions ? 'parent' : '_id',\n pipeline,\n },\n },\n {\n $addFields: {\n [`${as}.docs`]: {\n $map: {\n as: 'doc',\n in: '$$doc._id',\n input: `$${as}.docs`,\n },\n }, // Slicing the docs to match the limit\n [`${as}.hasNextPage`]: {\n $gt: [{ $size: `$${as}.docs` }, limitJoin || Number.MAX_VALUE],\n }, // Boolean indicating if more docs than limit\n },\n },\n )\n if (limitJoin > 0) {\n aggregate.push({\n $addFields: {\n [`${as}.docs`]: {\n $slice: [`$${as}.docs`, limitJoin],\n },\n },\n })\n }\n }\n }\n }\n\n return aggregate\n}\n"],"names":["buildSortParam","buildJoinAggregation","adapter","collection","collectionConfig","joins","limit","locale","query","versions","Object","keys","length","joinConfig","payload","collections","config","aggregate","$sort","createdAt","push","$match","$limit","slug","join","joinModel","field","limitJoin","sort","sortJoin","where","whereJoin","schemaPath","fields","defaultSort","timestamps","sortProperty","sortDirection","buildQuery","pipeline","localization","localeCodes","forEach","code","as","$lookup","foreignField","on","from","localField","$addFields","$map","in","input","$gt","$size","$slice","localeSuffix","localized","Number","MAX_VALUE"],"mappings":"AAKA,SAASA,cAAc,QAAQ,+BAA8B;AAgB7D,OAAO,MAAMC,uBAAuB,OAAO,EACzCC,OAAO,EACPC,UAAU,EACVC,gBAAgB,EAChBC,KAAK,EACLC,KAAK,EACLC,MAAM,EACNC,KAAK,EACLC,QAAQ,EACiB;IACzB,IAAIC,OAAOC,IAAI,CAACP,iBAAiBC,KAAK,EAAEO,MAAM,KAAK,KAAKP,UAAU,OAAO;QACvE;IACF;IAEA,MAAMQ,aAAaX,QAAQY,OAAO,CAACC,WAAW,CAACZ,WAAW,CAACa,MAAM,CAACX,KAAK;IACvE,MAAMY,YAA6B;QACjC;YACEC,OAAO;gBAAEC,WAAW,CAAC;YAAE;QACzB;KACD;IAED,IAAIX,OAAO;QACTS,UAAUG,IAAI,CAAC;YACbC,QAAQb;QACV;IACF;IAEA,IAAIF,OAAO;QACTW,UAAUG,IAAI,CAAC;YACbE,QAAQhB;QACV;IACF;IAEA,KAAK,MAAMiB,QAAQb,OAAOC,IAAI,CAACE,YAAa;QAC1C,KAAK,MAAMW,QAAQX,UAAU,CAACU,KAAK,CAAE;YACnC,MAAME,YAAYvB,QAAQa,WAAW,CAACS,KAAKE,KAAK,CAACvB,UAAU,CAAC;YAE5D,MAAM,EACJG,OAAOqB,YAAY,EAAE,EACrBC,M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,CAAC,CAAC,EAAE;4BACdO,MAAM;gCACJP,IAAI;gCACJQ,IAAI;gCACJC,OAAO,CAAC,CAAC,EAAET,GAAG,KAAK,CAAC;4BACtB;wBACF;wBACA,CAAC,CAAC,EAAEA,GAAG,YAAY,CAAC,CAAC,EAAE;4BACrBU,KAAK;gCAAC;oCAAEC,OAAO,CAAC,CAAC,EAAEX,GAAG,KAAK,CAAC;gCAAC;gCAAGjB,aAAagC,OAAOC,SAAS;6BAAC;wBAChE;oBACF;gBACF;gBAEF,IAAIjC,YAAY,GAAG;oBACjBV,UAAUG,IAAI,CAAC;wBACb8B,YAAY;4BACV,CAAC,CAAC,EAAEN,GAAG,KAAK,CAAC,CAAC,EAAE;gCACdY,QAAQ;oCAAC,CAAC,CAAC,EAAEZ,GAAG,KAAK,CAAC;oCAAEjB;iCAAU;4BACpC;wBACF;oBACF;gBACF;YACF;QACF;IACF;IAEA,OAAOV;AACT,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"sanitizeRelationshipIDs.d.ts","sourceRoot":"","sources":["../../src/utilities/sanitizeRelationshipIDs.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAoB,KAAK,EAAE,eAAe,EAA0B,MAAM,SAAS,CAAA;AAM/F,KAAK,IAAI,GAAG;IACV,MAAM,EAAE,eAAe,CAAA;IACvB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC7B,MAAM,EAAE,KAAK,EAAE,CAAA;CAChB,CAAA;AAgGD,eAAO,MAAM,uBAAuB,8BAIjC,IAAI,KAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CA6B/B,CAAA"}
1
+ {"version":3,"file":"sanitizeRelationshipIDs.d.ts","sourceRoot":"","sources":["../../src/utilities/sanitizeRelationshipIDs.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAoB,KAAK,EAAE,eAAe,EAA0B,MAAM,SAAS,CAAA;AAM/F,KAAK,IAAI,GAAG;IACV,MAAM,EAAE,eAAe,CAAA;IACvB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC7B,MAAM,EAAE,KAAK,EAAE,CAAA;CAChB,CAAA;AAuGD,eAAO,MAAM,uBAAuB,8BAIjC,IAAI,KAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CA6B/B,CAAA"}
@@ -1,5 +1,5 @@
1
1
  import mongoose from 'mongoose';
2
- import { traverseFields } from 'payload';
2
+ import { APIError, traverseFields } from 'payload';
3
3
  import { fieldAffectsData } from 'payload/shared';
4
4
  function isValidRelationObject(value) {
5
5
  return typeof value === 'object' && value !== null && 'relationTo' in value && 'value' in value;
@@ -7,7 +7,11 @@ function isValidRelationObject(value) {
7
7
  const convertValue = ({ relatedCollection, value })=>{
8
8
  const customIDField = relatedCollection.fields.find((field)=>fieldAffectsData(field) && field.name === 'id');
9
9
  if (!customIDField) {
10
- return new mongoose.Types.ObjectId(value);
10
+ try {
11
+ return new mongoose.Types.ObjectId(value);
12
+ } catch (error) {
13
+ throw new APIError(`Failed to create ObjectId from value: ${value}. Error: ${error.message}`, 400);
14
+ }
11
15
  }
12
16
  return value;
13
17
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utilities/sanitizeRelationshipIDs.ts"],"sourcesContent":["import type { CollectionConfig, Field, SanitizedConfig, TraverseFieldsCallback } from 'payload'\n\nimport mongoose from 'mongoose'\nimport { traverseFields } from 'payload'\nimport { fieldAffectsData } from 'payload/shared'\n\ntype Args = {\n config: SanitizedConfig\n data: Record<string, unknown>\n fields: Field[]\n}\n\ninterface RelationObject {\n relationTo: string\n value: number | string\n}\n\nfunction isValidRelationObject(value: unknown): value is RelationObject {\n return typeof value === 'object' && value !== null && 'relationTo' in value && 'value' in value\n}\n\nconst convertValue = ({\n relatedCollection,\n value,\n}: {\n relatedCollection: CollectionConfig\n value: number | string\n}): mongoose.Types.ObjectId | number | string => {\n const customIDField = relatedCollection.fields.find(\n (field) => fieldAffectsData(field) && field.name === 'id',\n )\n\n if (!customIDField) {\n return new mongoose.Types.ObjectId(value)\n }\n\n return value\n}\n\nconst sanitizeRelationship = ({ config, field, locale, ref, value }) => {\n let relatedCollection: CollectionConfig | undefined\n let result = value\n\n const hasManyRelations = typeof field.relationTo !== 'string'\n\n if (!hasManyRelations) {\n relatedCollection = config.collections?.find(({ slug }) => slug === field.relationTo)\n }\n\n if (Array.isArray(value)) {\n result = value.map((val) => {\n // Handle has many\n if (relatedCollection && val && (typeof val === 'string' || typeof val === 'number')) {\n return convertValue({\n relatedCollection,\n value: val,\n })\n }\n\n // Handle has many - polymorphic\n if (isValidRelationObject(val)) {\n const relatedCollectionForSingleValue = config.collections?.find(\n ({ slug }) => slug === val.relationTo,\n )\n\n if (relatedCollectionForSingleValue) {\n return {\n relationTo: val.relationTo,\n value: convertValue({\n relatedCollection: relatedCollectionForSingleValue,\n value: val.value,\n }),\n }\n }\n }\n\n return val\n })\n }\n\n // Handle has one - polymorphic\n if (isValidRelationObject(value)) {\n relatedCollection = config.collections?.find(({ slug }) => slug === value.relationTo)\n\n if (relatedCollection) {\n result = {\n relationTo: value.relationTo,\n value: convertValue({ relatedCollection, value: value.value }),\n }\n }\n }\n\n // Handle has one\n if (relatedCollection && value && (typeof value === 'string' || typeof value === 'number')) {\n result = convertValue({\n relatedCollection,\n value,\n })\n }\n if (locale) {\n ref[locale] = result\n } else {\n ref[field.name] = result\n }\n}\n\nexport const sanitizeRelationshipIDs = ({\n config,\n data,\n fields,\n}: Args): Record<string, unknown> => {\n const sanitize: TraverseFieldsCallback = ({ field, ref }) => {\n if (field.type === 'relationship' || field.type === 'upload') {\n // handle localized relationships\n if (config.localization && field.localized) {\n const locales = config.localization.locales\n const fieldRef = ref[field.name]\n for (const { code } of locales) {\n if (ref[field.name]?.[code]) {\n const value = ref[field.name][code]\n sanitizeRelationship({ config, field, locale: code, ref: fieldRef, value })\n }\n }\n } else {\n // handle non-localized relationships\n sanitizeRelationship({\n config,\n field,\n locale: undefined,\n ref,\n value: ref[field.name],\n })\n }\n }\n }\n\n traverseFields({ callback: sanitize, fields, ref: data })\n\n return data\n}\n"],"names":["mongoose","traverseFields","fieldAffectsData","isValidRelationObject","value","convertValue","relatedCollection","customIDField","fields","find","field","name","Types","ObjectId","sanitizeRelationship","config","locale","ref","result","hasManyRelations","relationTo","collections","slug","Array","isArray","map","val","relatedCollectionForSingleValue","sanitizeRelationshipIDs","data","sanitize","type","localization","localized","locales","fieldRef","code","undefined","callback"],"mappings":"AAEA,OAAOA,cAAc,WAAU;AAC/B,SAASC,cAAc,QAAQ,UAAS;AACxC,SAASC,gBAAgB,QAAQ,iBAAgB;AAajD,SAASC,sBAAsBC,KAAc;IAC3C,OAAO,OAAOA,UAAU,YAAYA,UAAU,QAAQ,gBAAgBA,SAAS,WAAWA;AAC5F;AAEA,MAAMC,eAAe,CAAC,EACpBC,iBAAiB,EACjBF,KAAK,EAIN;IACC,MAAMG,gBAAgBD,kBAAkBE,MAAM,CAACC,IAAI,CACjD,CAACC,QAAUR,iBAAiBQ,UAAUA,MAAMC,IAAI,KAAK;IAGvD,IAAI,CAACJ,eAAe;QAClB,OAAO,IAAIP,SAASY,KAAK,CAACC,QAAQ,CAACT;IACrC;IAEA,OAAOA;AACT;AAEA,MAAMU,uBAAuB,CAAC,EAAEC,MAAM,EAAEL,KAAK,EAAEM,MAAM,EAAEC,GAAG,EAAEb,KAAK,EAAE;IACjE,IAAIE;IACJ,IAAIY,SAASd;IAEb,MAAMe,mBAAmB,OAAOT,MAAMU,UAAU,KAAK;IAErD,IAAI,CAACD,kBAAkB;QACrBb,oBAAoBS,OAAOM,WAAW,EAAEZ,KAAK,CAAC,EAAEa,IAAI,EAAE,GAAKA,SAASZ,MAAMU,UAAU;IACtF;IAEA,IAAIG,MAAMC,OAAO,CAACpB,QAAQ;QACxBc,SAASd,MAAMqB,GAAG,CAAC,CAACC;YAClB,kBAAkB;YAClB,IAAIpB,qBAAqBoB,OAAQ,CAAA,OAAOA,QAAQ,YAAY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AAItB,MAAMuB,SAAS,EAAE;gBAC1C,MAAMC,UAAUnB,OAAOiB,YAAY,CAACE,OAAO;gBAC3C,MAAMC,WAAWlB,GAAG,CAACP,MAAMC,IAAI,CAAC;gBAChC,KAAK,MAAM,EAAEyB,IAAI,EAAE,IAAIF,QAAS;oBAC9B,IAAIjB,GAAG,CAACP,MAAMC,IAAI,CAAC,EAAE,CAACyB,KAAK,EAAE;wBAC3B,MAAMhC,QAAQa,GAAG,CAACP,MAAMC,IAAI,CAAC,CAACyB,KAAK;wBACnCtB,qBAAqB;4BAAEC;4BAAQL;4BAAOM,QAAQoB;4BAAMnB,KAAKkB;4BAAU/B;wBAAM;oBAC3E;gBACF;YACF,OAAO;gBACL,qCAAqC;gBACrCU,qBAAqB;oBACnBC;oBACAL;oBACAM,QAAQqB;oBACRpB;oBACAb,OAAOa,GAAG,CAACP,MAAMC,IAAI,CAAC;gBACxB;YACF;QACF;IACF;IAEAV,eAAe;QAAEqC,UAAUR;QAAUtB;QAAQS,KAAKY;IAAK;IAEvD,OAAOA;AACT,EAAC"}
1
+ {"version":3,"sources":["../../src/utilities/sanitizeRelationshipIDs.ts"],"sourcesContent":["import type { CollectionConfig, Field, SanitizedConfig, TraverseFieldsCallback } from 'payload'\n\nimport mongoose from 'mongoose'\nimport { APIError, traverseFields } from 'payload'\nimport { fieldAffectsData } from 'payload/shared'\n\ntype Args = {\n config: SanitizedConfig\n data: Record<string, unknown>\n fields: Field[]\n}\n\ninterface RelationObject {\n relationTo: string\n value: number | string\n}\n\nfunction isValidRelationObject(value: unknown): value is RelationObject {\n return typeof value === 'object' && value !== null && 'relationTo' in value && 'value' in value\n}\n\nconst convertValue = ({\n relatedCollection,\n value,\n}: {\n relatedCollection: CollectionConfig\n value: number | string\n}): mongoose.Types.ObjectId | number | string => {\n const customIDField = relatedCollection.fields.find(\n (field) => fieldAffectsData(field) && field.name === 'id',\n )\n\n if (!customIDField) {\n try {\n return new mongoose.Types.ObjectId(value)\n } catch (error) {\n throw new APIError(\n `Failed to create ObjectId from value: ${value}. Error: ${error.message}`,\n 400,\n )\n }\n }\n\n return value\n}\n\nconst sanitizeRelationship = ({ config, field, locale, ref, value }) => {\n let relatedCollection: CollectionConfig | undefined\n let result = value\n\n const hasManyRelations = typeof field.relationTo !== 'string'\n\n if (!hasManyRelations) {\n relatedCollection = config.collections?.find(({ slug }) => slug === field.relationTo)\n }\n\n if (Array.isArray(value)) {\n result = value.map((val) => {\n // Handle has many\n if (relatedCollection && val && (typeof val === 'string' || typeof val === 'number')) {\n return convertValue({\n relatedCollection,\n value: val,\n })\n }\n\n // Handle has many - polymorphic\n if (isValidRelationObject(val)) {\n const relatedCollectionForSingleValue = config.collections?.find(\n ({ slug }) => slug === val.relationTo,\n )\n\n if (relatedCollectionForSingleValue) {\n return {\n relationTo: val.relationTo,\n value: convertValue({\n relatedCollection: relatedCollectionForSingleValue,\n value: val.value,\n }),\n }\n }\n }\n\n return val\n })\n }\n\n // Handle has one - polymorphic\n if (isValidRelationObject(value)) {\n relatedCollection = config.collections?.find(({ slug }) => slug === value.relationTo)\n\n if (relatedCollection) {\n result = {\n relationTo: value.relationTo,\n value: convertValue({ relatedCollection, value: value.value }),\n }\n }\n }\n\n // Handle has one\n if (relatedCollection && value && (typeof value === 'string' || typeof value === 'number')) {\n result = convertValue({\n relatedCollection,\n value,\n })\n }\n if (locale) {\n ref[locale] = result\n } else {\n ref[field.name] = result\n }\n}\n\nexport const sanitizeRelationshipIDs = ({\n config,\n data,\n fields,\n}: Args): Record<string, unknown> => {\n const sanitize: TraverseFieldsCallback = ({ field, ref }) => {\n if (field.type === 'relationship' || field.type === 'upload') {\n // handle localized relationships\n if (config.localization && field.localized) {\n const locales = config.localization.locales\n const fieldRef = ref[field.name]\n for (const { code } of locales) {\n if (ref[field.name]?.[code]) {\n const value = ref[field.name][code]\n sanitizeRelationship({ config, field, locale: code, ref: fieldRef, value })\n }\n }\n } else {\n // handle non-localized relationships\n sanitizeRelationship({\n config,\n field,\n locale: undefined,\n ref,\n value: ref[field.name],\n })\n }\n }\n }\n\n traverseFields({ callback: sanitize, fields, ref: data })\n\n return data\n}\n"],"names":["mongoose","APIError","traverseFields","fieldAffectsData","isValidRelationObject","value","convertValue","relatedCollection","customIDField","fields","find","field","name","Types","ObjectId","error","message","sanitizeRelationship","config","locale","ref","result","hasManyRelations","relationTo","collections","slug","Array","isArray","map","val","relatedCollectionForSingleValue","sanitizeRelationshipIDs","data","sanitize","type","localization","localized","locales","fieldRef","code","undefined","callback"],"mappings":"AAEA,OAAOA,cAAc,WAAU;AAC/B,SAASC,QAAQ,EAAEC,cAAc,QAAQ,UAAS;AAClD,SAASC,gBAAgB,QAAQ,iBAAgB;AAajD,SAASC,sBAAsBC,KAAc;IAC3C,OAAO,OAAOA,UAAU,YAAYA,UAAU,QAAQ,gBAAgBA,SAAS,WAAWA;AAC5F;AAEA,MAAMC,eAAe,CAAC,EACpBC,iBAAiB,EACjBF,KAAK,EAIN;IACC,MAAMG,gBAAgBD,kBAAkBE,MAAM,CAACC,IAAI,CACjD,CAACC,QAAUR,iBAAiBQ,UAAUA,MAAMC,IAAI,KAAK;IAGvD,IAAI,CAACJ,eAAe;QAClB,IAAI;YACF,OAAO,IAAIR,SAASa,KAAK,CAACC,QAAQ,CAACT;QACrC,EAAE,OAAOU,OAAO;YACd,MAAM,IAAId,SACR,CAAC,sCAAsC,EAAEI,MAAM,SAAS,EAAEU,MAAMC,OAAO,CAAC,CAAC,EACzE;QAEJ;IACF;IAEA,OAAOX;AACT;AAEA,MAAMY,uBAAuB,CAAC,EAAEC,MAAM,EAAEP,KAAK,EAAEQ,MAAM,EAAEC,GAAG,EAAEf,KAAK,EAAE;IACjE,IAAIE;IACJ,IAAIc,SAAShB;IAEb,MAAMiB,mBAAmB,OAAOX,MAAMY,UAAU,KAAK;IAErD,IAAI,CAACD,kBAAkB;QACrBf,oBAAoBW,OAAOM,WAAW,EAAEd,KAAK,CAAC,EAAEe,IAAI,EAAE,GAAKA,SAASd,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,MAAMwB,WAAmC,CAAC,EAAEtB,KAAK,EAAES,GAAG,EAAE;QACtD,IAAIT,MAAMuB,IAAI,KAAK,kBAAkBvB,MAAMuB,IAAI,KAAK,UAAU;YAC5D,iCAAiC;YACjC,IAAIhB,OAAOiB,YAAY,IAAIxB,MAAMyB,SAAS,EAAE;gBAC1C,MAAMC,UAAUnB,OAAOiB,YAAY,CAACE,OAAO;gBAC3C,MAAMC,WAAWlB,GAAG,CAACT,MAAMC,IAAI,CAAC;gBAChC,KAAK,MAAM,EAAE2B,IAAI,EAAE,IAAIF,QAAS;oBAC9B,IAAIjB,GAAG,CAACT,MAAMC,IAAI,CAAC,EAAE,CAAC2B,KAAK,EAAE;wBAC3B,MAAMlC,QAAQe,GAAG,CAACT,MAAMC,IAAI,CAAC,CAAC2B,KAAK;wBACnCtB,qBAAqB;4BAAEC;4BAAQP;4BAAOQ,QAAQoB;4BAAMnB,KAAKkB;4BAAUjC;wBAAM;oBAC3E;gBACF;YACF,OAAO;gBACL,qCAAqC;gBACrCY,qBAAqB;oBACnBC;oBACAP;oBACAQ,QAAQqB;oBACRpB;oBACAf,OAAOe,GAAG,CAACT,MAAMC,IAAI,CAAC;gBACxB;YACF;QACF;IACF;IAEAV,eAAe;QAAEuC,UAAUR;QAAUxB;QAAQW,KAAKY;IAAK;IAEvD,OAAOA;AACT,EAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payloadcms/db-mongodb",
3
- "version": "3.0.0-canary.e198dc5",
3
+ "version": "3.0.0-canary.e1fc0e0",
4
4
  "description": "The officially supported MongoDB database adapter for Payload",
5
5
  "homepage": "https://payloadcms.com",
6
6
  "repository": {
@@ -38,11 +38,11 @@
38
38
  "@types/mongoose-aggregate-paginate-v2": "1.0.6",
39
39
  "mongodb": "4.17.1",
40
40
  "mongodb-memory-server": "^9",
41
- "@payloadcms/eslint-config": "3.0.0-beta.97",
42
- "payload": "3.0.0-canary.e198dc5"
41
+ "@payloadcms/eslint-config": "3.0.0-beta.112",
42
+ "payload": "3.0.0-canary.e1fc0e0"
43
43
  },
44
44
  "peerDependencies": {
45
- "payload": "3.0.0-canary.e198dc5"
45
+ "payload": "3.0.0-canary.e1fc0e0"
46
46
  },
47
47
  "scripts": {
48
48
  "build": "pnpm build:types && pnpm build:swc",