@payloadcms/db-mongodb 3.44.0-internal.6b79dc2 → 3.45.0-canary.0
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/index.d.ts +8 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/queries/buildSortParam.d.ts +1 -1
- package/dist/queries/buildSortParam.d.ts.map +1 -1
- package/dist/queries/buildSortParam.js +10 -1
- package/dist/queries/buildSortParam.js.map +1 -1
- package/dist/queries/buildSortParam.spec.js +122 -0
- package/dist/queries/buildSortParam.spec.js.map +1 -0
- package/dist/utilities/transform.d.ts.map +1 -1
- package/dist/utilities/transform.js +38 -8
- package/dist/utilities/transform.js.map +1 -1
- package/package.json +3 -3
package/dist/index.d.ts
CHANGED
@@ -58,6 +58,13 @@ export interface Args {
|
|
58
58
|
*/
|
59
59
|
useFacet?: boolean;
|
60
60
|
} & ConnectOptions;
|
61
|
+
/**
|
62
|
+
* We add a secondary sort based on `createdAt` to ensure that results are always returned in the same order when sorting by a non-unique field.
|
63
|
+
* This is because MongoDB does not guarantee the order of results, however in very large datasets this could affect performance.
|
64
|
+
*
|
65
|
+
* Set to `true` to disable this behaviour.
|
66
|
+
*/
|
67
|
+
disableFallbackSort?: boolean;
|
61
68
|
/** Set to true to disable hinting to MongoDB to use 'id' as index. This is currently done when counting documents for pagination. Disabling this optimization might fix some problems with AWS DocumentDB. Defaults to false */
|
62
69
|
disableIndexHints?: boolean;
|
63
70
|
/**
|
@@ -126,5 +133,5 @@ declare module 'payload' {
|
|
126
133
|
};
|
127
134
|
}
|
128
135
|
}
|
129
|
-
export declare function mongooseAdapter({ allowAdditionalKeys, allowIDOnCreate, autoPluralization, collectionsSchemaOptions, connectOptions, disableIndexHints, ensureIndexes, migrationDir: migrationDirArg, mongoMemoryServer, prodMigrations, transactionOptions, url, }: Args): DatabaseAdapterObj;
|
136
|
+
export declare function mongooseAdapter({ allowAdditionalKeys, allowIDOnCreate, autoPluralization, collectionsSchemaOptions, connectOptions, disableFallbackSort, disableIndexHints, ensureIndexes, migrationDir: migrationDirArg, mongoMemoryServer, prodMigrations, transactionOptions, url, }: Args): DatabaseAdapterObj;
|
130
137
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAA;AACnE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAA;AAC/D,OAAO,KAAK,EACV,aAAa,EACb,UAAU,EACV,cAAc,EACd,YAAY,EACZ,aAAa,EACd,MAAM,UAAU,CAAA;AACjB,OAAO,KAAK,EACV,mBAAmB,EACnB,cAAc,EACd,kBAAkB,EAClB,SAAS,EAET,UAAU,EACV,eAAe,EACf,gBAAgB,EAChB,uBAAuB,EACvB,aAAa,EACb,iBAAiB,EAClB,MAAM,SAAS,CAAA;AAOhB,OAAO,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAkC9F,YAAY,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAEhE,MAAM,WAAW,IAAI;IACnB;;;;;OAKG;IACH,mBAAmB,CAAC,EAAE,OAAO,CAAA;IAC7B;;;;;;;;;OASG;IACH,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,uFAAuF;IACvF,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAE3B;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACH,SAAS,CAAC,EAAE,IAAI,CAAC,gBAAgB,EAAE,QAAQ,CAAC,CAAA;IAE5C,wBAAwB,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,cAAc,EAAE,aAAa,CAAC,CAAC,CA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KAAK,OAAO,CAAC,QAAQ,CAAC,CAAA;QAClF,aAAa,EAAE,CAAC,CAAC,SAAS,UAAU,GAAG,UAAU,EAC/C,IAAI,EAAE;YAAE,OAAO,CAAC,EAAE,YAAY,CAAA;SAAE,GAAG,iBAAiB,CAAC,CAAC,CAAC,KACpD,OAAO,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAA;QAChC,QAAQ,EAAE;YACR,CAAC,IAAI,EAAE,MAAM,GAAG,eAAe,CAAA;SAChC,CAAA;KACF;CACF;AAED,wBAAgB,eAAe,CAAC,EAC9B,mBAA2B,EAC3B,eAAuB,EACvB,iBAAwB,EACxB,wBAA6B,EAC7B,cAAc,EACd,mBAA2B,EAC3B,iBAAyB,EACzB,aAAqB,EACrB,YAAY,EAAE,eAAe,EAC7B,iBAAiB,EACjB,cAAc,EACd,kBAAuB,EACvB,GAAG,GACJ,EAAE,IAAI,GAAG,kBAAkB,CA0E3B"}
|
package/dist/index.js
CHANGED
@@ -33,7 +33,7 @@ import { updateMany } from './updateMany.js';
|
|
33
33
|
import { updateOne } from './updateOne.js';
|
34
34
|
import { updateVersion } from './updateVersion.js';
|
35
35
|
import { upsert } from './upsert.js';
|
36
|
-
export function mongooseAdapter({ allowAdditionalKeys = false, allowIDOnCreate = false, autoPluralization = true, collectionsSchemaOptions = {}, connectOptions, disableIndexHints = false, ensureIndexes = false, migrationDir: migrationDirArg, mongoMemoryServer, prodMigrations, transactionOptions = {}, url }) {
|
36
|
+
export function mongooseAdapter({ allowAdditionalKeys = false, allowIDOnCreate = false, autoPluralization = true, collectionsSchemaOptions = {}, connectOptions, disableFallbackSort = false, disableIndexHints = false, ensureIndexes = false, migrationDir: migrationDirArg, mongoMemoryServer, prodMigrations, transactionOptions = {}, url }) {
|
37
37
|
function adapter({ payload }) {
|
38
38
|
const migrationDir = findMigrationDir(migrationDirArg);
|
39
39
|
mongoose.set('strictQuery', false);
|
@@ -77,6 +77,7 @@ export function mongooseAdapter({ allowAdditionalKeys = false, allowIDOnCreate =
|
|
77
77
|
deleteOne,
|
78
78
|
deleteVersions,
|
79
79
|
destroy,
|
80
|
+
disableFallbackSort,
|
80
81
|
find,
|
81
82
|
findGlobal,
|
82
83
|
findGlobalVersions,
|
package/dist/index.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { CollationOptions, TransactionOptions } from 'mongodb'\nimport type { MongoMemoryReplSet } from 'mongodb-memory-server'\nimport type {\n ClientSession,\n Connection,\n ConnectOptions,\n QueryOptions,\n SchemaOptions,\n} from 'mongoose'\nimport type {\n BaseDatabaseAdapter,\n CollectionSlug,\n DatabaseAdapterObj,\n Migration,\n Payload,\n TypeWithID,\n TypeWithVersion,\n UpdateGlobalArgs,\n UpdateGlobalVersionArgs,\n UpdateOneArgs,\n UpdateVersionArgs,\n} from 'payload'\n\nimport fs from 'fs'\nimport mongoose from 'mongoose'\nimport path from 'path'\nimport { createDatabaseAdapter, defaultBeginTransaction } from 'payload'\n\nimport type { CollectionModel, GlobalModel, MigrateDownArgs, MigrateUpArgs } from './types.js'\n\nimport { connect } from './connect.js'\nimport { count } from './count.js'\nimport { countGlobalVersions } from './countGlobalVersions.js'\nimport { countVersions } from './countVersions.js'\nimport { create } from './create.js'\nimport { createGlobal } from './createGlobal.js'\nimport { createGlobalVersion } from './createGlobalVersion.js'\nimport { createMigration } from './createMigration.js'\nimport { createVersion } from './createVersion.js'\nimport { deleteMany } from './deleteMany.js'\nimport { deleteOne } from './deleteOne.js'\nimport { deleteVersions } from './deleteVersions.js'\nimport { destroy } from './destroy.js'\nimport { find } from './find.js'\nimport { findGlobal } from './findGlobal.js'\nimport { findGlobalVersions } from './findGlobalVersions.js'\nimport { findOne } from './findOne.js'\nimport { findVersions } from './findVersions.js'\nimport { init } from './init.js'\nimport { migrateFresh } from './migrateFresh.js'\nimport { queryDrafts } from './queryDrafts.js'\nimport { beginTransaction } from './transactions/beginTransaction.js'\nimport { commitTransaction } from './transactions/commitTransaction.js'\nimport { rollbackTransaction } from './transactions/rollbackTransaction.js'\nimport { updateGlobal } from './updateGlobal.js'\nimport { updateGlobalVersion } from './updateGlobalVersion.js'\nimport { updateJobs } from './updateJobs.js'\nimport { updateMany } from './updateMany.js'\nimport { updateOne } from './updateOne.js'\nimport { updateVersion } from './updateVersion.js'\nimport { upsert } from './upsert.js'\n\nexport type { MigrateDownArgs, MigrateUpArgs } from './types.js'\n\nexport interface Args {\n /**\n * By default, Payload strips all additional keys from MongoDB data that don't exist\n * in the Payload schema. If you have some data that you want to include to the result\n * but it doesn't exist in Payload, you can enable this flag\n * @default false\n */\n allowAdditionalKeys?: boolean\n /**\n * Enable this flag if you want to thread your own ID to create operation data, for example:\n * ```ts\n * import { Types } from 'mongoose'\n *\n * const id = new Types.ObjectId().toHexString()\n * const doc = await payload.create({ collection: 'posts', data: {id, title: \"my title\"}})\n * assertEq(doc.id, id)\n * ```\n */\n allowIDOnCreate?: boolean\n /** Set to false to disable auto-pluralization of collection names, Defaults to true */\n autoPluralization?: boolean\n\n /**\n * If enabled, collation allows for language-specific rules for string comparison.\n * This configuration can include the following options:\n *\n * - `strength` (number): Comparison level (1: Primary, 2: Secondary, 3: Tertiary (default), 4: Quaternary, 5: Identical)\n * - `caseLevel` (boolean): Include case comparison at strength level 1 or 2.\n * - `caseFirst` (string): Sort order of case differences during tertiary level comparisons (\"upper\", \"lower\", \"off\").\n * - `numericOrdering` (boolean): Compare numeric strings as numbers.\n * - `alternate` (string): Consider whitespace and punctuation as base characters (\"non-ignorable\", \"shifted\").\n * - `maxVariable` (string): Characters considered ignorable when `alternate` is \"shifted\" (\"punct\", \"space\").\n * - `backwards` (boolean): Sort strings with diacritics from back of the string.\n * - `normalization` (boolean): Check if text requires normalization and perform normalization.\n *\n * Available on MongoDB version 3.4 and up.\n * The locale that gets passed is your current project's locale but defaults to \"en\".\n *\n * Example:\n * {\n * strength: 3\n * }\n *\n * Defaults to disabled.\n */\n collation?: Omit<CollationOptions, 'locale'>\n\n collectionsSchemaOptions?: Partial<Record<CollectionSlug, SchemaOptions>>\n /** Extra configuration options */\n connectOptions?: {\n /**\n * Set false to disable $facet aggregation in non-supporting databases, Defaults to true\n * @deprecated Payload doesn't use `$facet` anymore anywhere.\n */\n useFacet?: boolean\n } & ConnectOptions\n /** Set to true to disable hinting to MongoDB to use 'id' as index. This is currently done when counting documents for pagination. Disabling this optimization might fix some problems with AWS DocumentDB. Defaults to false */\n disableIndexHints?: boolean\n /**\n * Set to `true` to ensure that indexes are ready before completing connection.\n * NOTE: not recommended for production. This can slow down the initialization of Payload.\n */\n ensureIndexes?: boolean\n migrationDir?: string\n /**\n * typed as any to avoid dependency\n */\n mongoMemoryServer?: MongoMemoryReplSet\n prodMigrations?: Migration[]\n transactionOptions?: false | TransactionOptions\n\n /** The URL to connect to MongoDB or false to start payload and prevent connecting */\n url: false | string\n}\n\nexport type MongooseAdapter = {\n collections: {\n [slug: string]: CollectionModel\n }\n connection: Connection\n ensureIndexes: boolean\n globals: GlobalModel\n mongoMemoryServer: MongoMemoryReplSet\n prodMigrations?: {\n down: (args: MigrateDownArgs) => Promise<void>\n name: string\n up: (args: MigrateUpArgs) => Promise<void>\n }[]\n sessions: Record<number | string, ClientSession>\n versions: {\n [slug: string]: CollectionModel\n }\n} & Args &\n BaseDatabaseAdapter\n\ndeclare module 'payload' {\n export interface DatabaseAdapter\n extends Omit<BaseDatabaseAdapter, 'sessions'>,\n Omit<Args, 'migrationDir'> {\n collections: {\n [slug: string]: CollectionModel\n }\n connection: Connection\n ensureIndexes: boolean\n globals: GlobalModel\n mongoMemoryServer: MongoMemoryReplSet\n prodMigrations?: {\n down: (args: MigrateDownArgs) => Promise<void>\n name: string\n up: (args: MigrateUpArgs) => Promise<void>\n }[]\n sessions: Record<number | string, ClientSession>\n transactionOptions: TransactionOptions\n updateGlobal: <T extends Record<string, unknown>>(\n args: { options?: QueryOptions } & UpdateGlobalArgs<T>,\n ) => Promise<T>\n updateGlobalVersion: <T extends TypeWithID = TypeWithID>(\n args: { options?: QueryOptions } & UpdateGlobalVersionArgs<T>,\n ) => Promise<TypeWithVersion<T>>\n\n updateOne: (args: { options?: QueryOptions } & UpdateOneArgs) => Promise<Document>\n updateVersion: <T extends TypeWithID = TypeWithID>(\n args: { options?: QueryOptions } & UpdateVersionArgs<T>,\n ) => Promise<TypeWithVersion<T>>\n versions: {\n [slug: string]: CollectionModel\n }\n }\n}\n\nexport function mongooseAdapter({\n allowAdditionalKeys = false,\n allowIDOnCreate = false,\n autoPluralization = true,\n collectionsSchemaOptions = {},\n connectOptions,\n disableIndexHints = false,\n ensureIndexes = false,\n migrationDir: migrationDirArg,\n mongoMemoryServer,\n prodMigrations,\n transactionOptions = {},\n url,\n}: Args): DatabaseAdapterObj {\n function adapter({ payload }: { payload: Payload }) {\n const migrationDir = findMigrationDir(migrationDirArg)\n mongoose.set('strictQuery', false)\n\n return createDatabaseAdapter<MongooseAdapter>({\n name: 'mongoose',\n\n // Mongoose-specific\n autoPluralization,\n collections: {},\n // @ts-expect-error initialize without a connection\n connection: undefined,\n connectOptions: connectOptions || {},\n disableIndexHints,\n ensureIndexes,\n // @ts-expect-error don't have globals model yet\n globals: undefined,\n // @ts-expect-error Should not be required\n mongoMemoryServer,\n sessions: {},\n transactionOptions: transactionOptions === false ? undefined : transactionOptions,\n updateJobs,\n updateMany,\n url,\n versions: {},\n // DatabaseAdapter\n allowAdditionalKeys,\n allowIDOnCreate,\n beginTransaction: transactionOptions === false ? defaultBeginTransaction() : beginTransaction,\n collectionsSchemaOptions,\n commitTransaction,\n connect,\n count,\n countGlobalVersions,\n countVersions,\n create,\n createGlobal,\n createGlobalVersion,\n createMigration,\n createVersion,\n defaultIDType: 'text',\n deleteMany,\n deleteOne,\n deleteVersions,\n destroy,\n find,\n findGlobal,\n findGlobalVersions,\n findOne,\n findVersions,\n init,\n migrateFresh,\n migrationDir,\n packageName: '@payloadcms/db-mongodb',\n payload,\n prodMigrations,\n queryDrafts,\n rollbackTransaction,\n updateGlobal,\n updateGlobalVersion,\n updateOne,\n updateVersion,\n upsert,\n })\n }\n\n return {\n name: 'mongoose',\n allowIDOnCreate,\n defaultIDType: 'text',\n init: adapter,\n }\n}\n\n/**\n * Attempt to find migrations directory.\n *\n * Checks for the following directories in order:\n * - `migrationDir` argument from Payload config\n * - `src/migrations`\n * - `dist/migrations`\n * - `migrations`\n *\n * Defaults to `src/migrations`\n *\n * @param migrationDir\n * @returns\n */\nfunction findMigrationDir(migrationDir?: string): string {\n const cwd = process.cwd()\n const srcDir = path.resolve(cwd, 'src/migrations')\n const distDir = path.resolve(cwd, 'dist/migrations')\n const relativeMigrations = path.resolve(cwd, 'migrations')\n\n // Use arg if provided\n if (migrationDir) {\n return migrationDir\n }\n\n // Check other common locations\n if (fs.existsSync(srcDir)) {\n return srcDir\n }\n\n if (fs.existsSync(distDir)) {\n return distDir\n }\n\n if (fs.existsSync(relativeMigrations)) {\n return relativeMigrations\n }\n\n return srcDir\n}\n"],"names":["fs","mongoose","path","createDatabaseAdapter","defaultBeginTransaction","connect","count","countGlobalVersions","countVersions","create","createGlobal","createGlobalVersion","createMigration","createVersion","deleteMany","deleteOne","deleteVersions","destroy","find","findGlobal","findGlobalVersions","findOne","findVersions","init","migrateFresh","queryDrafts","beginTransaction","commitTransaction","rollbackTransaction","updateGlobal","updateGlobalVersion","updateJobs","updateMany","updateOne","updateVersion","upsert","mongooseAdapter","allowAdditionalKeys","allowIDOnCreate","autoPluralization","collectionsSchemaOptions","connectOptions","disableIndexHints","ensureIndexes","migrationDir","migrationDirArg","mongoMemoryServer","prodMigrations","transactionOptions","url","adapter","payload","findMigrationDir","set","name","collections","connection","undefined","globals","sessions","versions","defaultIDType","packageName","cwd","process","srcDir","resolve","distDir","relativeMigrations","existsSync"],"mappings":"AAuBA,OAAOA,QAAQ,KAAI;AACnB,OAAOC,cAAc,WAAU;AAC/B,OAAOC,UAAU,OAAM;AACvB,SAASC,qBAAqB,EAAEC,uBAAuB,QAAQ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,SAAS;QACzB,OAAOA;IACT;IAEA,IAAIjE,GAAGqE,UAAU,CAACF,UAAU;QAC1B,OAAOA;IACT;IAEA,IAAInE,GAAGqE,UAAU,CAACD,qBAAqB;QACrC,OAAOA;IACT;IAEA,OAAOH;AACT"}
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { CollationOptions, TransactionOptions } from 'mongodb'\nimport type { MongoMemoryReplSet } from 'mongodb-memory-server'\nimport type {\n ClientSession,\n Connection,\n ConnectOptions,\n QueryOptions,\n SchemaOptions,\n} from 'mongoose'\nimport type {\n BaseDatabaseAdapter,\n CollectionSlug,\n DatabaseAdapterObj,\n Migration,\n Payload,\n TypeWithID,\n TypeWithVersion,\n UpdateGlobalArgs,\n UpdateGlobalVersionArgs,\n UpdateOneArgs,\n UpdateVersionArgs,\n} from 'payload'\n\nimport fs from 'fs'\nimport mongoose from 'mongoose'\nimport path from 'path'\nimport { createDatabaseAdapter, defaultBeginTransaction } from 'payload'\n\nimport type { CollectionModel, GlobalModel, MigrateDownArgs, MigrateUpArgs } from './types.js'\n\nimport { connect } from './connect.js'\nimport { count } from './count.js'\nimport { countGlobalVersions } from './countGlobalVersions.js'\nimport { countVersions } from './countVersions.js'\nimport { create } from './create.js'\nimport { createGlobal } from './createGlobal.js'\nimport { createGlobalVersion } from './createGlobalVersion.js'\nimport { createMigration } from './createMigration.js'\nimport { createVersion } from './createVersion.js'\nimport { deleteMany } from './deleteMany.js'\nimport { deleteOne } from './deleteOne.js'\nimport { deleteVersions } from './deleteVersions.js'\nimport { destroy } from './destroy.js'\nimport { find } from './find.js'\nimport { findGlobal } from './findGlobal.js'\nimport { findGlobalVersions } from './findGlobalVersions.js'\nimport { findOne } from './findOne.js'\nimport { findVersions } from './findVersions.js'\nimport { init } from './init.js'\nimport { migrateFresh } from './migrateFresh.js'\nimport { queryDrafts } from './queryDrafts.js'\nimport { beginTransaction } from './transactions/beginTransaction.js'\nimport { commitTransaction } from './transactions/commitTransaction.js'\nimport { rollbackTransaction } from './transactions/rollbackTransaction.js'\nimport { updateGlobal } from './updateGlobal.js'\nimport { updateGlobalVersion } from './updateGlobalVersion.js'\nimport { updateJobs } from './updateJobs.js'\nimport { updateMany } from './updateMany.js'\nimport { updateOne } from './updateOne.js'\nimport { updateVersion } from './updateVersion.js'\nimport { upsert } from './upsert.js'\n\nexport type { MigrateDownArgs, MigrateUpArgs } from './types.js'\n\nexport interface Args {\n /**\n * By default, Payload strips all additional keys from MongoDB data that don't exist\n * in the Payload schema. If you have some data that you want to include to the result\n * but it doesn't exist in Payload, you can enable this flag\n * @default false\n */\n allowAdditionalKeys?: boolean\n /**\n * Enable this flag if you want to thread your own ID to create operation data, for example:\n * ```ts\n * import { Types } from 'mongoose'\n *\n * const id = new Types.ObjectId().toHexString()\n * const doc = await payload.create({ collection: 'posts', data: {id, title: \"my title\"}})\n * assertEq(doc.id, id)\n * ```\n */\n allowIDOnCreate?: boolean\n /** Set to false to disable auto-pluralization of collection names, Defaults to true */\n autoPluralization?: boolean\n\n /**\n * If enabled, collation allows for language-specific rules for string comparison.\n * This configuration can include the following options:\n *\n * - `strength` (number): Comparison level (1: Primary, 2: Secondary, 3: Tertiary (default), 4: Quaternary, 5: Identical)\n * - `caseLevel` (boolean): Include case comparison at strength level 1 or 2.\n * - `caseFirst` (string): Sort order of case differences during tertiary level comparisons (\"upper\", \"lower\", \"off\").\n * - `numericOrdering` (boolean): Compare numeric strings as numbers.\n * - `alternate` (string): Consider whitespace and punctuation as base characters (\"non-ignorable\", \"shifted\").\n * - `maxVariable` (string): Characters considered ignorable when `alternate` is \"shifted\" (\"punct\", \"space\").\n * - `backwards` (boolean): Sort strings with diacritics from back of the string.\n * - `normalization` (boolean): Check if text requires normalization and perform normalization.\n *\n * Available on MongoDB version 3.4 and up.\n * The locale that gets passed is your current project's locale but defaults to \"en\".\n *\n * Example:\n * {\n * strength: 3\n * }\n *\n * Defaults to disabled.\n */\n collation?: Omit<CollationOptions, 'locale'>\n\n collectionsSchemaOptions?: Partial<Record<CollectionSlug, SchemaOptions>>\n /** Extra configuration options */\n connectOptions?: {\n /**\n * Set false to disable $facet aggregation in non-supporting databases, Defaults to true\n * @deprecated Payload doesn't use `$facet` anymore anywhere.\n */\n useFacet?: boolean\n } & ConnectOptions\n /**\n * We add a secondary sort based on `createdAt` to ensure that results are always returned in the same order when sorting by a non-unique field.\n * This is because MongoDB does not guarantee the order of results, however in very large datasets this could affect performance.\n *\n * Set to `true` to disable this behaviour.\n */\n disableFallbackSort?: boolean\n /** Set to true to disable hinting to MongoDB to use 'id' as index. This is currently done when counting documents for pagination. Disabling this optimization might fix some problems with AWS DocumentDB. Defaults to false */\n disableIndexHints?: boolean\n /**\n * Set to `true` to ensure that indexes are ready before completing connection.\n * NOTE: not recommended for production. This can slow down the initialization of Payload.\n */\n ensureIndexes?: boolean\n migrationDir?: string\n /**\n * typed as any to avoid dependency\n */\n mongoMemoryServer?: MongoMemoryReplSet\n prodMigrations?: Migration[]\n\n transactionOptions?: false | TransactionOptions\n\n /** The URL to connect to MongoDB or false to start payload and prevent connecting */\n url: false | string\n}\n\nexport type MongooseAdapter = {\n collections: {\n [slug: string]: CollectionModel\n }\n connection: Connection\n ensureIndexes: boolean\n globals: GlobalModel\n mongoMemoryServer: MongoMemoryReplSet\n prodMigrations?: {\n down: (args: MigrateDownArgs) => Promise<void>\n name: string\n up: (args: MigrateUpArgs) => Promise<void>\n }[]\n sessions: Record<number | string, ClientSession>\n versions: {\n [slug: string]: CollectionModel\n }\n} & Args &\n BaseDatabaseAdapter\n\ndeclare module 'payload' {\n export interface DatabaseAdapter\n extends Omit<BaseDatabaseAdapter, 'sessions'>,\n Omit<Args, 'migrationDir'> {\n collections: {\n [slug: string]: CollectionModel\n }\n connection: Connection\n ensureIndexes: boolean\n globals: GlobalModel\n mongoMemoryServer: MongoMemoryReplSet\n prodMigrations?: {\n down: (args: MigrateDownArgs) => Promise<void>\n name: string\n up: (args: MigrateUpArgs) => Promise<void>\n }[]\n sessions: Record<number | string, ClientSession>\n transactionOptions: TransactionOptions\n updateGlobal: <T extends Record<string, unknown>>(\n args: { options?: QueryOptions } & UpdateGlobalArgs<T>,\n ) => Promise<T>\n updateGlobalVersion: <T extends TypeWithID = TypeWithID>(\n args: { options?: QueryOptions } & UpdateGlobalVersionArgs<T>,\n ) => Promise<TypeWithVersion<T>>\n\n updateOne: (args: { options?: QueryOptions } & UpdateOneArgs) => Promise<Document>\n updateVersion: <T extends TypeWithID = TypeWithID>(\n args: { options?: QueryOptions } & UpdateVersionArgs<T>,\n ) => Promise<TypeWithVersion<T>>\n versions: {\n [slug: string]: CollectionModel\n }\n }\n}\n\nexport function mongooseAdapter({\n allowAdditionalKeys = false,\n allowIDOnCreate = false,\n autoPluralization = true,\n collectionsSchemaOptions = {},\n connectOptions,\n disableFallbackSort = false,\n disableIndexHints = false,\n ensureIndexes = false,\n migrationDir: migrationDirArg,\n mongoMemoryServer,\n prodMigrations,\n transactionOptions = {},\n url,\n}: Args): DatabaseAdapterObj {\n function adapter({ payload }: { payload: Payload }) {\n const migrationDir = findMigrationDir(migrationDirArg)\n mongoose.set('strictQuery', false)\n\n return createDatabaseAdapter<MongooseAdapter>({\n name: 'mongoose',\n\n // Mongoose-specific\n autoPluralization,\n collections: {},\n // @ts-expect-error initialize without a connection\n connection: undefined,\n connectOptions: connectOptions || {},\n disableIndexHints,\n ensureIndexes,\n // @ts-expect-error don't have globals model yet\n globals: undefined,\n // @ts-expect-error Should not be required\n mongoMemoryServer,\n sessions: {},\n transactionOptions: transactionOptions === false ? undefined : transactionOptions,\n updateJobs,\n updateMany,\n url,\n versions: {},\n // DatabaseAdapter\n allowAdditionalKeys,\n allowIDOnCreate,\n beginTransaction: transactionOptions === false ? defaultBeginTransaction() : beginTransaction,\n collectionsSchemaOptions,\n commitTransaction,\n connect,\n count,\n countGlobalVersions,\n countVersions,\n create,\n createGlobal,\n createGlobalVersion,\n createMigration,\n createVersion,\n defaultIDType: 'text',\n deleteMany,\n deleteOne,\n deleteVersions,\n destroy,\n disableFallbackSort,\n find,\n findGlobal,\n findGlobalVersions,\n findOne,\n findVersions,\n init,\n migrateFresh,\n migrationDir,\n packageName: '@payloadcms/db-mongodb',\n payload,\n prodMigrations,\n queryDrafts,\n rollbackTransaction,\n updateGlobal,\n updateGlobalVersion,\n updateOne,\n updateVersion,\n upsert,\n })\n }\n\n return {\n name: 'mongoose',\n allowIDOnCreate,\n defaultIDType: 'text',\n init: adapter,\n }\n}\n\n/**\n * Attempt to find migrations directory.\n *\n * Checks for the following directories in order:\n * - `migrationDir` argument from Payload config\n * - `src/migrations`\n * - `dist/migrations`\n * - `migrations`\n *\n * Defaults to `src/migrations`\n *\n * @param migrationDir\n * @returns\n */\nfunction findMigrationDir(migrationDir?: string): string {\n const cwd = process.cwd()\n const srcDir = path.resolve(cwd, 'src/migrations')\n const distDir = path.resolve(cwd, 'dist/migrations')\n const relativeMigrations = path.resolve(cwd, 'migrations')\n\n // Use arg if provided\n if (migrationDir) {\n return migrationDir\n }\n\n // Check other common locations\n if (fs.existsSync(srcDir)) {\n return srcDir\n }\n\n if (fs.existsSync(distDir)) {\n return distDir\n }\n\n if (fs.existsSync(relativeMigrations)) {\n return relativeMigrations\n }\n\n return srcDir\n}\n"],"names":["fs","mongoose","path","createDatabaseAdapter","defaultBeginTransaction","connect","count","countGlobalVersions","countVersions","create","createGlobal","createGlobalVersion","createMigration","createVersion","deleteMany","deleteOne","deleteVersions","destroy","find","findGlobal","findGlobalVersions","findOne","findVersions","init","migrateFresh","queryDrafts","beginTransaction","commitTransaction","rollbackTransaction","updateGlobal","updateGlobalVersion","updateJobs","updateMany","updateOne","updateVersion","upsert","mongooseAdapter","allowAdditionalKeys","allowIDOnCreate","autoPluralization","collectionsSchemaOptions","connectOptions","disableFallbackSort","disableIndexHints","ensureIndexes","migrationDir","migrationDirArg","mongoMemoryServer","prodMigrations","transactionOptions","url","adapter","payload","findMigrationDir","set","name","collections","connection","undefined","globals","sessions","versions","defaultIDType","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AK;IACjC,MAAMI,UAAUlE,KAAKiE,OAAO,CAACH,KAAK;IAClC,MAAMK,qBAAqBnE,KAAKiE,OAAO,CAACH,KAAK;IAE7C,sBAAsB;IACtB,IAAInB,cAAc;QAChB,OAAOA;IACT;IAEA,+BAA+B;IAC/B,IAAI7C,GAAGsE,UAAU,CAACJ,SAAS;QACzB,OAAOA;IACT;IAEA,IAAIlE,GAAGsE,UAAU,CAACF,UAAU;QAC1B,OAAOA;IACT;IAEA,IAAIpE,GAAGsE,UAAU,CAACD,qBAAqB;QACrC,OAAOA;IACT;IAEA,OAAOH;AACT"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"buildSortParam.d.ts","sourceRoot":"","sources":["../../src/queries/buildSortParam.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAE7C,OAAO,EAEL,KAAK,cAAc,EAEnB,KAAK,eAAe,EACpB,KAAK,IAAI,EACV,MAAM,SAAS,CAAA;AAEhB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAKlD,KAAK,IAAI,GAAG;IACV,OAAO,EAAE,eAAe,CAAA;IACxB,MAAM,EAAE,eAAe,CAAA;IACvB,MAAM,EAAE,cAAc,EAAE,CAAA;IACxB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B,IAAI,EAAE,IAAI,CAAA;
|
1
|
+
{"version":3,"file":"buildSortParam.d.ts","sourceRoot":"","sources":["../../src/queries/buildSortParam.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAE7C,OAAO,EAEL,KAAK,cAAc,EAEnB,KAAK,eAAe,EACpB,KAAK,IAAI,EACV,MAAM,SAAS,CAAA;AAEhB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAKlD,KAAK,IAAI,GAAG;IACV,OAAO,EAAE,eAAe,CAAA;IACxB,MAAM,EAAE,eAAe,CAAA;IACvB,MAAM,EAAE,cAAc,EAAE,CAAA;IACxB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B,IAAI,CAAC,EAAE,IAAI,CAAA;IACX,eAAe,CAAC,EAAE,aAAa,EAAE,CAAA;IACjC,UAAU,EAAE,OAAO,CAAA;IACnB,QAAQ,CAAC,EAAE,OAAO,CAAA;CACnB,CAAA;AAED,MAAM,MAAM,QAAQ,GAAG;IACrB,SAAS,EAAE,aAAa,CAAA;IACxB,QAAQ,EAAE,MAAM,CAAA;CACjB,EAAE,CAAA;AAEH,MAAM,MAAM,aAAa,GAAG,KAAK,GAAG,MAAM,CAAA;AAiG1C,eAAO,MAAM,cAAc,yGAUxB,IAAI,KAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAgF9B,CAAA"}
|
@@ -77,13 +77,22 @@ export const buildSortParam = ({ adapter, config, fields, locale, parentIsLocali
|
|
77
77
|
sort
|
78
78
|
];
|
79
79
|
}
|
80
|
+
// We use this flag to determine if the sort is unique or not to decide whether to add a fallback sort.
|
81
|
+
const isUniqueSort = sort.some((item)=>{
|
82
|
+
const field = getFieldByPath({
|
83
|
+
fields,
|
84
|
+
path: item
|
85
|
+
});
|
86
|
+
return field?.field?.unique;
|
87
|
+
});
|
80
88
|
// In the case of Mongo, when sorting by a field that is not unique, the results are not guaranteed to be in the same order each time.
|
81
89
|
// So we add a fallback sort to ensure that the results are always in the same order.
|
82
90
|
let fallbackSort = '-id';
|
83
91
|
if (timestamps) {
|
84
92
|
fallbackSort = '-createdAt';
|
85
93
|
}
|
86
|
-
|
94
|
+
const includeFallbackSort = !adapter.disableFallbackSort && !isUniqueSort && !(sort.includes(fallbackSort) || sort.includes(fallbackSort.replace('-', '')));
|
95
|
+
if (includeFallbackSort) {
|
87
96
|
sort.push(fallbackSort);
|
88
97
|
}
|
89
98
|
const sorting = sort.reduce((acc, item)=>{
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../src/queries/buildSortParam.ts"],"sourcesContent":["import type { PipelineStage } from 'mongoose'\n\nimport {\n APIError,\n type FlattenedField,\n getFieldByPath,\n type SanitizedConfig,\n type Sort,\n} from 'payload'\n\nimport type { MongooseAdapter } from '../index.js'\n\nimport { getCollection } from '../utilities/getEntity.js'\nimport { getLocalizedSortProperty } from './getLocalizedSortProperty.js'\n\ntype Args = {\n adapter: MongooseAdapter\n config: SanitizedConfig\n fields: FlattenedField[]\n locale?: string\n parentIsLocalized?: boolean\n sort
|
1
|
+
{"version":3,"sources":["../../src/queries/buildSortParam.ts"],"sourcesContent":["import type { PipelineStage } from 'mongoose'\n\nimport {\n APIError,\n type FlattenedField,\n getFieldByPath,\n type SanitizedConfig,\n type Sort,\n} from 'payload'\n\nimport type { MongooseAdapter } from '../index.js'\n\nimport { getCollection } from '../utilities/getEntity.js'\nimport { getLocalizedSortProperty } from './getLocalizedSortProperty.js'\n\ntype Args = {\n adapter: MongooseAdapter\n config: SanitizedConfig\n fields: FlattenedField[]\n locale?: string\n parentIsLocalized?: boolean\n sort?: Sort\n sortAggregation?: PipelineStage[]\n timestamps: boolean\n versions?: boolean\n}\n\nexport type SortArgs = {\n direction: SortDirection\n property: string\n}[]\n\nexport type SortDirection = 'asc' | 'desc'\n\nconst relationshipSort = ({\n adapter,\n fields,\n locale,\n path,\n sort,\n sortAggregation,\n sortDirection,\n versions,\n}: {\n adapter: MongooseAdapter\n fields: FlattenedField[]\n locale?: string\n path: string\n sort: Record<string, string>\n sortAggregation: PipelineStage[]\n sortDirection: SortDirection\n versions?: boolean\n}) => {\n let currentFields = fields\n const segments = path.split('.')\n if (segments.length < 2) {\n return false\n }\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i]\n const field = currentFields.find((each) => each.name === segment)\n\n if (!field) {\n return false\n }\n\n if ('fields' in field) {\n currentFields = field.flattenedFields\n if (field.name === 'version' && versions && i === 0) {\n segments.shift()\n i--\n }\n } else if (\n (field.type === 'relationship' || field.type === 'upload') &&\n i !== segments.length - 1\n ) {\n const relationshipPath = segments.slice(0, i + 1).join('.')\n let sortFieldPath = segments.slice(i + 1, segments.length).join('.')\n if (Array.isArray(field.relationTo)) {\n throw new APIError('Not supported')\n }\n\n const foreignCollection = getCollection({ adapter, collectionSlug: field.relationTo })\n\n const foreignFieldPath = getFieldByPath({\n fields: foreignCollection.collectionConfig.flattenedFields,\n path: sortFieldPath,\n })\n\n if (!foreignFieldPath) {\n return false\n }\n\n if (foreignFieldPath.pathHasLocalized && locale) {\n sortFieldPath = foreignFieldPath.localizedPath.replace('<locale>', locale)\n }\n\n if (\n !sortAggregation.some((each) => {\n return '$lookup' in each && each.$lookup.as === `__${path}`\n })\n ) {\n sortAggregation.push({\n $lookup: {\n as: `__${path}`,\n foreignField: '_id',\n from: foreignCollection.Model.collection.name,\n localField: versions ? `version.${relationshipPath}` : relationshipPath,\n pipeline: [\n {\n $project: {\n [sortFieldPath]: true,\n },\n },\n ],\n },\n })\n\n sort[`__${path}.${sortFieldPath}`] = sortDirection\n\n return true\n }\n }\n }\n\n return false\n}\n\nexport const buildSortParam = ({\n adapter,\n config,\n fields,\n locale,\n parentIsLocalized = false,\n sort,\n sortAggregation,\n timestamps,\n versions,\n}: Args): Record<string, string> => {\n if (!sort) {\n if (timestamps) {\n sort = '-createdAt'\n } else {\n sort = '-id'\n }\n }\n\n if (typeof sort === 'string') {\n sort = [sort]\n }\n\n // We use this flag to determine if the sort is unique or not to decide whether to add a fallback sort.\n const isUniqueSort = sort.some((item) => {\n const field = getFieldByPath({ fields, path: item })\n return field?.field?.unique\n })\n\n // In the case of Mongo, when sorting by a field that is not unique, the results are not guaranteed to be in the same order each time.\n // So we add a fallback sort to ensure that the results are always in the same order.\n let fallbackSort = '-id'\n\n if (timestamps) {\n fallbackSort = '-createdAt'\n }\n\n const includeFallbackSort =\n !adapter.disableFallbackSort &&\n !isUniqueSort &&\n !(sort.includes(fallbackSort) || sort.includes(fallbackSort.replace('-', '')))\n\n if (includeFallbackSort) {\n sort.push(fallbackSort)\n }\n\n const sorting = sort.reduce<Record<string, string>>((acc, item) => {\n let sortProperty: string\n let sortDirection: SortDirection\n if (item.indexOf('-') === 0) {\n sortProperty = item.substring(1)\n sortDirection = 'desc'\n } else {\n sortProperty = item\n sortDirection = 'asc'\n }\n if (sortProperty === 'id') {\n acc['_id'] = sortDirection\n return acc\n }\n\n if (\n sortAggregation &&\n relationshipSort({\n adapter,\n fields,\n locale,\n path: sortProperty,\n sort: acc,\n sortAggregation,\n sortDirection,\n versions,\n })\n ) {\n return acc\n }\n\n const localizedProperty = getLocalizedSortProperty({\n config,\n fields,\n locale,\n parentIsLocalized,\n segments: sortProperty.split('.'),\n })\n acc[localizedProperty] = sortDirection\n\n return acc\n }, {})\n\n return sorting\n}\n"],"names":["APIError","getFieldByPath","getCollection","getLocalizedSortProperty","relationshipSort","adapter","fields","locale","path","sort","sortAggregation","sortDirection","versions","currentFields","segments","split","length","i","segment","field","find","each","name","flattenedFields","shift","type","relationshipPath","slice","join","sortFieldPath","Array","isArray","relationTo","foreignCollection","collectionSlug","foreignFieldPath","collectionConfig","pathHasLocalized","localizedPath","replace","some","$lookup","as","push","foreignField","from","Model","collection","localField","pipeline","$project","buildSortParam","config","parentIsLocalized","timestamps","isUniqueSort","item","unique","fallbackSort","includeFallbackSort","disableFallbackSort","includes","sorting","reduce","acc","sortProperty","indexOf","substring","localizedProperty"],"mappings":"AAEA,SACEA,QAAQ,EAERC,cAAc,QAGT,UAAS;AAIhB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,wBAAwB,QAAQ,gCAA+B;AAqBxE,MAAMC,mBAAmB,CAAC,EACxBC,OAAO,EACPC,MAAM,EACNC,MAAM,EACNC,IAAI,EACJC,IAAI,EACJC,eAAe,EACfC,aAAa,EACbC,QAAQ,EAUT;IACC,IAAIC,gBAAgBP;IACpB,MAAMQ,WAAWN,KAAKO,KAAK,C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B;QACvBlD,KAAKkC,IAAI,CAACe;IACZ;IAEA,MAAMI,UAAUrD,KAAKsD,MAAM,CAAyB,CAACC,KAAKR;QACxD,IAAIS;QACJ,IAAItD;QACJ,IAAI6C,KAAKU,OAAO,CAAC,SAAS,GAAG;YAC3BD,eAAeT,KAAKW,SAAS,CAAC;YAC9BxD,gBAAgB;QAClB,OAAO;YACLsD,eAAeT;YACf7C,gBAAgB;QAClB;QACA,IAAIsD,iBAAiB,MAAM;YACzBD,GAAG,CAAC,MAAM,GAAGrD;YACb,OAAOqD;QACT;QAEA,IACEtD,mBACAN,iBAAiB;YACfC;YACAC;YACAC;YACAC,MAAMyD;YACNxD,MAAMuD;YACNtD;YACAC;YACAC;QACF,IACA;YACA,OAAOoD;QACT;QAEA,MAAMI,oBAAoBjE,yBAAyB;YACjDiD;YACA9C;YACAC;YACA8C;YACAvC,UAAUmD,aAAalD,KAAK,CAAC;QAC/B;QACAiD,GAAG,CAACI,kBAAkB,GAAGzD;QAEzB,OAAOqD;IACT,GAAG,CAAC;IAEJ,OAAOF;AACT,EAAC"}
|
@@ -0,0 +1,122 @@
|
|
1
|
+
import { sanitizeConfig } from 'payload';
|
2
|
+
import { buildSortParam } from './buildSortParam.js';
|
3
|
+
let config;
|
4
|
+
describe('builds sort params', ()=>{
|
5
|
+
beforeAll(async ()=>{
|
6
|
+
config = await sanitizeConfig({
|
7
|
+
localization: {
|
8
|
+
defaultLocale: 'en',
|
9
|
+
fallback: true,
|
10
|
+
locales: [
|
11
|
+
'en',
|
12
|
+
'es'
|
13
|
+
]
|
14
|
+
}
|
15
|
+
});
|
16
|
+
});
|
17
|
+
it('adds a fallback on non-unique field', ()=>{
|
18
|
+
const result = buildSortParam({
|
19
|
+
config,
|
20
|
+
parentIsLocalized: false,
|
21
|
+
fields: [
|
22
|
+
{
|
23
|
+
name: 'title',
|
24
|
+
type: 'text'
|
25
|
+
},
|
26
|
+
{
|
27
|
+
name: 'order',
|
28
|
+
type: 'number'
|
29
|
+
}
|
30
|
+
],
|
31
|
+
locale: 'en',
|
32
|
+
sort: 'order',
|
33
|
+
timestamps: true,
|
34
|
+
adapter: {
|
35
|
+
disableFallbackSort: false
|
36
|
+
}
|
37
|
+
});
|
38
|
+
expect(result).toStrictEqual({
|
39
|
+
order: 'asc',
|
40
|
+
createdAt: 'desc'
|
41
|
+
});
|
42
|
+
});
|
43
|
+
it('adds a fallback when sort isnt provided', ()=>{
|
44
|
+
const result = buildSortParam({
|
45
|
+
config,
|
46
|
+
parentIsLocalized: false,
|
47
|
+
fields: [
|
48
|
+
{
|
49
|
+
name: 'title',
|
50
|
+
type: 'text'
|
51
|
+
},
|
52
|
+
{
|
53
|
+
name: 'order',
|
54
|
+
type: 'number'
|
55
|
+
}
|
56
|
+
],
|
57
|
+
locale: 'en',
|
58
|
+
sort: undefined,
|
59
|
+
timestamps: true,
|
60
|
+
adapter: {
|
61
|
+
disableFallbackSort: false
|
62
|
+
}
|
63
|
+
});
|
64
|
+
expect(result).toStrictEqual({
|
65
|
+
createdAt: 'desc'
|
66
|
+
});
|
67
|
+
});
|
68
|
+
it('does not add a fallback on non-unique field when disableFallbackSort is true', ()=>{
|
69
|
+
const result = buildSortParam({
|
70
|
+
config,
|
71
|
+
parentIsLocalized: false,
|
72
|
+
fields: [
|
73
|
+
{
|
74
|
+
name: 'title',
|
75
|
+
type: 'text'
|
76
|
+
},
|
77
|
+
{
|
78
|
+
name: 'order',
|
79
|
+
type: 'number'
|
80
|
+
}
|
81
|
+
],
|
82
|
+
locale: 'en',
|
83
|
+
sort: 'order',
|
84
|
+
timestamps: true,
|
85
|
+
adapter: {
|
86
|
+
disableFallbackSort: true
|
87
|
+
}
|
88
|
+
});
|
89
|
+
expect(result).toStrictEqual({
|
90
|
+
order: 'asc'
|
91
|
+
});
|
92
|
+
});
|
93
|
+
// This test should be true even when disableFallbackSort is false
|
94
|
+
it('does not add a fallback on unique field', ()=>{
|
95
|
+
const result = buildSortParam({
|
96
|
+
config,
|
97
|
+
parentIsLocalized: false,
|
98
|
+
fields: [
|
99
|
+
{
|
100
|
+
name: 'title',
|
101
|
+
type: 'text'
|
102
|
+
},
|
103
|
+
{
|
104
|
+
name: 'order',
|
105
|
+
type: 'number',
|
106
|
+
unique: true
|
107
|
+
}
|
108
|
+
],
|
109
|
+
locale: 'en',
|
110
|
+
sort: 'order',
|
111
|
+
timestamps: true,
|
112
|
+
adapter: {
|
113
|
+
disableFallbackSort: false
|
114
|
+
}
|
115
|
+
});
|
116
|
+
expect(result).toStrictEqual({
|
117
|
+
order: 'asc'
|
118
|
+
});
|
119
|
+
});
|
120
|
+
});
|
121
|
+
|
122
|
+
//# sourceMappingURL=buildSortParam.spec.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"sources":["../../src/queries/buildSortParam.spec.ts"],"sourcesContent":["import type { Config, SanitizedConfig } from 'payload'\n\nimport { sanitizeConfig } from 'payload'\n\nimport { buildSortParam } from './buildSortParam.js'\nimport { MongooseAdapter } from '../index.js'\n\nlet config: SanitizedConfig\n\ndescribe('builds sort params', () => {\n beforeAll(async () => {\n config = await sanitizeConfig({\n localization: {\n defaultLocale: 'en',\n fallback: true,\n locales: ['en', 'es'],\n },\n } as Config)\n })\n it('adds a fallback on non-unique field', () => {\n const result = buildSortParam({\n config,\n parentIsLocalized: false,\n fields: [\n {\n name: 'title',\n type: 'text',\n },\n {\n name: 'order',\n type: 'number',\n },\n ],\n locale: 'en',\n sort: 'order',\n timestamps: true,\n adapter: {\n disableFallbackSort: false,\n } as MongooseAdapter,\n })\n\n expect(result).toStrictEqual({ order: 'asc', createdAt: 'desc' })\n })\n\n it('adds a fallback when sort isnt provided', () => {\n const result = buildSortParam({\n config,\n parentIsLocalized: false,\n fields: [\n {\n name: 'title',\n type: 'text',\n },\n {\n name: 'order',\n type: 'number',\n },\n ],\n locale: 'en',\n sort: undefined,\n timestamps: true,\n adapter: {\n disableFallbackSort: false,\n } as MongooseAdapter,\n })\n\n expect(result).toStrictEqual({ createdAt: 'desc' })\n })\n\n it('does not add a fallback on non-unique field when disableFallbackSort is true', () => {\n const result = buildSortParam({\n config,\n parentIsLocalized: false,\n fields: [\n {\n name: 'title',\n type: 'text',\n },\n {\n name: 'order',\n type: 'number',\n },\n ],\n locale: 'en',\n sort: 'order',\n timestamps: true,\n adapter: {\n disableFallbackSort: true,\n } as MongooseAdapter,\n })\n\n expect(result).toStrictEqual({ order: 'asc' })\n })\n\n // This test should be true even when disableFallbackSort is false\n it('does not add a fallback on unique field', () => {\n const result = buildSortParam({\n config,\n parentIsLocalized: false,\n fields: [\n {\n name: 'title',\n type: 'text',\n },\n {\n name: 'order',\n type: 'number',\n unique: true, // Marking this field as unique\n },\n ],\n locale: 'en',\n sort: 'order',\n timestamps: true,\n adapter: {\n disableFallbackSort: false,\n } as MongooseAdapter,\n })\n\n expect(result).toStrictEqual({ order: 'asc' })\n })\n})\n"],"names":["sanitizeConfig","buildSortParam","config","describe","beforeAll","localization","defaultLocale","fallback","locales","it","result","parentIsLocalized","fields","name","type","locale","sort","timestamps","adapter","disableFallbackSort","expect","toStrictEqual","order","createdAt","undefined","unique"],"mappings":"AAEA,SAASA,cAAc,QAAQ,UAAS;AAExC,SAASC,cAAc,QAAQ,sBAAqB;AAGpD,IAAIC;AAEJC,SAAS,sBAAsB;IAC7BC,UAAU;QACRF,SAAS,MAAMF,eAAe;YAC5BK,cAAc;gBACZC,eAAe;gBACfC,UAAU;gBACVC,SAAS;oBAAC;oBAAM;iBAAK;YACvB;QACF;IACF;IACAC,GAAG,uCAAuC;QACxC,MAAMC,SAAST,eAAe;YAC5BC;YACAS,mBAAmB;YACnBC,QAAQ;gBACN;oBACEC,MAAM;oBACNC,MAAM;gBACR;gBACA;oBACED,MAAM;oBACNC,MAAM;gBACR;aACD;YACDC,QAAQ;YACRC,MAAM;YACNC,YAAY;YACZC,SAAS;gBACPC,qBAAqB;YACvB;QACF;QAEAC,OAAOV,QAAQW,aAAa,CAAC;YAAEC,OAAO;YAAOC,WAAW;QAAO;IACjE;IAEAd,GAAG,2CAA2C;QAC5C,MAAMC,SAAST,eAAe;YAC5BC;YACAS,mBAAmB;YACnBC,QAAQ;gBACN;oBACEC,MAAM;oBACNC,MAAM;gBACR;gBACA;oBACED,MAAM;oBACNC,MAAM;gBACR;aACD;YACDC,QAAQ;YACRC,MAAMQ;YACNP,YAAY;YACZC,SAAS;gBACPC,qBAAqB;YACvB;QACF;QAEAC,OAAOV,QAAQW,aAAa,CAAC;YAAEE,WAAW;QAAO;IACnD;IAEAd,GAAG,gFAAgF;QACjF,MAAMC,SAAST,eAAe;YAC5BC;YACAS,mBAAmB;YACnBC,QAAQ;gBACN;oBACEC,MAAM;oBACNC,MAAM;gBACR;gBACA;oBACED,MAAM;oBACNC,MAAM;gBACR;aACD;YACDC,QAAQ;YACRC,MAAM;YACNC,YAAY;YACZC,SAAS;gBACPC,qBAAqB;YACvB;QACF;QAEAC,OAAOV,QAAQW,aAAa,CAAC;YAAEC,OAAO;QAAM;IAC9C;IAEA,kEAAkE;IAClEb,GAAG,2CAA2C;QAC5C,MAAMC,SAAST,eAAe;YAC5BC;YACAS,mBAAmB;YACnBC,QAAQ;gBACN;oBACEC,MAAM;oBACNC,MAAM;gBACR;gBACA;oBACED,MAAM;oBACNC,MAAM;oBACNW,QAAQ;gBACV;aACD;YACDV,QAAQ;YACRC,MAAM;YACNC,YAAY;YACZC,SAAS;gBACPC,qBAAqB;YACvB;QACF;QAEAC,OAAOV,QAAQW,aAAa,CAAC;YAAEC,OAAO;QAAM;IAC9C;AACF"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"transform.d.ts","sourceRoot":"","sources":["../../src/utilities/transform.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAGV,KAAK,EAQN,MAAM,SAAS,CAAA;AAMhB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAgMlD,KAAK,IAAI,GAAG;IACV,8BAA8B;IAC9B,OAAO,EAAE,eAAe,CAAA;IACxB,2EAA2E;IAC3E,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAA;IACzD,uCAAuC;IACvC,MAAM,EAAE,KAAK,EAAE,CAAA;IACf,kEAAkE;IAClE,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB;;;;OAIG;IACH,SAAS,EAAE,MAAM,GAAG,OAAO,CAAA;IAC3B,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B;;;OAGG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAA;CAChC,CAAA;
|
1
|
+
{"version":3,"file":"transform.d.ts","sourceRoot":"","sources":["../../src/utilities/transform.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAGV,KAAK,EAQN,MAAM,SAAS,CAAA;AAMhB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAgMlD,KAAK,IAAI,GAAG;IACV,8BAA8B;IAC9B,OAAO,EAAE,eAAe,CAAA;IACxB,2EAA2E;IAC3E,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAA;IACzD,uCAAuC;IACvC,MAAM,EAAE,KAAK,EAAE,CAAA;IACf,kEAAkE;IAClE,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB;;;;OAIG;IACH,SAAS,EAAE,MAAM,GAAG,OAAO,CAAA;IAC3B,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B;;;OAGG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAA;CAChC,CAAA;AAuKD,eAAO,MAAM,SAAS,gGAQnB,IAAI,SAwHN,CAAA"}
|
@@ -145,16 +145,25 @@ const stripFields = ({ config, data, fields, reservedKeys = [] })=>{
|
|
145
145
|
if (!Array.isArray(localeData)) {
|
146
146
|
continue;
|
147
147
|
}
|
148
|
-
|
148
|
+
let hasNull = false;
|
149
|
+
for(let i = 0; i < localeData.length; i++){
|
150
|
+
const data = localeData[i];
|
149
151
|
let fields = null;
|
150
152
|
if (field.type === 'array') {
|
151
153
|
fields = field.flattenedFields;
|
152
154
|
} else {
|
153
155
|
let maybeBlock = undefined;
|
154
156
|
if (field.blockReferences) {
|
155
|
-
const maybeBlockReference = field.blockReferences.find((each)=>
|
156
|
-
|
157
|
-
|
157
|
+
const maybeBlockReference = field.blockReferences.find((each)=>{
|
158
|
+
const slug = typeof each === 'string' ? each : each.slug;
|
159
|
+
return slug === data.blockType;
|
160
|
+
});
|
161
|
+
if (maybeBlockReference) {
|
162
|
+
if (typeof maybeBlockReference === 'object') {
|
163
|
+
maybeBlock = maybeBlockReference;
|
164
|
+
} else {
|
165
|
+
maybeBlock = config.blocks?.find((each)=>each.slug === maybeBlockReference);
|
166
|
+
}
|
158
167
|
}
|
159
168
|
}
|
160
169
|
if (!maybeBlock) {
|
@@ -162,6 +171,9 @@ const stripFields = ({ config, data, fields, reservedKeys = [] })=>{
|
|
162
171
|
}
|
163
172
|
if (maybeBlock) {
|
164
173
|
fields = maybeBlock.flattenedFields;
|
174
|
+
} else {
|
175
|
+
localeData[i] = null;
|
176
|
+
hasNull = true;
|
165
177
|
}
|
166
178
|
}
|
167
179
|
if (!fields) {
|
@@ -174,6 +186,9 @@ const stripFields = ({ config, data, fields, reservedKeys = [] })=>{
|
|
174
186
|
reservedKeys
|
175
187
|
});
|
176
188
|
}
|
189
|
+
if (hasNull) {
|
190
|
+
fieldData[localeKey] = localeData.filter(Boolean);
|
191
|
+
}
|
177
192
|
continue;
|
178
193
|
} else {
|
179
194
|
stripFields({
|
@@ -190,16 +205,25 @@ const stripFields = ({ config, data, fields, reservedKeys = [] })=>{
|
|
190
205
|
if (!Array.isArray(fieldData)) {
|
191
206
|
continue;
|
192
207
|
}
|
193
|
-
|
208
|
+
let hasNull = false;
|
209
|
+
for(let i = 0; i < fieldData.length; i++){
|
210
|
+
const data = fieldData[i];
|
194
211
|
let fields = null;
|
195
212
|
if (field.type === 'array') {
|
196
213
|
fields = field.flattenedFields;
|
197
214
|
} else {
|
198
215
|
let maybeBlock = undefined;
|
199
216
|
if (field.blockReferences) {
|
200
|
-
const maybeBlockReference = field.blockReferences.find((each)=>
|
201
|
-
|
202
|
-
|
217
|
+
const maybeBlockReference = field.blockReferences.find((each)=>{
|
218
|
+
const slug = typeof each === 'string' ? each : each.slug;
|
219
|
+
return slug === data.blockType;
|
220
|
+
});
|
221
|
+
if (maybeBlockReference) {
|
222
|
+
if (typeof maybeBlockReference === 'object') {
|
223
|
+
maybeBlock = maybeBlockReference;
|
224
|
+
} else {
|
225
|
+
maybeBlock = config.blocks?.find((each)=>each.slug === maybeBlockReference);
|
226
|
+
}
|
203
227
|
}
|
204
228
|
}
|
205
229
|
if (!maybeBlock) {
|
@@ -207,6 +231,9 @@ const stripFields = ({ config, data, fields, reservedKeys = [] })=>{
|
|
207
231
|
}
|
208
232
|
if (maybeBlock) {
|
209
233
|
fields = maybeBlock.flattenedFields;
|
234
|
+
} else {
|
235
|
+
fieldData[i] = null;
|
236
|
+
hasNull = true;
|
210
237
|
}
|
211
238
|
}
|
212
239
|
if (!fields) {
|
@@ -219,6 +246,9 @@ const stripFields = ({ config, data, fields, reservedKeys = [] })=>{
|
|
219
246
|
reservedKeys
|
220
247
|
});
|
221
248
|
}
|
249
|
+
if (hasNull) {
|
250
|
+
data[field.name] = fieldData.filter(Boolean);
|
251
|
+
}
|
222
252
|
continue;
|
223
253
|
} else {
|
224
254
|
stripFields({
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/transform.ts"],"sourcesContent":["import type {\n CollectionConfig,\n DateField,\n Field,\n FlattenedBlock,\n FlattenedField,\n JoinField,\n RelationshipField,\n SanitizedConfig,\n TraverseFieldsCallback,\n UploadField,\n} from 'payload'\n\nimport { Types } from 'mongoose'\nimport { flattenAllFields, traverseFields } from 'payload'\nimport { fieldAffectsData, fieldShouldBeLocalized } from 'payload/shared'\n\nimport type { MongooseAdapter } from '../index.js'\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 convertRelationshipValue = ({\n operation,\n relatedCollection,\n validateRelationships,\n value,\n}: {\n operation: Args['operation']\n relatedCollection: CollectionConfig\n validateRelationships?: boolean\n value: unknown\n}) => {\n const customIDField = relatedCollection.fields.find(\n (field) => fieldAffectsData(field) && field.name === 'id',\n )\n\n if (operation === 'read') {\n if (value instanceof Types.ObjectId) {\n return value.toHexString()\n }\n\n return value\n }\n\n if (customIDField) {\n return value\n }\n\n if (typeof value === 'string') {\n try {\n return new Types.ObjectId(value)\n } catch (e) {\n if (validateRelationships) {\n throw e\n }\n return value\n }\n }\n\n return value\n}\n\nconst sanitizeRelationship = ({\n config,\n field,\n locale,\n operation,\n ref,\n validateRelationships,\n value,\n}: {\n config: SanitizedConfig\n field: JoinField | RelationshipField | UploadField\n locale?: string\n operation: Args['operation']\n ref: Record<string, unknown>\n validateRelationships?: boolean\n value?: unknown\n}) => {\n if (field.type === 'join') {\n if (\n operation === 'read' &&\n value &&\n typeof value === 'object' &&\n 'docs' in value &&\n Array.isArray(value.docs)\n ) {\n for (let i = 0; i < value.docs.length; i++) {\n const item = value.docs[i]\n\n if (item instanceof Types.ObjectId) {\n value.docs[i] = item.toHexString()\n } else if (Array.isArray(field.collection) && item) {\n // Fields here for polymorphic joins cannot be determinted, JSON.parse needed\n value.docs[i] = JSON.parse(JSON.stringify(value.docs[i]))\n }\n }\n }\n\n return value\n }\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 - 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: convertRelationshipValue({\n operation,\n relatedCollection: relatedCollectionForSingleValue,\n validateRelationships,\n value: val.value,\n }),\n }\n }\n }\n\n if (relatedCollection) {\n return convertRelationshipValue({\n operation,\n relatedCollection,\n validateRelationships,\n value: val,\n })\n }\n\n return val\n })\n }\n // Handle has one - polymorphic\n else if (isValidRelationObject(value)) {\n relatedCollection = config.collections?.find(({ slug }) => slug === value.relationTo)\n\n if (relatedCollection) {\n result = {\n relationTo: value.relationTo,\n value: convertRelationshipValue({\n operation,\n relatedCollection,\n validateRelationships,\n value: value.value,\n }),\n }\n }\n }\n // Handle has one\n else if (relatedCollection) {\n result = convertRelationshipValue({\n operation,\n relatedCollection,\n validateRelationships,\n value,\n })\n }\n\n if (locale) {\n ref[locale] = result\n } else {\n ref[field.name] = result\n }\n}\n\nconst sanitizeDate = ({\n field,\n locale,\n ref,\n value,\n}: {\n field: DateField\n locale?: string\n ref: Record<string, unknown>\n value: unknown\n}) => {\n if (!value) {\n return\n }\n\n if (value instanceof Date) {\n value = value.toISOString()\n }\n\n if (locale) {\n ref[locale] = value\n } else {\n ref[field.name] = value\n }\n}\n\ntype Args = {\n /** instance of the adapter */\n adapter: MongooseAdapter\n /** data to transform, can be an array of documents or a single document */\n data: Record<string, unknown> | Record<string, unknown>[]\n /** fields accossiated with the data */\n fields: Field[]\n /** slug of the global, pass only when the operation is `write` */\n globalSlug?: string\n /**\n * Type of the operation\n * read - sanitizes ObjectIDs, Date to strings.\n * write - sanitizes string relationships to ObjectIDs.\n */\n operation: 'read' | 'write'\n parentIsLocalized?: boolean\n /**\n * Throw errors on invalid relationships\n * @default true\n */\n validateRelationships?: boolean\n}\n\nconst stripFields = ({\n config,\n data,\n fields,\n reservedKeys = [],\n}: {\n config: SanitizedConfig\n data: any\n fields: FlattenedField[]\n reservedKeys?: string[]\n}) => {\n for (const k in data) {\n if (!fields.some((field) => field.name === k) && !reservedKeys.includes(k)) {\n delete data[k]\n }\n }\n\n for (const field of fields) {\n reservedKeys = []\n const fieldData = data[field.name]\n if (!fieldData || typeof fieldData !== 'object') {\n continue\n }\n\n if (field.type === 'blocks') {\n reservedKeys.push('blockType')\n }\n\n if ('flattenedFields' in field || 'blocks' in field) {\n if (field.localized && config.localization) {\n for (const localeKey in fieldData) {\n if (!config.localization.localeCodes.some((code) => code === localeKey)) {\n delete fieldData[localeKey]\n continue\n }\n\n const localeData = fieldData[localeKey]\n\n if (!localeData || typeof localeData !== 'object') {\n continue\n }\n\n if (field.type === 'array' || field.type === 'blocks') {\n if (!Array.isArray(localeData)) {\n continue\n }\n\n for (const data of localeData) {\n let fields: FlattenedField[] | null = null\n\n if (field.type === 'array') {\n fields = field.flattenedFields\n } else {\n let maybeBlock: FlattenedBlock | undefined = undefined\n\n if (field.blockReferences) {\n const maybeBlockReference = field.blockReferences.find(\n (each) => typeof each === 'object' && each.slug === data.blockType,\n )\n if (maybeBlockReference && typeof maybeBlockReference === 'object') {\n maybeBlock = maybeBlockReference\n }\n }\n\n if (!maybeBlock) {\n maybeBlock = field.blocks.find((each) => each.slug === data.blockType)\n }\n\n if (maybeBlock) {\n fields = maybeBlock.flattenedFields\n }\n }\n\n if (!fields) {\n continue\n }\n\n stripFields({ config, data, fields, reservedKeys })\n }\n\n continue\n } else {\n stripFields({ config, data: localeData, fields: field.flattenedFields, reservedKeys })\n }\n }\n continue\n }\n\n if (field.type === 'array' || field.type === 'blocks') {\n if (!Array.isArray(fieldData)) {\n continue\n }\n\n for (const data of fieldData) {\n let fields: FlattenedField[] | null = null\n\n if (field.type === 'array') {\n fields = field.flattenedFields\n } else {\n let maybeBlock: FlattenedBlock | undefined = undefined\n\n if (field.blockReferences) {\n const maybeBlockReference = field.blockReferences.find(\n (each) => typeof each === 'object' && each.slug === data.blockType,\n )\n\n if (maybeBlockReference && typeof maybeBlockReference === 'object') {\n maybeBlock = maybeBlockReference\n }\n }\n\n if (!maybeBlock) {\n maybeBlock = field.blocks.find((each) => each.slug === data.blockType)\n }\n\n if (maybeBlock) {\n fields = maybeBlock.flattenedFields\n }\n }\n\n if (!fields) {\n continue\n }\n\n stripFields({ config, data, fields, reservedKeys })\n }\n\n continue\n } else {\n stripFields({ config, data: fieldData, fields: field.flattenedFields, reservedKeys })\n }\n }\n }\n}\n\nexport const transform = ({\n adapter,\n data,\n fields,\n globalSlug,\n operation,\n parentIsLocalized = false,\n validateRelationships = true,\n}: Args) => {\n if (Array.isArray(data)) {\n for (const item of data) {\n transform({ adapter, data: item, fields, globalSlug, operation, validateRelationships })\n }\n return\n }\n\n const {\n payload: { config },\n } = adapter\n\n if (operation === 'read') {\n delete data['__v']\n data.id = data._id\n delete data['_id']\n\n if (data.id instanceof Types.ObjectId) {\n data.id = data.id.toHexString()\n }\n\n if (!adapter.allowAdditionalKeys) {\n stripFields({\n config,\n data,\n fields: flattenAllFields({ cache: true, fields }),\n reservedKeys: ['id', 'globalType'],\n })\n }\n }\n\n if (operation === 'write' && globalSlug) {\n data.globalType = globalSlug\n }\n\n const sanitize: TraverseFieldsCallback = ({ field, ref: incomingRef }) => {\n if (!incomingRef || typeof incomingRef !== 'object') {\n return\n }\n\n const ref = incomingRef as Record<string, unknown>\n\n if (field.type === 'date' && operation === 'read' && field.name in ref && ref[field.name]) {\n if (config.localization && fieldShouldBeLocalized({ field, parentIsLocalized })) {\n const fieldRef = ref[field.name] as Record<string, unknown>\n if (!fieldRef || typeof fieldRef !== 'object') {\n return\n }\n\n for (const locale of config.localization.localeCodes) {\n sanitizeDate({\n field,\n locale,\n ref: fieldRef,\n value: fieldRef[locale],\n })\n }\n } else {\n sanitizeDate({\n field,\n ref,\n value: ref[field.name],\n })\n }\n }\n\n if (\n field.type === 'relationship' ||\n field.type === 'upload' ||\n (operation === 'read' && field.type === 'join')\n ) {\n if (!ref[field.name]) {\n return\n }\n\n // handle localized relationships\n if (config.localization && fieldShouldBeLocalized({ field, parentIsLocalized })) {\n const locales = config.localization.locales\n const fieldRef = ref[field.name] as Record<string, unknown>\n if (typeof fieldRef !== 'object') {\n return\n }\n\n for (const { code } of locales) {\n const value = fieldRef[code]\n if (value) {\n sanitizeRelationship({\n config,\n field,\n locale: code,\n operation,\n ref: fieldRef,\n validateRelationships,\n value,\n })\n }\n }\n } else {\n // handle non-localized relationships\n sanitizeRelationship({\n config,\n field,\n locale: undefined,\n operation,\n ref,\n validateRelationships,\n value: ref[field.name],\n })\n }\n }\n }\n\n traverseFields({\n callback: sanitize,\n config,\n fields,\n fillEmpty: false,\n parentIsLocalized,\n ref: data,\n })\n}\n"],"names":["Types","flattenAllFields","traverseFields","fieldAffectsData","fieldShouldBeLocalized","isValidRelationObject","value","convertRelationshipValue","operation","relatedCollection","validateRelationships","customIDField","fields","find","field","name","ObjectId","toHexString","e","sanitizeRelationship","config","locale","ref","type","Array","isArray","docs","i","length","item","collection","JSON","parse","stringify","result","hasManyRelations","relationTo","collections","slug","map","val","relatedCollectionForSingleValue","sanitizeDate","Date","toISOString","stripFields","data","reservedKeys","k","some","includes","fieldData","push","localized","localization","localeKey","localeCodes","code","localeData","flattenedFields","maybeBlock","undefined","blockReferences","maybeBlockReference","each","blockType","blocks","transform","adapter","globalSlug","parentIsLocalized","payload","id","_id","allowAdditionalKeys","cache","globalType","sanitize","incomingRef","fieldRef","locales","callback","fillEmpty"],"mappings":"AAaA,SAASA,KAAK,QAAQ,WAAU;AAChC,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,UAAS;AAC1D,SAASC,gBAAgB,EAAEC,sBAAsB,QAAQ,iBAAgB;AASzE,SAASC,sBAAsBC,KAAc;IAC3C,OAAO,OAAOA,UAAU,YAAYA,UAAU,QAAQ,gBAAgBA,SAAS,WAAWA;AAC5F;AAEA,MAAMC,2BAA2B,CAAC,EAChCC,SAAS,EACTC,iBAAiB,EACjBC,qBAAqB,EACrBJ,KAAK,EAMN;IACC,MAAMK,gBAAgBF,kBAAkBG,MAAM,C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,IAAIlD,uBAAuB;gBAAEU;gBAAOwD;YAAkB,IAAI;gBAC/E,MAAMU,UAAU5D,OAAOkC,YAAY,CAAC0B,OAAO;gBAC3C,MAAMD,WAAWzD,GAAG,CAACR,MAAMC,IAAI,CAAC;gBAChC,IAAI,OAAOgE,aAAa,UAAU;oBAChC;gBACF;gBAEA,KAAK,MAAM,EAAEtB,IAAI,EAAE,IAAIuB,QAAS;oBAC9B,MAAM1E,QAAQyE,QAAQ,CAACtB,KAAK;oBAC5B,IAAInD,OAAO;wBACTa,qBAAqB;4BACnBC;4BACAN;4BACAO,QAAQoC;4BACRjD;4BACAc,KAAKyD;4BACLrE;4BACAJ;wBACF;oBACF;gBACF;YACF,OAAO;gBACL,qCAAqC;gBACrCa,qBAAqB;oBACnBC;oBACAN;oBACAO,QAAQwC;oBACRrD;oBACAc;oBACAZ;oBACAJ,OAAOgB,GAAG,CAACR,MAAMC,IAAI,CAAC;gBACxB;YACF;QACF;IACF;IAEAb,eAAe;QACb+E,UAAUJ;QACVzD;QACAR;QACAsE,WAAW;QACXZ;QACAhD,KAAKwB;IACP;AACF,EAAC"}
|
1
|
+
{"version":3,"sources":["../../src/utilities/transform.ts"],"sourcesContent":["import type {\n CollectionConfig,\n DateField,\n Field,\n FlattenedBlock,\n FlattenedField,\n JoinField,\n RelationshipField,\n SanitizedConfig,\n TraverseFieldsCallback,\n UploadField,\n} from 'payload'\n\nimport { Types } from 'mongoose'\nimport { flattenAllFields, traverseFields } from 'payload'\nimport { fieldAffectsData, fieldShouldBeLocalized } from 'payload/shared'\n\nimport type { MongooseAdapter } from '../index.js'\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 convertRelationshipValue = ({\n operation,\n relatedCollection,\n validateRelationships,\n value,\n}: {\n operation: Args['operation']\n relatedCollection: CollectionConfig\n validateRelationships?: boolean\n value: unknown\n}) => {\n const customIDField = relatedCollection.fields.find(\n (field) => fieldAffectsData(field) && field.name === 'id',\n )\n\n if (operation === 'read') {\n if (value instanceof Types.ObjectId) {\n return value.toHexString()\n }\n\n return value\n }\n\n if (customIDField) {\n return value\n }\n\n if (typeof value === 'string') {\n try {\n return new Types.ObjectId(value)\n } catch (e) {\n if (validateRelationships) {\n throw e\n }\n return value\n }\n }\n\n return value\n}\n\nconst sanitizeRelationship = ({\n config,\n field,\n locale,\n operation,\n ref,\n validateRelationships,\n value,\n}: {\n config: SanitizedConfig\n field: JoinField | RelationshipField | UploadField\n locale?: string\n operation: Args['operation']\n ref: Record<string, unknown>\n validateRelationships?: boolean\n value?: unknown\n}) => {\n if (field.type === 'join') {\n if (\n operation === 'read' &&\n value &&\n typeof value === 'object' &&\n 'docs' in value &&\n Array.isArray(value.docs)\n ) {\n for (let i = 0; i < value.docs.length; i++) {\n const item = value.docs[i]\n\n if (item instanceof Types.ObjectId) {\n value.docs[i] = item.toHexString()\n } else if (Array.isArray(field.collection) && item) {\n // Fields here for polymorphic joins cannot be determinted, JSON.parse needed\n value.docs[i] = JSON.parse(JSON.stringify(value.docs[i]))\n }\n }\n }\n\n return value\n }\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 - 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: convertRelationshipValue({\n operation,\n relatedCollection: relatedCollectionForSingleValue,\n validateRelationships,\n value: val.value,\n }),\n }\n }\n }\n\n if (relatedCollection) {\n return convertRelationshipValue({\n operation,\n relatedCollection,\n validateRelationships,\n value: val,\n })\n }\n\n return val\n })\n }\n // Handle has one - polymorphic\n else if (isValidRelationObject(value)) {\n relatedCollection = config.collections?.find(({ slug }) => slug === value.relationTo)\n\n if (relatedCollection) {\n result = {\n relationTo: value.relationTo,\n value: convertRelationshipValue({\n operation,\n relatedCollection,\n validateRelationships,\n value: value.value,\n }),\n }\n }\n }\n // Handle has one\n else if (relatedCollection) {\n result = convertRelationshipValue({\n operation,\n relatedCollection,\n validateRelationships,\n value,\n })\n }\n\n if (locale) {\n ref[locale] = result\n } else {\n ref[field.name] = result\n }\n}\n\nconst sanitizeDate = ({\n field,\n locale,\n ref,\n value,\n}: {\n field: DateField\n locale?: string\n ref: Record<string, unknown>\n value: unknown\n}) => {\n if (!value) {\n return\n }\n\n if (value instanceof Date) {\n value = value.toISOString()\n }\n\n if (locale) {\n ref[locale] = value\n } else {\n ref[field.name] = value\n }\n}\n\ntype Args = {\n /** instance of the adapter */\n adapter: MongooseAdapter\n /** data to transform, can be an array of documents or a single document */\n data: Record<string, unknown> | Record<string, unknown>[]\n /** fields accossiated with the data */\n fields: Field[]\n /** slug of the global, pass only when the operation is `write` */\n globalSlug?: string\n /**\n * Type of the operation\n * read - sanitizes ObjectIDs, Date to strings.\n * write - sanitizes string relationships to ObjectIDs.\n */\n operation: 'read' | 'write'\n parentIsLocalized?: boolean\n /**\n * Throw errors on invalid relationships\n * @default true\n */\n validateRelationships?: boolean\n}\n\nconst stripFields = ({\n config,\n data,\n fields,\n reservedKeys = [],\n}: {\n config: SanitizedConfig\n data: any\n fields: FlattenedField[]\n reservedKeys?: string[]\n}) => {\n for (const k in data) {\n if (!fields.some((field) => field.name === k) && !reservedKeys.includes(k)) {\n delete data[k]\n }\n }\n\n for (const field of fields) {\n reservedKeys = []\n const fieldData = data[field.name]\n if (!fieldData || typeof fieldData !== 'object') {\n continue\n }\n\n if (field.type === 'blocks') {\n reservedKeys.push('blockType')\n }\n\n if ('flattenedFields' in field || 'blocks' in field) {\n if (field.localized && config.localization) {\n for (const localeKey in fieldData) {\n if (!config.localization.localeCodes.some((code) => code === localeKey)) {\n delete fieldData[localeKey]\n continue\n }\n\n const localeData = fieldData[localeKey]\n\n if (!localeData || typeof localeData !== 'object') {\n continue\n }\n\n if (field.type === 'array' || field.type === 'blocks') {\n if (!Array.isArray(localeData)) {\n continue\n }\n\n let hasNull = false\n for (let i = 0; i < localeData.length; i++) {\n const data = localeData[i]\n let fields: FlattenedField[] | null = null\n\n if (field.type === 'array') {\n fields = field.flattenedFields\n } else {\n let maybeBlock: FlattenedBlock | undefined = undefined\n\n if (field.blockReferences) {\n const maybeBlockReference = field.blockReferences.find((each) => {\n const slug = typeof each === 'string' ? each : each.slug\n return slug === data.blockType\n })\n\n if (maybeBlockReference) {\n if (typeof maybeBlockReference === 'object') {\n maybeBlock = maybeBlockReference\n } else {\n maybeBlock = config.blocks?.find((each) => each.slug === maybeBlockReference)\n }\n }\n }\n\n if (!maybeBlock) {\n maybeBlock = field.blocks.find((each) => each.slug === data.blockType)\n }\n\n if (maybeBlock) {\n fields = maybeBlock.flattenedFields\n } else {\n localeData[i] = null\n hasNull = true\n }\n }\n\n if (!fields) {\n continue\n }\n\n stripFields({ config, data, fields, reservedKeys })\n }\n\n if (hasNull) {\n fieldData[localeKey] = localeData.filter(Boolean)\n }\n\n continue\n } else {\n stripFields({ config, data: localeData, fields: field.flattenedFields, reservedKeys })\n }\n }\n continue\n }\n\n if (field.type === 'array' || field.type === 'blocks') {\n if (!Array.isArray(fieldData)) {\n continue\n }\n\n let hasNull = false\n\n for (let i = 0; i < fieldData.length; i++) {\n const data = fieldData[i]\n let fields: FlattenedField[] | null = null\n\n if (field.type === 'array') {\n fields = field.flattenedFields\n } else {\n let maybeBlock: FlattenedBlock | undefined = undefined\n\n if (field.blockReferences) {\n const maybeBlockReference = field.blockReferences.find((each) => {\n const slug = typeof each === 'string' ? each : each.slug\n return slug === data.blockType\n })\n\n if (maybeBlockReference) {\n if (typeof maybeBlockReference === 'object') {\n maybeBlock = maybeBlockReference\n } else {\n maybeBlock = config.blocks?.find((each) => each.slug === maybeBlockReference)\n }\n }\n }\n\n if (!maybeBlock) {\n maybeBlock = field.blocks.find((each) => each.slug === data.blockType)\n }\n\n if (maybeBlock) {\n fields = maybeBlock.flattenedFields\n } else {\n fieldData[i] = null\n hasNull = true\n }\n }\n\n if (!fields) {\n continue\n }\n\n stripFields({ config, data, fields, reservedKeys })\n }\n\n if (hasNull) {\n data[field.name] = fieldData.filter(Boolean)\n }\n\n continue\n } else {\n stripFields({ config, data: fieldData, fields: field.flattenedFields, reservedKeys })\n }\n }\n }\n}\n\nexport const transform = ({\n adapter,\n data,\n fields,\n globalSlug,\n operation,\n parentIsLocalized = false,\n validateRelationships = true,\n}: Args) => {\n if (Array.isArray(data)) {\n for (const item of data) {\n transform({ adapter, data: item, fields, globalSlug, operation, validateRelationships })\n }\n return\n }\n\n const {\n payload: { config },\n } = adapter\n\n if (operation === 'read') {\n delete data['__v']\n data.id = data._id\n delete data['_id']\n\n if (data.id instanceof Types.ObjectId) {\n data.id = data.id.toHexString()\n }\n\n if (!adapter.allowAdditionalKeys) {\n stripFields({\n config,\n data,\n fields: flattenAllFields({ cache: true, fields }),\n reservedKeys: ['id', 'globalType'],\n })\n }\n }\n\n if (operation === 'write' && globalSlug) {\n data.globalType = globalSlug\n }\n\n const sanitize: TraverseFieldsCallback = ({ field, ref: incomingRef }) => {\n if (!incomingRef || typeof incomingRef !== 'object') {\n return\n }\n\n const ref = incomingRef as Record<string, unknown>\n\n if (field.type === 'date' && operation === 'read' && field.name in ref && ref[field.name]) {\n if (config.localization && fieldShouldBeLocalized({ field, parentIsLocalized })) {\n const fieldRef = ref[field.name] as Record<string, unknown>\n if (!fieldRef || typeof fieldRef !== 'object') {\n return\n }\n\n for (const locale of config.localization.localeCodes) {\n sanitizeDate({\n field,\n locale,\n ref: fieldRef,\n value: fieldRef[locale],\n })\n }\n } else {\n sanitizeDate({\n field,\n ref,\n value: ref[field.name],\n })\n }\n }\n\n if (\n field.type === 'relationship' ||\n field.type === 'upload' ||\n (operation === 'read' && field.type === 'join')\n ) {\n if (!ref[field.name]) {\n return\n }\n\n // handle localized relationships\n if (config.localization && fieldShouldBeLocalized({ field, parentIsLocalized })) {\n const locales = config.localization.locales\n const fieldRef = ref[field.name] as Record<string, unknown>\n if (typeof fieldRef !== 'object') {\n return\n }\n\n for (const { code } of locales) {\n const value = fieldRef[code]\n if (value) {\n sanitizeRelationship({\n config,\n field,\n locale: code,\n operation,\n ref: fieldRef,\n validateRelationships,\n value,\n })\n }\n }\n } else {\n // handle non-localized relationships\n sanitizeRelationship({\n config,\n field,\n locale: undefined,\n operation,\n ref,\n validateRelationships,\n value: ref[field.name],\n })\n }\n }\n }\n\n traverseFields({\n callback: sanitize,\n config,\n fields,\n fillEmpty: false,\n parentIsLocalized,\n ref: data,\n })\n}\n"],"names":["Types","flattenAllFields","traverseFields","fieldAffectsData","fieldShouldBeLocalized","isValidRelationObject","value","convertRelationshipValue","operation","relatedCollection","validateRelationships","customIDField","fields","find","field","name","ObjectId","toHexString","e","sanitizeRelationship","config","locale","ref","type","Array","isArray","docs","i","length","item","collection","JSON","parse","stringify","result","hasManyRelations","relationTo","collections","slug","map","val","relatedCollectionForSingleValue","sanitizeDate","Date","toISOString","stripFields","data","reservedKeys","k","some","includes","fieldData","push","localized","localization","localeKey","localeCodes","code","localeData","hasNull","flattenedFields","maybeBlock","undefined","blockReferences","maybeBlockReference","each","blockType","blocks","filter","Boolean","transform","adapter","globalSlug","parentIsLocalized","payload","id","_id","allowAdditionalKeys","cache","globalType","sanitize","incomingRef","fieldRef","locales","callback","fillEmpty"],"mappings":"AAaA,SAASA,KAAK,QAAQ,WAAU;AAChC,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,UAAS;AAC1D,SAASC,gBAAgB,EAAEC,sBAAsB,QAAQ,iBAAgB;AASzE,SAASC,sBAAsBC,KAAc;IAC3C,OAAO,OAAOA,UAAU,YAAYA,UAAU,QAAQ,gBAAgBA,SAAS,WAAWA;AAC5F;AAEA,MAAMC,2BAA2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,IAAInD,OAAO;wBACTa,qBAAqB;4BACnBC;4BACAN;4BACAO,QAAQoC;4BACRjD;4BACAc,KAAK4D;4BACLxE;4BACAJ;wBACF;oBACF;gBACF;YACF,OAAO;gBACL,qCAAqC;gBACrCa,qBAAqB;oBACnBC;oBACAN;oBACAO,QAAQyC;oBACRtD;oBACAc;oBACAZ;oBACAJ,OAAOgB,GAAG,CAACR,MAAMC,IAAI,CAAC;gBACxB;YACF;QACF;IACF;IAEAb,eAAe;QACbkF,UAAUJ;QACV5D;QACAR;QACAyE,WAAW;QACXZ;QACAnD,KAAKwB;IACP;AACF,EAAC"}
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@payloadcms/db-mongodb",
|
3
|
-
"version": "3.
|
3
|
+
"version": "3.45.0-canary.0",
|
4
4
|
"description": "The officially supported MongoDB database adapter for Payload",
|
5
5
|
"homepage": "https://payloadcms.com",
|
6
6
|
"repository": {
|
@@ -50,10 +50,10 @@
|
|
50
50
|
"mongodb": "6.16.0",
|
51
51
|
"mongodb-memory-server": "10.1.4",
|
52
52
|
"@payloadcms/eslint-config": "3.28.0",
|
53
|
-
"payload": "3.
|
53
|
+
"payload": "3.45.0-canary.0"
|
54
54
|
},
|
55
55
|
"peerDependencies": {
|
56
|
-
"payload": "3.
|
56
|
+
"payload": "3.45.0-canary.0"
|
57
57
|
},
|
58
58
|
"scripts": {
|
59
59
|
"build": "pnpm build:types && pnpm build:swc",
|