@payloadcms/db-mongodb 4.0.0-internal.314c594 → 4.0.0-internal.31ba7ee
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/connect.d.ts.map +1 -1
- package/dist/connect.js +8 -2
- package/dist/connect.js.map +1 -1
- package/dist/createMigration.d.ts.map +1 -1
- package/dist/createMigration.js +9 -2
- package/dist/createMigration.js.map +1 -1
- package/dist/findDistinct.d.ts.map +1 -1
- package/dist/findDistinct.js +52 -8
- package/dist/findDistinct.js.map +1 -1
- package/dist/init.d.ts.map +1 -1
- package/dist/init.js +89 -67
- package/dist/init.js.map +1 -1
- package/dist/migrateFresh.d.ts +4 -2
- package/dist/migrateFresh.d.ts.map +1 -1
- package/dist/migrateFresh.js +21 -6
- package/dist/migrateFresh.js.map +1 -1
- package/dist/models/buildCollectionSchema.d.ts +8 -2
- package/dist/models/buildCollectionSchema.d.ts.map +1 -1
- package/dist/models/buildCollectionSchema.js +4 -2
- package/dist/models/buildCollectionSchema.js.map +1 -1
- package/dist/models/buildGlobalModel.d.ts +5 -1
- package/dist/models/buildGlobalModel.d.ts.map +1 -1
- package/dist/models/buildGlobalModel.js +4 -2
- package/dist/models/buildGlobalModel.js.map +1 -1
- package/dist/models/buildSchema.d.ts +4 -0
- package/dist/models/buildSchema.d.ts.map +1 -1
- package/dist/models/buildSchema.js +64 -26
- package/dist/models/buildSchema.js.map +1 -1
- package/dist/models/schemaBuildContext.d.ts +21 -0
- package/dist/models/schemaBuildContext.d.ts.map +1 -0
- package/dist/models/schemaBuildContext.js +29 -0
- package/dist/models/schemaBuildContext.js.map +1 -0
- package/dist/queries/buildSearchParams.d.ts.map +1 -1
- package/dist/queries/buildSearchParams.js +50 -0
- package/dist/queries/buildSearchParams.js.map +1 -1
- package/dist/updateGlobal.js +2 -2
- package/dist/updateGlobal.js.map +1 -1
- package/dist/updateGlobalVersion.js +2 -2
- package/dist/updateGlobalVersion.js.map +1 -1
- package/dist/updateJobs.js +1 -1
- package/dist/updateJobs.js.map +1 -1
- package/dist/updateMany.d.ts.map +1 -1
- package/dist/updateMany.js +0 -1
- package/dist/updateMany.js.map +1 -1
- package/dist/updateOne.js +2 -2
- package/dist/updateOne.js.map +1 -1
- package/dist/updateVersion.js +2 -2
- package/dist/updateVersion.js.map +1 -1
- package/package.json +3 -3
- package/dist/queries/buildSortParam.spec.js +0 -123
- package/dist/queries/buildSortParam.spec.js.map +0 -1
- package/dist/queries/getLocalizedSortProperty.spec.js +0 -215
- package/dist/queries/getLocalizedSortProperty.spec.js.map +0 -1
- package/dist/utilities/transform.spec.js +0 -546
- package/dist/utilities/transform.spec.js.map +0 -1
package/dist/connect.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAa,MAAM,SAAS,CAAA;AAOjD,eAAO,MAAM,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAa,MAAM,SAAS,CAAA;AAOjD,eAAO,MAAM,OAAO,EAAE,OAkHrB,CAAA"}
|
package/dist/connect.js
CHANGED
|
@@ -64,8 +64,14 @@ export const connect = async function connect(options = {
|
|
|
64
64
|
}
|
|
65
65
|
}
|
|
66
66
|
if (this.ensureIndexes) {
|
|
67
|
-
await Promise.all(
|
|
68
|
-
|
|
67
|
+
await Promise.all([
|
|
68
|
+
...this.payload.config.collections.flatMap((collection)=>[
|
|
69
|
+
this.collections[collection.slug],
|
|
70
|
+
this.versions[collection.slug]
|
|
71
|
+
]),
|
|
72
|
+
...this.payload.config.globals.map((global)=>this.versions[global.slug])
|
|
73
|
+
].map(async (model)=>{
|
|
74
|
+
await model?.ensureIndexes();
|
|
69
75
|
}));
|
|
70
76
|
}
|
|
71
77
|
if (process.env.NODE_ENV === 'production' && this.prodMigrations) {
|
package/dist/connect.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/connect.ts"],"sourcesContent":["import type { ConnectOptions } from 'mongoose'\nimport type { Connect, Migration } from 'payload'\n\nimport mongoose from 'mongoose'\nimport { defaultBeginTransaction } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nexport const connect: Connect = async function connect(\n this: MongooseAdapter,\n options = {\n hotReload: false,\n },\n) {\n const { hotReload } = options\n\n if (this.url === false) {\n return\n }\n\n if (typeof this.url !== 'string') {\n throw new Error('Error: missing MongoDB connection URL.')\n }\n\n const urlToConnect = this.url\n\n const connectionOptions: ConnectOptions = {\n autoIndex: true,\n ...this.connectOptions,\n }\n\n if (hotReload) {\n connectionOptions.autoIndex = false\n }\n\n try {\n if (!this.connection) {\n this.connection = await mongoose.createConnection(urlToConnect, connectionOptions).asPromise()\n if (this.afterCreateConnection) {\n await this.afterCreateConnection(this)\n }\n }\n\n await this.connection.openUri(urlToConnect, connectionOptions)\n\n if (this.afterOpenConnection) {\n await this.afterOpenConnection(this)\n }\n\n if (this.useAlternativeDropDatabase) {\n if (this.connection.db) {\n // Firestore doesn't support dropDatabase, so we monkey patch\n // dropDatabase to delete all documents from all collections instead\n this.connection.db.dropDatabase = async function (): Promise<boolean> {\n const existingCollections = await this.listCollections().toArray()\n await Promise.all(\n existingCollections.map(async (collectionInfo) => {\n const collection = this.collection(collectionInfo.name)\n await collection.deleteMany({})\n }),\n )\n return true\n }\n this.connection.dropDatabase = async function () {\n await this.db?.dropDatabase()\n }\n }\n }\n\n // If we are running a replica set with MongoDB Memory Server,\n // wait until the replica set elects a primary before proceeding\n if (this.mongoMemoryServer) {\n this.payload.logger.info(\n 'Waiting for MongoDB Memory Server replica set to elect a primary...',\n )\n await new Promise((resolve) => setTimeout(resolve, 2000))\n }\n\n if (!this.connection.getClient().options.replicaSet) {\n this.transactionOptions = false\n this.beginTransaction = defaultBeginTransaction()\n }\n\n if (!hotReload) {\n if (process.env.PAYLOAD_DROP_DATABASE === 'true') {\n this.payload.logger.info('---- DROPPING DATABASE ----')\n await this.connection.dropDatabase()\n\n this.payload.logger.info('---- DROPPED DATABASE ----')\n }\n }\n\n if (this.ensureIndexes) {\n await Promise.all(\n this.payload.config.collections.
|
|
1
|
+
{"version":3,"sources":["../src/connect.ts"],"sourcesContent":["import type { ConnectOptions } from 'mongoose'\nimport type { Connect, Migration } from 'payload'\n\nimport mongoose from 'mongoose'\nimport { defaultBeginTransaction } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nexport const connect: Connect = async function connect(\n this: MongooseAdapter,\n options = {\n hotReload: false,\n },\n) {\n const { hotReload } = options\n\n if (this.url === false) {\n return\n }\n\n if (typeof this.url !== 'string') {\n throw new Error('Error: missing MongoDB connection URL.')\n }\n\n const urlToConnect = this.url\n\n const connectionOptions: ConnectOptions = {\n autoIndex: true,\n ...this.connectOptions,\n }\n\n if (hotReload) {\n connectionOptions.autoIndex = false\n }\n\n try {\n if (!this.connection) {\n this.connection = await mongoose.createConnection(urlToConnect, connectionOptions).asPromise()\n if (this.afterCreateConnection) {\n await this.afterCreateConnection(this)\n }\n }\n\n await this.connection.openUri(urlToConnect, connectionOptions)\n\n if (this.afterOpenConnection) {\n await this.afterOpenConnection(this)\n }\n\n if (this.useAlternativeDropDatabase) {\n if (this.connection.db) {\n // Firestore doesn't support dropDatabase, so we monkey patch\n // dropDatabase to delete all documents from all collections instead\n this.connection.db.dropDatabase = async function (): Promise<boolean> {\n const existingCollections = await this.listCollections().toArray()\n await Promise.all(\n existingCollections.map(async (collectionInfo) => {\n const collection = this.collection(collectionInfo.name)\n await collection.deleteMany({})\n }),\n )\n return true\n }\n this.connection.dropDatabase = async function () {\n await this.db?.dropDatabase()\n }\n }\n }\n\n // If we are running a replica set with MongoDB Memory Server,\n // wait until the replica set elects a primary before proceeding\n if (this.mongoMemoryServer) {\n this.payload.logger.info(\n 'Waiting for MongoDB Memory Server replica set to elect a primary...',\n )\n await new Promise((resolve) => setTimeout(resolve, 2000))\n }\n\n if (!this.connection.getClient().options.replicaSet) {\n this.transactionOptions = false\n this.beginTransaction = defaultBeginTransaction()\n }\n\n if (!hotReload) {\n if (process.env.PAYLOAD_DROP_DATABASE === 'true') {\n this.payload.logger.info('---- DROPPING DATABASE ----')\n await this.connection.dropDatabase()\n\n this.payload.logger.info('---- DROPPED DATABASE ----')\n }\n }\n\n if (this.ensureIndexes) {\n await Promise.all(\n [\n ...this.payload.config.collections.flatMap((collection) => [\n this.collections[collection.slug],\n this.versions[collection.slug],\n ]),\n ...this.payload.config.globals.map((global) => this.versions[global.slug]),\n ].map(async (model) => {\n await model?.ensureIndexes()\n }),\n )\n }\n\n if (process.env.NODE_ENV === 'production' && this.prodMigrations) {\n await this.migrate({ migrations: this.prodMigrations as unknown as Migration[] })\n }\n } catch (err) {\n let msg = `Error: cannot connect to MongoDB.`\n\n if (typeof err === 'object' && err && 'message' in err && typeof err.message === 'string') {\n msg = `${msg} Details: ${err.message}`\n }\n\n this.payload.logger.error({\n err,\n msg,\n })\n throw new Error(`Error: cannot connect to MongoDB: ${msg}`)\n }\n}\n"],"names":["mongoose","defaultBeginTransaction","connect","options","hotReload","url","Error","urlToConnect","connectionOptions","autoIndex","connectOptions","connection","createConnection","asPromise","afterCreateConnection","openUri","afterOpenConnection","useAlternativeDropDatabase","db","dropDatabase","existingCollections","listCollections","toArray","Promise","all","map","collectionInfo","collection","name","deleteMany","mongoMemoryServer","payload","logger","info","resolve","setTimeout","getClient","replicaSet","transactionOptions","beginTransaction","process","env","PAYLOAD_DROP_DATABASE","ensureIndexes","config","collections","flatMap","slug","versions","globals","global","model","NODE_ENV","prodMigrations","migrate","migrations","err","msg","message","error"],"mappings":"AAGA,OAAOA,cAAc,WAAU;AAC/B,SAASC,uBAAuB,QAAQ,UAAS;AAIjD,OAAO,MAAMC,UAAmB,eAAeA,QAE7CC,UAAU;IACRC,WAAW;AACb,CA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G,KAAK;QACZ,IAAIC,MAAM,CAAC,iCAAiC,CAAC;QAE7C,IAAI,OAAOD,QAAQ,YAAYA,OAAO,aAAaA,OAAO,OAAOA,IAAIE,OAAO,KAAK,UAAU;YACzFD,MAAM,GAAGA,IAAI,UAAU,EAAED,IAAIE,OAAO,EAAE;QACxC;QAEA,IAAI,CAAC3B,OAAO,CAACC,MAAM,CAAC2B,KAAK,CAAC;YACxBH;YACAC;QACF;QACA,MAAM,IAAInD,MAAM,CAAC,kCAAkC,EAAEmD,KAAK;IAC5D;AACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createMigration.d.ts","sourceRoot":"","sources":["../src/createMigration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAyB,MAAM,SAAS,CAAA;AAqBrE,eAAO,MAAM,eAAe,EAAE,
|
|
1
|
+
{"version":3,"file":"createMigration.d.ts","sourceRoot":"","sources":["../src/createMigration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAyB,MAAM,SAAS,CAAA;AAqBrE,eAAO,MAAM,eAAe,EAAE,eA4C7B,CAAA"}
|
package/dist/createMigration.js
CHANGED
|
@@ -36,15 +36,22 @@ export const createMigration = async function createMigration({ file, migrationN
|
|
|
36
36
|
const formattedName = migrationName?.replace(/\W/g, '_');
|
|
37
37
|
const fileName = migrationName ? `${timestamp}_${formattedName}.ts` : `${timestamp}_migration.ts`;
|
|
38
38
|
const filePath = `${dir}/${fileName}`;
|
|
39
|
-
if (
|
|
40
|
-
|
|
39
|
+
if (skipEmpty) {
|
|
40
|
+
return {
|
|
41
|
+
created: false
|
|
42
|
+
};
|
|
41
43
|
}
|
|
44
|
+
fs.writeFileSync(filePath, migrationFileContent);
|
|
42
45
|
writeMigrationIndex({
|
|
43
46
|
migrationsDir: payload.db.migrationDir
|
|
44
47
|
});
|
|
45
48
|
payload.logger.info({
|
|
46
49
|
msg: `Migration created at ${filePath}`
|
|
47
50
|
});
|
|
51
|
+
return {
|
|
52
|
+
created: true,
|
|
53
|
+
path: filePath
|
|
54
|
+
};
|
|
48
55
|
};
|
|
49
56
|
|
|
50
57
|
//# sourceMappingURL=createMigration.js.map
|
|
@@ -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, writeMigrationIndex } from 'payload'\nimport { fileURLToPath } from 'url'\n\nconst migrationTemplate = ({ downSQL, imports, upSQL }: MigrationTemplateArgs): string => `import {\n MigrateDownArgs,\n MigrateUpArgs,\n} from '@payloadcms/db-mongodb'\n${imports ?? ''}\nexport async function up({ payload, req, session }: MigrateUpArgs): Promise<void> {\n${upSQL ?? ` // Migration code`}\n}\n\nexport async function down({ payload, req, session }: MigrateDownArgs): Promise<void> {\n${downSQL ?? ` // Migration code`}\n}\n`\n\nexport const createMigration: CreateMigration = async function createMigration({\n file,\n migrationName,\n payload,\n skipEmpty,\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\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\n if (
|
|
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, writeMigrationIndex } from 'payload'\nimport { fileURLToPath } from 'url'\n\nconst migrationTemplate = ({ downSQL, imports, upSQL }: MigrationTemplateArgs): string => `import {\n MigrateDownArgs,\n MigrateUpArgs,\n} from '@payloadcms/db-mongodb'\n${imports ?? ''}\nexport async function up({ payload, req, session }: MigrateUpArgs): Promise<void> {\n${upSQL ?? ` // Migration code`}\n}\n\nexport async function down({ payload, req, session }: MigrateDownArgs): Promise<void> {\n${downSQL ?? ` // Migration code`}\n}\n`\n\nexport const createMigration: CreateMigration = async function createMigration({\n file,\n migrationName,\n payload,\n skipEmpty,\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\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\n if (skipEmpty) {\n return { created: false }\n }\n\n fs.writeFileSync(filePath, migrationFileContent)\n\n writeMigrationIndex({ migrationsDir: payload.db.migrationDir })\n\n payload.logger.info({ msg: `Migration created at ${filePath}` })\n\n return { created: true, path: filePath }\n}\n"],"names":["fs","path","getPredefinedMigration","writeMigrationIndex","fileURLToPath","migrationTemplate","downSQL","imports","upSQL","createMigration","file","migrationName","payload","skipEmpty","filename","url","dirname","dir","db","migrationDir","existsSync","mkdirSync","predefinedMigration","migrationFileContent","yyymmdd","hhmmss","Date","toISOString","split","formattedDate","replace","formattedTime","timestamp","formattedName","fileName","filePath","created","writeFileSync","migrationsDir","logger","info","msg"],"mappings":"AAEA,OAAOA,QAAQ,KAAI;AACnB,OAAOC,UAAU,OAAM;AACvB,SAASC,sBAAsB,EAAEC,mBAAmB,QAAQ,UAAS;AACrE,SAASC,aAAa,QAAQ,MAAK;AAEnC,MAAMC,oBAAoB,CAAC,EAAEC,OAAO,EAAEC,OAAO,EAAEC,KAAK,EAAyB,GAAa,CAAC;;;;AAI3F,EAAED,WAAW,GAAG;;AAEhB,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,EACPC,SAAS,EACV;IACC,MAAMC,WAAWV,cAAc,YAAYW,GAAG;IAC9C,MAAMC,UAAUf,KAAKe,OAAO,CAACF;IAE7B,MAAMG,MAAML,QAAQM,EAAE,CAACC,YAAY;IACnC,IAAI,CAACnB,GAAGoB,UAAU,CAACH,MAAM;QACvBjB,GAAGqB,SAAS,CAACJ;IACf;IACA,MAAMK,sBAAsB,MAAMpB,uBAAuB;QACvDc;QACAN;QACAC;QACAC;IACF;IAEA,MAAMW,uBAAuBlB,kBAAkBiB;IAE/C,MAAM,CAACE,SAASC,OAAO,GAAG,IAAIC,OAAOC,WAAW,GAAGC,KAAK,CAAC;IAEzD,MAAMC,gBAAgBL,QAASM,OAAO,CAAC,OAAO;IAC9C,MAAMC,gBAAgBN,OAAQG,KAAK,CAAC,IAAI,CAAC,EAAE,CAAEE,OAAO,CAAC,OAAO;IAE5D,MAAME,YAAY,GAAGH,cAAc,CAAC,EAAEE,eAAe;IAErD,MAAME,gBAAgBtB,eAAemB,QAAQ,OAAO;IACpD,MAAMI,WAAWvB,gBAAgB,GAAGqB,UAAU,CAAC,EAAEC,cAAc,GAAG,CAAC,GAAG,GAAGD,UAAU,aAAa,CAAC;IACjG,MAAMG,WAAW,GAAGlB,IAAI,CAAC,EAAEiB,UAAU;IAErC,IAAIrB,WAAW;QACb,OAAO;YAAEuB,SAAS;QAAM;IAC1B;IAEApC,GAAGqC,aAAa,CAACF,UAAUZ;IAE3BpB,oBAAoB;QAAEmC,eAAe1B,QAAQM,EAAE,CAACC,YAAY;IAAC;IAE7DP,QAAQ2B,MAAM,CAACC,IAAI,CAAC;QAAEC,KAAK,CAAC,qBAAqB,EAAEN,UAAU;IAAC;IAE9D,OAAO;QAAEC,SAAS;QAAMnC,MAAMkC;IAAS;AACzC,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"findDistinct.d.ts","sourceRoot":"","sources":["../src/findDistinct.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAkB,MAAM,SAAS,CAAA;AA6C3D,eAAO,MAAM,YAAY,EAAE,
|
|
1
|
+
{"version":3,"file":"findDistinct.d.ts","sourceRoot":"","sources":["../src/findDistinct.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAkB,MAAM,SAAS,CAAA;AA6C3D,eAAO,MAAM,YAAY,EAAE,YA4S1B,CAAA"}
|
package/dist/findDistinct.js
CHANGED
|
@@ -114,30 +114,74 @@ export const findDistinct = async function(args) {
|
|
|
114
114
|
sortProperty = sortWithoutRelationPrefix;
|
|
115
115
|
}
|
|
116
116
|
}
|
|
117
|
-
relationLookup =
|
|
117
|
+
relationLookup = [];
|
|
118
|
+
for (const { fieldPath, relationTo } of rels){
|
|
118
119
|
sortAggregation = sortAggregation.filter((each)=>{
|
|
119
120
|
if ('$lookup' in each && each.$lookup.as.replace(/^_+/, '') === fieldPath) {
|
|
120
121
|
return false;
|
|
121
122
|
}
|
|
122
123
|
return true;
|
|
123
124
|
});
|
|
124
|
-
const { Model: foreignModel } = getCollection({
|
|
125
|
+
const { collectionConfig: foreignCollectionConfig, Model: foreignModel } = getCollection({
|
|
125
126
|
adapter: this,
|
|
126
127
|
collectionSlug: relationTo
|
|
127
128
|
});
|
|
128
|
-
|
|
129
|
+
const relatedAccess = args.relatedAccess?.[fieldPath];
|
|
130
|
+
const relatedAccessQuery = relatedAccess ? await buildQuery({
|
|
131
|
+
adapter: this,
|
|
132
|
+
collectionSlug: relationTo,
|
|
133
|
+
fields: foreignCollectionConfig.flattenedFields,
|
|
134
|
+
locale: args.locale,
|
|
135
|
+
where: relatedAccess
|
|
136
|
+
}) : null;
|
|
137
|
+
relationLookup.push({
|
|
129
138
|
$lookup: {
|
|
130
139
|
as: fieldPath,
|
|
131
|
-
foreignField: '_id',
|
|
132
140
|
from: foreignModel.collection.name,
|
|
133
|
-
|
|
141
|
+
...relatedAccessQuery ? {
|
|
142
|
+
let: {
|
|
143
|
+
relatedIDs: `$${fieldPath}`
|
|
144
|
+
},
|
|
145
|
+
pipeline: [
|
|
146
|
+
{
|
|
147
|
+
$match: {
|
|
148
|
+
$and: [
|
|
149
|
+
{
|
|
150
|
+
$expr: {
|
|
151
|
+
$cond: {
|
|
152
|
+
else: {
|
|
153
|
+
$eq: [
|
|
154
|
+
'$_id',
|
|
155
|
+
'$$relatedIDs'
|
|
156
|
+
]
|
|
157
|
+
},
|
|
158
|
+
if: {
|
|
159
|
+
$isArray: '$$relatedIDs'
|
|
160
|
+
},
|
|
161
|
+
then: {
|
|
162
|
+
$in: [
|
|
163
|
+
'$_id',
|
|
164
|
+
'$$relatedIDs'
|
|
165
|
+
]
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
},
|
|
170
|
+
relatedAccessQuery
|
|
171
|
+
]
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
]
|
|
175
|
+
} : {
|
|
176
|
+
foreignField: '_id',
|
|
177
|
+
localField: fieldPath
|
|
178
|
+
}
|
|
134
179
|
}
|
|
135
180
|
});
|
|
136
|
-
|
|
181
|
+
relationLookup.push({
|
|
137
182
|
$unwind: `$${fieldPath}`
|
|
138
183
|
});
|
|
139
|
-
|
|
140
|
-
}, []);
|
|
184
|
+
}
|
|
141
185
|
}
|
|
142
186
|
let $unwind = '';
|
|
143
187
|
let $group = null;
|
package/dist/findDistinct.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/findDistinct.ts"],"sourcesContent":["import type { PipelineStage } from 'mongoose'\nimport type { FindDistinct, FlattenedField } from 'payload'\n\nimport { getFieldByPath } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { buildQuery } from './queries/buildQuery.js'\nimport { buildSortParam } from './queries/buildSortParam.js'\nimport { getCollection } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\n\nconst sanitizeGroupID = (id: any) => {\n if (id && typeof id === 'object' && '_field' in id) {\n return id._field\n }\n\n return id\n}\n\nconst getSortAggregation = ({\n fieldPath,\n hasSortAggregationAndHasMany,\n sortDirection,\n sortProperty,\n}: {\n fieldPath: string\n hasSortAggregationAndHasMany: boolean\n sortDirection: -1 | 1\n sortProperty: string\n}): Record<string, -1 | 1> => {\n let resolvedSortProperty: string\n\n if (hasSortAggregationAndHasMany) {\n if (sortProperty === fieldPath) {\n resolvedSortProperty = `_id._field`\n } else {\n resolvedSortProperty = `_id._sort`\n }\n } else {\n resolvedSortProperty = sortProperty === fieldPath ? '_id' : '_sort'\n }\n\n return { [`${resolvedSortProperty}`]: sortDirection }\n}\n\nexport const findDistinct: FindDistinct = async function (this: MongooseAdapter, args) {\n const { collectionConfig, Model } = getCollection({\n adapter: this,\n collectionSlug: args.collection,\n })\n\n const { where = {} } = args\n\n let sortAggregation: PipelineStage[] = []\n\n const sort = buildSortParam({\n adapter: this,\n config: this.payload.config,\n fields: collectionConfig.flattenedFields,\n locale: args.locale,\n sort: args.sort ?? args.field,\n sortAggregation,\n timestamps: true,\n })\n\n const query = await buildQuery({\n adapter: this,\n collectionSlug: args.collection,\n fields: collectionConfig.flattenedFields,\n locale: args.locale,\n where,\n })\n\n const fieldPathResult = getFieldByPath({\n config: this.payload.config,\n fields: collectionConfig.flattenedFields,\n includeRelationships: true,\n path: args.field,\n })\n let fieldPath = args.field\n if (fieldPathResult?.pathHasLocalized && args.locale) {\n fieldPath = fieldPathResult.localizedPath.replace('<locale>', args.locale)\n }\n\n const page = args.page || 1\n\n let sortProperty = Object.keys(sort)[0]! // assert because buildSortParam always returns at least 1 key.\n const sortDirection = sort[sortProperty] === 'asc' ? 1 : -1\n\n let currentFields = collectionConfig.flattenedFields\n let foundField: FlattenedField | null = null\n\n let rels: {\n fieldPath: string\n relationTo: string\n }[] = []\n\n let tempPath = ''\n let insideRelation = false\n\n const segments = args.field.split('.')\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i]\n const field = currentFields.find((e) => e.name === segment)\n if (rels.length) {\n insideRelation = true\n }\n\n if (!field) {\n break\n }\n\n if (tempPath) {\n tempPath = `${tempPath}.${field.name}`\n } else {\n tempPath = field.name\n }\n\n if ('flattenedFields' in field) {\n currentFields = field.flattenedFields\n continue\n }\n\n if (\n (field.type === 'relationship' || field.type === 'upload') &&\n typeof field.relationTo === 'string'\n ) {\n if (i === segments.length - 2 && segments[i + 1] === 'id') {\n foundField = field\n fieldPath = tempPath\n break\n }\n rels.push({ fieldPath: tempPath, relationTo: field.relationTo })\n currentFields = this.payload.collections[field.relationTo]?.config\n .flattenedFields as FlattenedField[]\n continue\n }\n foundField = field\n }\n\n const resolvedField = foundField || fieldPathResult?.field\n const isHasManyValue = resolvedField && 'hasMany' in resolvedField && resolvedField\n\n let relationLookup: null | PipelineStage[] = null\n\n if (!insideRelation) {\n rels = []\n }\n\n if (rels.length) {\n if (sortProperty.startsWith('_')) {\n const sortWithoutRelationPrefix = sortProperty.replace(/^_+/, '')\n const lastFieldPath = rels.at(-1)?.fieldPath as string\n if (sortWithoutRelationPrefix.startsWith(lastFieldPath)) {\n sortProperty = sortWithoutRelationPrefix\n }\n }\n relationLookup = rels.reduce<PipelineStage[]>((acc, { fieldPath, relationTo }) => {\n sortAggregation = sortAggregation.filter((each) => {\n if ('$lookup' in each && each.$lookup.as.replace(/^_+/, '') === fieldPath) {\n return false\n }\n\n return true\n })\n const { Model: foreignModel } = getCollection({ adapter: this, collectionSlug: relationTo })\n acc.push({\n $lookup: {\n as: fieldPath,\n foreignField: '_id',\n from: foreignModel.collection.name,\n localField: fieldPath,\n },\n })\n acc.push({ $unwind: `$${fieldPath}` })\n return acc\n }, [])\n }\n\n let $unwind: any = ''\n let $group: any = null\n if (\n isHasManyValue &&\n sortAggregation.length &&\n sortAggregation[0] &&\n '$lookup' in sortAggregation[0]\n ) {\n $unwind = { path: `$${sortAggregation[0].$lookup.as}`, preserveNullAndEmptyArrays: true }\n $group = {\n _id: {\n _field: `$${sortAggregation[0].$lookup.as}._id`,\n _sort: `$${sortProperty}`,\n },\n }\n } else if (isHasManyValue) {\n $unwind = { path: `$${args.field}`, preserveNullAndEmptyArrays: true }\n }\n\n if (!$group) {\n $group = {\n _id: `$${fieldPath}`,\n ...(sortProperty === fieldPath\n ? {}\n : {\n _sort: { $max: `$${sortProperty}` },\n }),\n }\n }\n\n const pipeline: PipelineStage[] = [\n {\n $match: query,\n },\n ...(sortAggregation.length > 0 ? sortAggregation : []),\n ...(relationLookup?.length ? relationLookup : []),\n ...($unwind\n ? [\n {\n $unwind,\n },\n ]\n : []),\n {\n $group,\n },\n {\n $sort: getSortAggregation({\n fieldPath,\n hasSortAggregationAndHasMany: Boolean(isHasManyValue) && Boolean(sortAggregation.length),\n sortDirection,\n sortProperty,\n }),\n },\n ]\n\n const session = await getSession(this, args.req)\n\n const getValues = async () => {\n return Model.aggregate(pipeline, { session }).then((res) =>\n res.map((each) => ({\n [args.field]: JSON.parse(JSON.stringify(sanitizeGroupID(each._id))),\n })),\n )\n }\n\n if (args.limit) {\n pipeline.push({\n $skip: (page - 1) * args.limit,\n })\n pipeline.push({ $limit: args.limit })\n\n // Build count pipeline with the same structure as the main pipeline\n // to ensure relationship lookups are included\n const countPipeline: PipelineStage[] = [\n {\n $match: query,\n },\n ...(sortAggregation.length > 0 ? sortAggregation : []),\n ...(relationLookup?.length ? relationLookup : []),\n ...($unwind\n ? [\n {\n $unwind,\n },\n ]\n : []),\n {\n $group,\n },\n { $count: 'count' },\n ]\n\n const totalDocs = await Model.aggregate(countPipeline, {\n session,\n }).then((res) => res[0]?.count ?? 0)\n const totalPages = Math.ceil(totalDocs / args.limit)\n const hasPrevPage = page > 1\n const hasNextPage = totalPages > page\n const pagingCounter = (page - 1) * args.limit + 1\n\n return {\n hasNextPage,\n hasPrevPage,\n limit: args.limit,\n nextPage: hasNextPage ? page + 1 : null,\n page,\n pagingCounter,\n prevPage: hasPrevPage ? page - 1 : null,\n totalDocs,\n totalPages,\n values: await getValues(),\n }\n }\n\n const values = await getValues()\n\n return {\n hasNextPage: false,\n hasPrevPage: false,\n limit: 0,\n page: 1,\n pagingCounter: 1,\n totalDocs: values.length,\n totalPages: 1,\n values,\n }\n}\n"],"names":["getFieldByPath","buildQuery","buildSortParam","getCollection","getSession","sanitizeGroupID","id","_field","getSortAggregation","fieldPath","hasSortAggregationAndHasMany","sortDirection","sortProperty","resolvedSortProperty","findDistinct","args","collectionConfig","Model","adapter","collectionSlug","collection","where","sortAggregation","sort","config","payload","fields","flattenedFields","locale","field","timestamps","query","fieldPathResult","includeRelationships","path","pathHasLocalized","localizedPath","replace","page","Object","keys","currentFields","foundField","rels","tempPath","insideRelation","segments","split","i","length","segment","find","e","name","type","relationTo","push","collections","resolvedField","isHasManyValue","relationLookup","startsWith","sortWithoutRelationPrefix","lastFieldPath","at","reduce","acc","filter","each","$lookup","as","foreignModel","foreignField","from","localField","$unwind","$group","preserveNullAndEmptyArrays","_id","_sort","$max","pipeline","$match","$sort","Boolean","session","req","getValues","aggregate","then","res","map","JSON","parse","stringify","limit","$skip","$limit","countPipeline","$count","totalDocs","count","totalPages","Math","ceil","hasPrevPage","hasNextPage","pagingCounter","nextPage","prevPage","values"],"mappings":"AAGA,SAAS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D;YACAV,OAAOhF,KAAKgF,KAAK;YACjBa,UAAUF,cAAcpE,OAAO,IAAI;YACnCA;YACAqE;YACAE,UAAUJ,cAAcnE,OAAO,IAAI;YACnC8D;YACAE;YACAQ,QAAQ,MAAMvB;QAChB;IACF;IAEA,MAAMuB,SAAS,MAAMvB;IAErB,OAAO;QACLmB,aAAa;QACbD,aAAa;QACbV,OAAO;QACPzD,MAAM;QACNqE,eAAe;QACfP,WAAWU,OAAO7D,MAAM;QACxBqD,YAAY;QACZQ;IACF;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../src/findDistinct.ts"],"sourcesContent":["import type { PipelineStage } from 'mongoose'\nimport type { FindDistinct, FlattenedField } from 'payload'\n\nimport { getFieldByPath } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { buildQuery } from './queries/buildQuery.js'\nimport { buildSortParam } from './queries/buildSortParam.js'\nimport { getCollection } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\n\nconst sanitizeGroupID = (id: any) => {\n if (id && typeof id === 'object' && '_field' in id) {\n return id._field\n }\n\n return id\n}\n\nconst getSortAggregation = ({\n fieldPath,\n hasSortAggregationAndHasMany,\n sortDirection,\n sortProperty,\n}: {\n fieldPath: string\n hasSortAggregationAndHasMany: boolean\n sortDirection: -1 | 1\n sortProperty: string\n}): Record<string, -1 | 1> => {\n let resolvedSortProperty: string\n\n if (hasSortAggregationAndHasMany) {\n if (sortProperty === fieldPath) {\n resolvedSortProperty = `_id._field`\n } else {\n resolvedSortProperty = `_id._sort`\n }\n } else {\n resolvedSortProperty = sortProperty === fieldPath ? '_id' : '_sort'\n }\n\n return { [`${resolvedSortProperty}`]: sortDirection }\n}\n\nexport const findDistinct: FindDistinct = async function (this: MongooseAdapter, args) {\n const { collectionConfig, Model } = getCollection({\n adapter: this,\n collectionSlug: args.collection,\n })\n\n const { where = {} } = args\n\n let sortAggregation: PipelineStage[] = []\n\n const sort = buildSortParam({\n adapter: this,\n config: this.payload.config,\n fields: collectionConfig.flattenedFields,\n locale: args.locale,\n sort: args.sort ?? args.field,\n sortAggregation,\n timestamps: true,\n })\n\n const query = await buildQuery({\n adapter: this,\n collectionSlug: args.collection,\n fields: collectionConfig.flattenedFields,\n locale: args.locale,\n where,\n })\n\n const fieldPathResult = getFieldByPath({\n config: this.payload.config,\n fields: collectionConfig.flattenedFields,\n includeRelationships: true,\n path: args.field,\n })\n let fieldPath = args.field\n if (fieldPathResult?.pathHasLocalized && args.locale) {\n fieldPath = fieldPathResult.localizedPath.replace('<locale>', args.locale)\n }\n\n const page = args.page || 1\n\n let sortProperty = Object.keys(sort)[0]! // assert because buildSortParam always returns at least 1 key.\n const sortDirection = sort[sortProperty] === 'asc' ? 1 : -1\n\n let currentFields = collectionConfig.flattenedFields\n let foundField: FlattenedField | null = null\n\n let rels: {\n fieldPath: string\n relationTo: string\n }[] = []\n\n let tempPath = ''\n let insideRelation = false\n\n const segments = args.field.split('.')\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i]\n const field = currentFields.find((e) => e.name === segment)\n if (rels.length) {\n insideRelation = true\n }\n\n if (!field) {\n break\n }\n\n if (tempPath) {\n tempPath = `${tempPath}.${field.name}`\n } else {\n tempPath = field.name\n }\n\n if ('flattenedFields' in field) {\n currentFields = field.flattenedFields\n continue\n }\n\n if (\n (field.type === 'relationship' || field.type === 'upload') &&\n typeof field.relationTo === 'string'\n ) {\n if (i === segments.length - 2 && segments[i + 1] === 'id') {\n foundField = field\n fieldPath = tempPath\n break\n }\n rels.push({ fieldPath: tempPath, relationTo: field.relationTo })\n currentFields = this.payload.collections[field.relationTo]?.config\n .flattenedFields as FlattenedField[]\n continue\n }\n foundField = field\n }\n\n const resolvedField = foundField || fieldPathResult?.field\n const isHasManyValue = resolvedField && 'hasMany' in resolvedField && resolvedField\n\n let relationLookup: null | PipelineStage[] = null\n\n if (!insideRelation) {\n rels = []\n }\n\n if (rels.length) {\n if (sortProperty.startsWith('_')) {\n const sortWithoutRelationPrefix = sortProperty.replace(/^_+/, '')\n const lastFieldPath = rels.at(-1)?.fieldPath as string\n if (sortWithoutRelationPrefix.startsWith(lastFieldPath)) {\n sortProperty = sortWithoutRelationPrefix\n }\n }\n relationLookup = []\n for (const { fieldPath, relationTo } of rels) {\n sortAggregation = sortAggregation.filter((each) => {\n if ('$lookup' in each && each.$lookup.as.replace(/^_+/, '') === fieldPath) {\n return false\n }\n\n return true\n })\n const { collectionConfig: foreignCollectionConfig, Model: foreignModel } = getCollection({\n adapter: this,\n collectionSlug: relationTo,\n })\n const relatedAccess = args.relatedAccess?.[fieldPath]\n const relatedAccessQuery = relatedAccess\n ? await buildQuery({\n adapter: this,\n collectionSlug: relationTo,\n fields: foreignCollectionConfig.flattenedFields,\n locale: args.locale,\n where: relatedAccess,\n })\n : null\n\n relationLookup.push({\n $lookup: {\n as: fieldPath,\n from: foreignModel.collection.name,\n ...(relatedAccessQuery\n ? {\n let: { relatedIDs: `$${fieldPath}` },\n pipeline: [\n {\n $match: {\n $and: [\n {\n $expr: {\n $cond: {\n else: { $eq: ['$_id', '$$relatedIDs'] },\n if: { $isArray: '$$relatedIDs' },\n then: { $in: ['$_id', '$$relatedIDs'] },\n },\n },\n },\n relatedAccessQuery,\n ],\n },\n },\n ],\n }\n : {\n foreignField: '_id',\n localField: fieldPath,\n }),\n },\n })\n relationLookup.push({ $unwind: `$${fieldPath}` })\n }\n }\n\n let $unwind: any = ''\n let $group: any = null\n if (\n isHasManyValue &&\n sortAggregation.length &&\n sortAggregation[0] &&\n '$lookup' in sortAggregation[0]\n ) {\n $unwind = { path: `$${sortAggregation[0].$lookup.as}`, preserveNullAndEmptyArrays: true }\n $group = {\n _id: {\n _field: `$${sortAggregation[0].$lookup.as}._id`,\n _sort: `$${sortProperty}`,\n },\n }\n } else if (isHasManyValue) {\n $unwind = { path: `$${args.field}`, preserveNullAndEmptyArrays: true }\n }\n\n if (!$group) {\n $group = {\n _id: `$${fieldPath}`,\n ...(sortProperty === fieldPath\n ? {}\n : {\n _sort: { $max: `$${sortProperty}` },\n }),\n }\n }\n\n const pipeline: PipelineStage[] = [\n {\n $match: query,\n },\n ...(sortAggregation.length > 0 ? sortAggregation : []),\n ...(relationLookup?.length ? relationLookup : []),\n ...($unwind\n ? [\n {\n $unwind,\n },\n ]\n : []),\n {\n $group,\n },\n {\n $sort: getSortAggregation({\n fieldPath,\n hasSortAggregationAndHasMany: Boolean(isHasManyValue) && Boolean(sortAggregation.length),\n sortDirection,\n sortProperty,\n }),\n },\n ]\n\n const session = await getSession(this, args.req)\n\n const getValues = async () => {\n return Model.aggregate(pipeline, { session }).then((res) =>\n res.map((each) => ({\n [args.field]: JSON.parse(JSON.stringify(sanitizeGroupID(each._id))),\n })),\n )\n }\n\n if (args.limit) {\n pipeline.push({\n $skip: (page - 1) * args.limit,\n })\n pipeline.push({ $limit: args.limit })\n\n // Build count pipeline with the same structure as the main pipeline\n // to ensure relationship lookups are included\n const countPipeline: PipelineStage[] = [\n {\n $match: query,\n },\n ...(sortAggregation.length > 0 ? sortAggregation : []),\n ...(relationLookup?.length ? relationLookup : []),\n ...($unwind\n ? [\n {\n $unwind,\n },\n ]\n : []),\n {\n $group,\n },\n { $count: 'count' },\n ]\n\n const totalDocs = await Model.aggregate(countPipeline, {\n session,\n }).then((res) => res[0]?.count ?? 0)\n const totalPages = Math.ceil(totalDocs / args.limit)\n const hasPrevPage = page > 1\n const hasNextPage = totalPages > page\n const pagingCounter = (page - 1) * args.limit + 1\n\n return {\n hasNextPage,\n hasPrevPage,\n limit: args.limit,\n nextPage: hasNextPage ? page + 1 : null,\n page,\n pagingCounter,\n prevPage: hasPrevPage ? page - 1 : null,\n totalDocs,\n totalPages,\n values: await getValues(),\n }\n }\n\n const values = await getValues()\n\n return {\n hasNextPage: false,\n hasPrevPage: false,\n limit: 0,\n page: 1,\n pagingCounter: 1,\n totalDocs: values.length,\n totalPages: 1,\n values,\n }\n}\n"],"names":["getFieldByPath","buildQuery","buildSortParam","getCollection","getSession","sanitizeGroupID","id","_field","getSortAggregation","fieldPath","hasSortAggregationAndHasMany","sortDirection","sortProperty","resolvedSortProperty","findDistinct","args","collectionConfig","Model","adapter","collectionSlug","collection","where","sortAggregation","sort","config","payload","fields","flattenedFields","locale","field","timestamps","query","fieldPathResult","includeRelationships","path","pathHasLocalized","localizedPath","replace","page","Object","keys","currentFields","foundField","rels","tempPath","insideRelation","segments","split","i","length","segment","find","e","name","type","relationTo","push","collections","resolvedField","isHasManyValue","relationLookup","startsWith","sortWithoutRelationPrefix","lastFieldPath","at","filter","each","$lookup","as","foreignCollectionConfig","foreignModel","relatedAccess","relatedAccessQuery","from","let","relatedIDs","pipeline","$match","$and","$expr","$cond","else","$eq","if","$isArray","then","$in","foreignField","localField","$unwind","$group","preserveNullAndEmptyArrays","_id","_sort","$max","$sort","Boolean","session","req","getValues","aggregate","res","map","JSON","parse","stringify","limit","$skip","$limit","countPipeline","$count","totalDocs","count","totalPages","Math","ceil","hasPrevPage","hasNextPage","pagingCounter","nextPage","prevPage","values"],"mappings":"AAGA,SAASA,cAAc,QAAQ,UAAS;AAIxC,SAASC,UAAU,QAAQ,0BAAyB;AACpD,SAASC,cAAc,QAAQ,8BAA6B;AAC5D,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,UAAU,QAAQ,4BAA2B;AAEtD,MAAMC,kBAAkB,CAACC;IACvB,IAAIA,MAAM,OAAOA,OAAO,YAAY,YAAYA,IAAI;QAClD,OAAOA,GAAGC,MAAM;IAClB;IAEA,OAAOD;AACT;AAEA,MAAME,qBAAqB,CAAC,EAC1BC,SAAS,EACTC,4BAA4B,EAC5BC,aAAa,EACbC,YAAY,EAMb;IACC,IAAIC;IAEJ,IAAIH,8BAA8B;QAChC,IAAIE,iBAAiBH,WAAW;YAC9BI,uBAAuB,CAAC,UAAU,CAAC;QACrC,OAAO;YACLA,uBAAuB,CAAC,SAAS,CAAC;QACpC;IACF,OAAO;QACLA,uBAAuBD,iBAAiBH,YAAY,QAAQ;IAC9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AAAA,OAAO,CAAA,IAAKvB,KAAK2F,KAAK,GAAG;QAEhD,OAAO;YACLW;YACAD;YACAV,OAAO3F,KAAK2F,KAAK;YACjBa,UAAUF,cAAc/E,OAAO,IAAI;YACnCA;YACAgF;YACAE,UAAUJ,cAAc9E,OAAO,IAAI;YACnCyE;YACAE;YACAQ,QAAQ,MAAMtB;QAChB;IACF;IAEA,MAAMsB,SAAS,MAAMtB;IAErB,OAAO;QACLkB,aAAa;QACbD,aAAa;QACbV,OAAO;QACPpE,MAAM;QACNgF,eAAe;QACfP,WAAWU,OAAOxE,MAAM;QACxBgE,YAAY;QACZQ;IACF;AACF,EAAC"}
|
package/dist/init.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAA6B,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAA6B,MAAM,SAAS,CAAA;AAoB9D,eAAO,MAAM,IAAI,EAAE,IAqHlB,CAAA"}
|
package/dist/init.js
CHANGED
|
@@ -4,6 +4,7 @@ import { buildVersionCollectionFields, buildVersionCompoundIndexes, buildVersion
|
|
|
4
4
|
import { buildCollectionSchema } from './models/buildCollectionSchema.js';
|
|
5
5
|
import { buildGlobalModel } from './models/buildGlobalModel.js';
|
|
6
6
|
import { buildSchema } from './models/buildSchema.js';
|
|
7
|
+
import { createMongoSchemaBuildContext } from './models/schemaBuildContext.js';
|
|
7
8
|
import { getBuildQueryPlugin } from './queries/getBuildQueryPlugin.js';
|
|
8
9
|
import { getDBName } from './utilities/getDBName.js';
|
|
9
10
|
export const init = async function init() {
|
|
@@ -13,76 +14,97 @@ export const init = async function init() {
|
|
|
13
14
|
if (this.afterCreateConnection) {
|
|
14
15
|
await this.afterCreateConnection(this);
|
|
15
16
|
}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
const schema = buildCollectionSchema(collection, this.payload, schemaOptions);
|
|
19
|
-
if (collection.versions) {
|
|
20
|
-
const versionModelName = getDBName({
|
|
21
|
-
config: collection,
|
|
22
|
-
versions: true
|
|
23
|
-
});
|
|
24
|
-
const versionCollectionFields = buildVersionCollectionFields(this.payload.config, collection);
|
|
25
|
-
const versionSchema = buildSchema({
|
|
26
|
-
buildSchemaOptions: {
|
|
27
|
-
disableUnique: true,
|
|
28
|
-
draftsEnabled: true,
|
|
29
|
-
indexSortableFields: this.payload.config.indexSortableFields,
|
|
30
|
-
options: {
|
|
31
|
-
minimize: false,
|
|
32
|
-
timestamps: false,
|
|
33
|
-
...schemaOptions
|
|
34
|
-
}
|
|
35
|
-
},
|
|
36
|
-
compoundIndexes: buildVersionCompoundIndexes({
|
|
37
|
-
indexes: collection.sanitizedIndexes
|
|
38
|
-
}),
|
|
39
|
-
configFields: versionCollectionFields,
|
|
40
|
-
payload: this.payload
|
|
41
|
-
});
|
|
42
|
-
versionSchema.plugin(paginate, {
|
|
43
|
-
useEstimatedCount: true
|
|
44
|
-
}).plugin(getBuildQueryPlugin({
|
|
45
|
-
collectionSlug: collection.slug,
|
|
46
|
-
versionsFields: buildVersionCollectionFields(this.payload.config, collection, true)
|
|
47
|
-
}));
|
|
48
|
-
const versionCollectionName = this.autoPluralization === true && !collection.dbName ? undefined : versionModelName;
|
|
49
|
-
this.versions[collection.slug] = this.connection.model(versionModelName, versionSchema, versionCollectionName);
|
|
50
|
-
}
|
|
51
|
-
const modelName = getDBName({
|
|
52
|
-
config: collection
|
|
53
|
-
});
|
|
54
|
-
const collectionName = this.autoPluralization === true && !collection.dbName ? undefined : modelName;
|
|
55
|
-
this.collections[collection.slug] = this.connection.model(modelName, schema, collectionName);
|
|
17
|
+
const schemaBuildContext = createMongoSchemaBuildContext({
|
|
18
|
+
connection: this.connection
|
|
56
19
|
});
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
|
|
20
|
+
try {
|
|
21
|
+
this.payload.config.collections.forEach((collection)=>{
|
|
22
|
+
const schemaOptions = this.collectionsSchemaOptions?.[collection.slug];
|
|
23
|
+
const schema = buildCollectionSchema({
|
|
24
|
+
collection,
|
|
25
|
+
payload: this.payload,
|
|
26
|
+
schemaBuildContext,
|
|
27
|
+
schemaOptions
|
|
63
28
|
});
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
29
|
+
if (collection.versions) {
|
|
30
|
+
const versionModelName = getDBName({
|
|
31
|
+
config: collection,
|
|
32
|
+
versions: true
|
|
33
|
+
});
|
|
34
|
+
const versionCollectionFields = buildVersionCollectionFields(this.payload.config, collection);
|
|
35
|
+
const versionSchema = buildSchema({
|
|
36
|
+
buildSchemaOptions: {
|
|
37
|
+
disableUnique: true,
|
|
38
|
+
draftsEnabled: true,
|
|
39
|
+
indexSortableFields: this.payload.config.indexSortableFields,
|
|
40
|
+
options: {
|
|
41
|
+
minimize: false,
|
|
42
|
+
timestamps: false,
|
|
43
|
+
...schemaOptions
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
compoundIndexes: buildVersionCompoundIndexes({
|
|
47
|
+
indexes: collection.sanitizedIndexes
|
|
48
|
+
}),
|
|
49
|
+
configFields: versionCollectionFields,
|
|
50
|
+
isVersion: true,
|
|
51
|
+
payload: this.payload,
|
|
52
|
+
schemaBuildContext,
|
|
53
|
+
schemaPath: `collection:${collection.slug}`
|
|
54
|
+
});
|
|
55
|
+
versionSchema.plugin(paginate, {
|
|
56
|
+
useEstimatedCount: true
|
|
57
|
+
}).plugin(getBuildQueryPlugin({
|
|
58
|
+
collectionSlug: collection.slug,
|
|
59
|
+
versionsFields: buildVersionCollectionFields(this.payload.config, collection, true)
|
|
60
|
+
}));
|
|
61
|
+
const versionCollectionName = this.autoPluralization === true && !collection.dbName ? undefined : versionModelName;
|
|
62
|
+
this.versions[collection.slug] = this.connection.model(versionModelName, versionSchema, versionCollectionName);
|
|
63
|
+
}
|
|
64
|
+
const modelName = getDBName({
|
|
65
|
+
config: collection
|
|
77
66
|
});
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
}
|
|
85
|
-
|
|
67
|
+
const collectionName = this.autoPluralization === true && !collection.dbName ? undefined : modelName;
|
|
68
|
+
this.collections[collection.slug] = this.connection.model(modelName, schema, collectionName);
|
|
69
|
+
});
|
|
70
|
+
this.globals = buildGlobalModel({
|
|
71
|
+
adapter: this,
|
|
72
|
+
schemaBuildContext
|
|
73
|
+
});
|
|
74
|
+
this.payload.config.globals.forEach((global)=>{
|
|
75
|
+
if (global.versions) {
|
|
76
|
+
const versionModelName = getDBName({
|
|
77
|
+
config: global,
|
|
78
|
+
versions: true
|
|
79
|
+
});
|
|
80
|
+
const versionGlobalFields = buildVersionGlobalFields(this.payload.config, global);
|
|
81
|
+
const versionSchema = buildSchema({
|
|
82
|
+
buildSchemaOptions: {
|
|
83
|
+
disableUnique: true,
|
|
84
|
+
draftsEnabled: true,
|
|
85
|
+
indexSortableFields: this.payload.config.indexSortableFields,
|
|
86
|
+
options: {
|
|
87
|
+
minimize: false,
|
|
88
|
+
timestamps: false
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
configFields: versionGlobalFields,
|
|
92
|
+
isVersion: true,
|
|
93
|
+
payload: this.payload,
|
|
94
|
+
schemaBuildContext,
|
|
95
|
+
schemaPath: `global:${global.slug}`
|
|
96
|
+
});
|
|
97
|
+
versionSchema.plugin(paginate, {
|
|
98
|
+
useEstimatedCount: true
|
|
99
|
+
}).plugin(getBuildQueryPlugin({
|
|
100
|
+
versionsFields: buildVersionGlobalFields(this.payload.config, global, true)
|
|
101
|
+
}));
|
|
102
|
+
this.versions[global.slug] = this.connection.model(versionModelName, versionSchema, versionModelName);
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
} finally{
|
|
106
|
+
schemaBuildContext.clear();
|
|
107
|
+
}
|
|
86
108
|
};
|
|
87
109
|
|
|
88
110
|
//# sourceMappingURL=init.js.map
|
package/dist/init.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/init.ts"],"sourcesContent":["import type { PaginateOptions } from 'mongoose'\nimport type { Init, SanitizedCollectionConfig } from 'payload'\n\nimport mongoose from 'mongoose'\nimport paginate from 'mongoose-paginate-v2'\nimport {\n buildVersionCollectionFields,\n buildVersionCompoundIndexes,\n buildVersionGlobalFields,\n} from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\nimport type { CollectionModel, GlobalModel } from './types.js'\n\nimport { buildCollectionSchema } from './models/buildCollectionSchema.js'\nimport { buildGlobalModel } from './models/buildGlobalModel.js'\nimport { buildSchema } from './models/buildSchema.js'\nimport { getBuildQueryPlugin } from './queries/getBuildQueryPlugin.js'\nimport { getDBName } from './utilities/getDBName.js'\n\nexport const init: Init = async function init(this: MongooseAdapter) {\n // Always create a scoped, **unopened** connection object\n // (no URI here; models compile per-connection and do not require an open socket)\n this.connection ??= mongoose.createConnection()\n\n if (this.afterCreateConnection) {\n await this.afterCreateConnection(this)\n }\n\n this.payload.config.collections.forEach((collection: SanitizedCollectionConfig) => {\n
|
|
1
|
+
{"version":3,"sources":["../src/init.ts"],"sourcesContent":["import type { PaginateOptions } from 'mongoose'\nimport type { Init, SanitizedCollectionConfig } from 'payload'\n\nimport mongoose from 'mongoose'\nimport paginate from 'mongoose-paginate-v2'\nimport {\n buildVersionCollectionFields,\n buildVersionCompoundIndexes,\n buildVersionGlobalFields,\n} from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\nimport type { CollectionModel, GlobalModel } from './types.js'\n\nimport { buildCollectionSchema } from './models/buildCollectionSchema.js'\nimport { buildGlobalModel } from './models/buildGlobalModel.js'\nimport { buildSchema } from './models/buildSchema.js'\nimport { createMongoSchemaBuildContext } from './models/schemaBuildContext.js'\nimport { getBuildQueryPlugin } from './queries/getBuildQueryPlugin.js'\nimport { getDBName } from './utilities/getDBName.js'\n\nexport const init: Init = async function init(this: MongooseAdapter) {\n // Always create a scoped, **unopened** connection object\n // (no URI here; models compile per-connection and do not require an open socket)\n this.connection ??= mongoose.createConnection()\n\n if (this.afterCreateConnection) {\n await this.afterCreateConnection(this)\n }\n\n const schemaBuildContext = createMongoSchemaBuildContext({ connection: this.connection })\n\n try {\n this.payload.config.collections.forEach((collection: SanitizedCollectionConfig) => {\n const schemaOptions = this.collectionsSchemaOptions?.[collection.slug]\n\n const schema = buildCollectionSchema({\n collection,\n payload: this.payload,\n schemaBuildContext,\n schemaOptions,\n })\n if (collection.versions) {\n const versionModelName = getDBName({ config: collection, versions: true })\n\n const versionCollectionFields = buildVersionCollectionFields(\n this.payload.config,\n collection,\n )\n\n const versionSchema = buildSchema({\n buildSchemaOptions: {\n disableUnique: true,\n draftsEnabled: true,\n indexSortableFields: this.payload.config.indexSortableFields,\n options: {\n minimize: false,\n timestamps: false,\n ...schemaOptions,\n },\n },\n compoundIndexes: buildVersionCompoundIndexes({ indexes: collection.sanitizedIndexes }),\n configFields: versionCollectionFields,\n isVersion: true,\n payload: this.payload,\n schemaBuildContext,\n schemaPath: `collection:${collection.slug}`,\n })\n\n versionSchema.plugin<any, PaginateOptions>(paginate, { useEstimatedCount: true }).plugin(\n getBuildQueryPlugin({\n collectionSlug: collection.slug,\n versionsFields: buildVersionCollectionFields(this.payload.config, collection, true),\n }),\n )\n\n const versionCollectionName =\n this.autoPluralization === true && !collection.dbName ? undefined : versionModelName\n\n this.versions[collection.slug] = this.connection.model(\n versionModelName,\n versionSchema,\n versionCollectionName,\n ) as unknown as CollectionModel\n }\n\n const modelName = getDBName({ config: collection })\n const collectionName =\n this.autoPluralization === true && !collection.dbName ? undefined : modelName\n\n this.collections[collection.slug] = this.connection.model<any>(\n modelName,\n schema,\n collectionName,\n ) as CollectionModel\n })\n\n this.globals = buildGlobalModel({ adapter: this, schemaBuildContext }) as GlobalModel\n\n this.payload.config.globals.forEach((global) => {\n if (global.versions) {\n const versionModelName = getDBName({ config: global, versions: true })\n\n const versionGlobalFields = buildVersionGlobalFields(this.payload.config, global)\n\n const versionSchema = buildSchema({\n buildSchemaOptions: {\n disableUnique: true,\n draftsEnabled: true,\n indexSortableFields: this.payload.config.indexSortableFields,\n options: {\n minimize: false,\n timestamps: false,\n },\n },\n configFields: versionGlobalFields,\n isVersion: true,\n payload: this.payload,\n schemaBuildContext,\n schemaPath: `global:${global.slug}`,\n })\n\n versionSchema.plugin<any, PaginateOptions>(paginate, { useEstimatedCount: true }).plugin(\n getBuildQueryPlugin({\n versionsFields: buildVersionGlobalFields(this.payload.config, global, true),\n }),\n )\n\n this.versions[global.slug] = this.connection.model<any>(\n versionModelName,\n versionSchema,\n versionModelName,\n ) as CollectionModel\n }\n })\n } finally {\n schemaBuildContext.clear()\n }\n}\n"],"names":["mongoose","paginate","buildVersionCollectionFields","buildVersionCompoundIndexes","buildVersionGlobalFields","buildCollectionSchema","buildGlobalModel","buildSchema","createMongoSchemaBuildContext","getBuildQueryPlugin","getDBName","init","connection","createConnection","afterCreateConnection","schemaBuildContext","payload","config","collections","forEach","collection","schemaOptions","collectionsSchemaOptions","slug","schema","versions","versionModelName","versionCollectionFields","versionSchema","buildSchemaOptions","disableUnique","draftsEnabled","indexSortableFields","options","minimize","timestamps","compoundIndexes","indexes","sanitizedIndexes","configFields","isVersion","schemaPath","plugin","useEstimatedCount","collectionSlug","versionsFields","versionCollectionName","autoPluralization","dbName","undefined","model","modelName","collectionName","globals","adapter","global","versionGlobalFields","clear"],"mappings":"AAGA,OAAOA,cAAc,WAAU;AAC/B,OAAOC,cAAc,uBAAsB;AAC3C,SACEC,4BAA4B,EAC5BC,2BAA2B,EAC3BC,wBAAw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CAACC,MAAM,CAACe,mBAAmB;wBAC5DC,SAAS;4BACPC,UAAU;4BACVC,YAAY;wBACd;oBACF;oBACAI,cAAciB;oBACdhB,WAAW;oBACXxB,SAAS,IAAI,CAACA,OAAO;oBACrBD;oBACA0B,YAAY,CAAC,OAAO,EAAEc,OAAOhC,IAAI,EAAE;gBACrC;gBAEAK,cAAcc,MAAM,CAAuBzC,UAAU;oBAAE0C,mBAAmB;gBAAK,GAAGD,MAAM,CACtFjC,oBAAoB;oBAClBoC,gBAAgBzC,yBAAyB,IAAI,CAACY,OAAO,CAACC,MAAM,EAAEsC,QAAQ;gBACxE;gBAGF,IAAI,CAAC9B,QAAQ,CAAC8B,OAAOhC,IAAI,CAAC,GAAG,IAAI,CAACX,UAAU,CAACsC,KAAK,CAChDxB,kBACAE,eACAF;YAEJ;QACF;IACF,SAAU;QACRX,mBAAmB0C,KAAK;IAC1B;AACF,EAAC"}
|
package/dist/migrateFresh.d.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import type { MigrationResult } from 'payload';
|
|
1
2
|
import type { MongooseAdapter } from './index.js';
|
|
2
3
|
/**
|
|
3
4
|
* Drop the current database and run all migrate up functions
|
|
4
5
|
*/
|
|
5
|
-
export declare function migrateFresh(this: MongooseAdapter, { forceAcceptWarning }: {
|
|
6
|
+
export declare function migrateFresh(this: MongooseAdapter, { forceAcceptWarning, shouldPrompt, }: {
|
|
6
7
|
forceAcceptWarning?: boolean;
|
|
7
|
-
|
|
8
|
+
shouldPrompt?: boolean;
|
|
9
|
+
}): Promise<MigrationResult>;
|
|
8
10
|
//# sourceMappingURL=migrateFresh.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migrateFresh.d.ts","sourceRoot":"","sources":["../src/migrateFresh.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"migrateFresh.d.ts","sourceRoot":"","sources":["../src/migrateFresh.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAK9C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAEjD;;GAEG;AACH,wBAAsB,YAAY,CAChC,IAAI,EAAE,eAAe,EACrB,EACE,kBAA0B,EAC1B,YAAmB,GACpB,EAAE;IAAE,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAAC,YAAY,CAAC,EAAE,OAAO,CAAA;CAAE,GAC1D,OAAO,CAAC,eAAe,CAAC,CAkE1B"}
|
package/dist/migrateFresh.js
CHANGED
|
@@ -2,21 +2,28 @@ import { commitTransaction, initTransaction, killTransaction, readMigrationFiles
|
|
|
2
2
|
import prompts from 'prompts';
|
|
3
3
|
/**
|
|
4
4
|
* Drop the current database and run all migrate up functions
|
|
5
|
-
*/ export async function migrateFresh({ forceAcceptWarning = false }) {
|
|
5
|
+
*/ export async function migrateFresh({ forceAcceptWarning = false, shouldPrompt = true }) {
|
|
6
6
|
const { payload } = this;
|
|
7
7
|
if (!forceAcceptWarning) {
|
|
8
|
+
if (!shouldPrompt) {
|
|
9
|
+
return {
|
|
10
|
+
cancelled: true,
|
|
11
|
+
migrated: [],
|
|
12
|
+
rolledBack: []
|
|
13
|
+
};
|
|
14
|
+
}
|
|
8
15
|
const { confirm: acceptWarning } = await prompts({
|
|
9
16
|
name: 'confirm',
|
|
10
17
|
type: 'confirm',
|
|
11
18
|
initial: false,
|
|
12
19
|
message: `WARNING: This will drop your database and run all migrations. Are you sure you want to proceed?`
|
|
13
|
-
}, {
|
|
14
|
-
onCancel: ()=>{
|
|
15
|
-
process.exit(0);
|
|
16
|
-
}
|
|
17
20
|
});
|
|
18
21
|
if (!acceptWarning) {
|
|
19
|
-
|
|
22
|
+
return {
|
|
23
|
+
cancelled: true,
|
|
24
|
+
migrated: [],
|
|
25
|
+
rolledBack: []
|
|
26
|
+
};
|
|
20
27
|
}
|
|
21
28
|
}
|
|
22
29
|
payload.logger.info({
|
|
@@ -32,6 +39,7 @@ import prompts from 'prompts';
|
|
|
32
39
|
const req = {
|
|
33
40
|
payload
|
|
34
41
|
};
|
|
42
|
+
const migrated = [];
|
|
35
43
|
// Run all migrate up
|
|
36
44
|
for (const migration of migrationFiles){
|
|
37
45
|
payload.logger.info({
|
|
@@ -50,9 +58,11 @@ import prompts from 'prompts';
|
|
|
50
58
|
name: migration.name,
|
|
51
59
|
batch: 1
|
|
52
60
|
},
|
|
61
|
+
overrideAccess: true,
|
|
53
62
|
req
|
|
54
63
|
});
|
|
55
64
|
await commitTransaction(req);
|
|
65
|
+
migrated.push(migration.name);
|
|
56
66
|
payload.logger.info({
|
|
57
67
|
msg: `Migrated: ${migration.name} (${Date.now() - start}ms)`
|
|
58
68
|
});
|
|
@@ -65,6 +75,11 @@ import prompts from 'prompts';
|
|
|
65
75
|
throw err;
|
|
66
76
|
}
|
|
67
77
|
}
|
|
78
|
+
return {
|
|
79
|
+
batch: 1,
|
|
80
|
+
migrated,
|
|
81
|
+
rolledBack: []
|
|
82
|
+
};
|
|
68
83
|
}
|
|
69
84
|
|
|
70
85
|
//# sourceMappingURL=migrateFresh.js.map
|