@payloadcms/db-mongodb 4.0.0-internal.543da65 → 4.0.0-internal.567a487
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/count.d.ts.map +1 -1
- package/dist/count.js +8 -2
- package/dist/count.js.map +1 -1
- package/dist/countVersions.d.ts.map +1 -1
- package/dist/countVersions.js +10 -2
- package/dist/countVersions.js.map +1 -1
- package/dist/createGlobalVersion.d.ts.map +1 -1
- package/dist/createGlobalVersion.js +22 -0
- package/dist/createGlobalVersion.js.map +1 -1
- package/dist/createVersion.d.ts.map +1 -1
- package/dist/createVersion.js +16 -3
- package/dist/createVersion.js.map +1 -1
- package/dist/deleteBranchGlobal.d.ts +10 -0
- package/dist/deleteBranchGlobal.d.ts.map +1 -0
- package/dist/deleteBranchGlobal.js +22 -0
- package/dist/deleteBranchGlobal.js.map +1 -0
- package/dist/deleteOne.d.ts.map +1 -1
- package/dist/deleteOne.js +18 -1
- package/dist/deleteOne.js.map +1 -1
- package/dist/find.d.ts.map +1 -1
- package/dist/find.js +24 -5
- package/dist/find.js.map +1 -1
- package/dist/findDistinct.d.ts.map +1 -1
- package/dist/findDistinct.js +10 -2
- package/dist/findDistinct.js.map +1 -1
- package/dist/findGlobal.d.ts.map +1 -1
- package/dist/findGlobal.js +26 -4
- package/dist/findGlobal.js.map +1 -1
- package/dist/findGlobalVersions.d.ts.map +1 -1
- package/dist/findGlobalVersions.js +8 -2
- package/dist/findGlobalVersions.js.map +1 -1
- package/dist/findOne.d.ts.map +1 -1
- package/dist/findOne.js +24 -3
- package/dist/findOne.js.map +1 -1
- package/dist/findVersions.d.ts.map +1 -1
- package/dist/findVersions.js +17 -3
- package/dist/findVersions.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/models/buildCollectionSchema.d.ts.map +1 -1
- package/dist/models/buildGlobalModel.d.ts.map +1 -1
- package/dist/models/buildSchema.d.ts.map +1 -1
- package/dist/queries/buildQuery.d.ts.map +1 -1
- package/dist/queries/buildSortParam.d.ts.map +1 -1
- package/dist/queries/buildSortParam.spec.js +1 -1
- package/dist/queries/buildSortParam.spec.js.map +1 -1
- package/dist/queries/getBuildQueryPlugin.d.ts.map +1 -1
- package/dist/queries/getLocalizedSortProperty.d.ts.map +1 -1
- package/dist/queries/getLocalizedSortProperty.spec.js +1 -1
- package/dist/queries/getLocalizedSortProperty.spec.js.map +1 -1
- package/dist/queries/operatorMap.d.ts.map +1 -1
- package/dist/queries/sanitizeQueryValue.d.ts.map +1 -1
- package/dist/queryDrafts.d.ts.map +1 -1
- package/dist/queryDrafts.js +16 -4
- package/dist/queryDrafts.js.map +1 -1
- package/dist/testCredentials.d.ts.map +1 -1
- package/dist/transactions/beginTransaction.d.ts.map +1 -1
- package/dist/transactions/beginTransaction.js +0 -1
- package/dist/transactions/beginTransaction.js.map +1 -1
- package/dist/updateGlobal.d.ts.map +1 -1
- package/dist/updateGlobal.js +68 -7
- package/dist/updateGlobal.js.map +1 -1
- package/dist/updateJobs.d.ts.map +1 -1
- package/dist/updateJobs.js +70 -13
- package/dist/updateJobs.js.map +1 -1
- package/dist/updateOne.d.ts.map +1 -1
- package/dist/updateOne.js +26 -2
- package/dist/updateOne.js.map +1 -1
- package/dist/utilities/aggregatePaginate.d.ts.map +1 -1
- package/dist/utilities/buildJoinAggregation.d.ts +3 -2
- package/dist/utilities/buildJoinAggregation.d.ts.map +1 -1
- package/dist/utilities/buildJoinAggregation.js +31 -4
- package/dist/utilities/buildJoinAggregation.js.map +1 -1
- package/dist/utilities/buildProjectionFromSelect.d.ts.map +1 -1
- package/dist/utilities/getDBName.d.ts.map +1 -1
- package/dist/utilities/getEntity.d.ts +1 -1
- package/dist/utilities/getEntity.d.ts.map +1 -1
- package/dist/utilities/handleError.d.ts.map +1 -1
- package/dist/utilities/isObjectID.d.ts.map +1 -1
- package/dist/utilities/resolveJoins.d.ts +4 -2
- package/dist/utilities/resolveJoins.d.ts.map +1 -1
- package/dist/utilities/resolveJoins.js +16 -2
- package/dist/utilities/resolveJoins.js.map +1 -1
- package/dist/utilities/transform.d.ts.map +1 -1
- package/dist/utilities/transform.js +15 -0
- package/dist/utilities/transform.js.map +1 -1
- package/dist/utilities/transform.spec.js +67 -0
- package/dist/utilities/transform.spec.js.map +1 -1
- package/package.json +4 -4
package/dist/count.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"count.d.ts","sourceRoot":"","sources":["../src/count.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAUpC,eAAO,MAAM,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"count.d.ts","sourceRoot":"","sources":["../src/count.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAUpC,eAAO,MAAM,KAAK,EAAE,KA6DnB,CAAA"}
|
package/dist/count.js
CHANGED
|
@@ -1,12 +1,18 @@
|
|
|
1
|
-
import { flattenWhereToOperators } from 'payload';
|
|
1
|
+
import { flattenWhereToOperators, resolveBranchQuery } from 'payload';
|
|
2
2
|
import { buildQuery } from './queries/buildQuery.js';
|
|
3
3
|
import { getCollection } from './utilities/getEntity.js';
|
|
4
4
|
import { getSession } from './utilities/getSession.js';
|
|
5
|
-
export const count = async function count({ collection: collectionSlug, locale, req, where = {} }) {
|
|
5
|
+
export const count = async function count({ branch, collection: collectionSlug, locale, req, where = {} }) {
|
|
6
6
|
const { collectionConfig, Model } = getCollection({
|
|
7
7
|
adapter: this,
|
|
8
8
|
collectionSlug
|
|
9
9
|
});
|
|
10
|
+
where = await resolveBranchQuery({
|
|
11
|
+
branch,
|
|
12
|
+
collectionSlug,
|
|
13
|
+
req,
|
|
14
|
+
where
|
|
15
|
+
}) ?? {};
|
|
10
16
|
let hasNearConstraint = false;
|
|
11
17
|
if (where) {
|
|
12
18
|
const constraints = flattenWhereToOperators(where);
|
package/dist/count.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/count.ts"],"sourcesContent":["import type { CountOptions } from 'mongodb'\nimport type { Count } from 'payload'\n\nimport { flattenWhereToOperators } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { buildQuery } from './queries/buildQuery.js'\nimport { getCollection } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\n\nexport const count: Count = async function count(\n this: MongooseAdapter,\n { collection: collectionSlug, locale, req, where = {} },\n) {\n const { collectionConfig, Model } = getCollection({ adapter: this, collectionSlug })\n\n let hasNearConstraint = false\n\n if (where) {\n const constraints = flattenWhereToOperators(where)\n hasNearConstraint = constraints.some((prop) => Object.keys(prop).some((key) => key === 'near'))\n }\n\n const query = await buildQuery({\n adapter: this,\n collectionSlug,\n fields: collectionConfig.flattenedFields,\n locale,\n where,\n })\n\n // useEstimatedCount is faster, but not accurate, as it ignores any filters. It is thus set to true if there are no filters.\n const useEstimatedCount = hasNearConstraint || !query || Object.keys(query).length === 0\n\n const options: CountOptions = {\n session: await getSession(this, req),\n }\n\n if (this.collation) {\n const localizationConfig = this.payload.config.localization\n const defaultLocale =\n (typeof localizationConfig === 'object' && localizationConfig?.defaultLocale) || 'en'\n\n options.collation = {\n locale: locale && locale !== 'all' && locale !== '*' ? locale : defaultLocale,\n ...this.collation,\n }\n }\n\n if (!useEstimatedCount && Object.keys(query).length === 0 && this.disableIndexHints !== true) {\n // Improve the performance of the countDocuments query which is used if useEstimatedCount is set to false by adding\n // a hint. By default, if no hint is provided, MongoDB does not use an indexed field to count the returned documents,\n // which makes queries very slow. This only happens when no query (filter) is provided. If one is provided, it uses\n // the correct indexed field\n options.hint = {\n _id: 1,\n }\n }\n\n let result: number\n if (useEstimatedCount) {\n result = await Model.estimatedDocumentCount({ session: options.session })\n } else {\n result = await Model.countDocuments(query, options)\n }\n\n return {\n totalDocs: result,\n }\n}\n"],"names":["flattenWhereToOperators","buildQuery","getCollection","getSession","count","collection","collectionSlug","locale","req","where","collectionConfig","Model","adapter","hasNearConstraint","constraints","some","prop","Object","keys","key","query","fields","flattenedFields","useEstimatedCount","length","options","session","collation","localizationConfig","payload","config","localization","defaultLocale","disableIndexHints","hint","_id","result","estimatedDocumentCount","countDocuments","totalDocs"],"mappings":"AAGA,SAASA,uBAAuB,QAAQ,UAAS;
|
|
1
|
+
{"version":3,"sources":["../src/count.ts"],"sourcesContent":["import type { CountOptions } from 'mongodb'\nimport type { Count } from 'payload'\n\nimport { flattenWhereToOperators, resolveBranchQuery } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { buildQuery } from './queries/buildQuery.js'\nimport { getCollection } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\n\nexport const count: Count = async function count(\n this: MongooseAdapter,\n { branch, collection: collectionSlug, locale, req, where = {} },\n) {\n const { collectionConfig, Model } = getCollection({ adapter: this, collectionSlug })\n\n where = (await resolveBranchQuery({ branch, collectionSlug, req, where })) ?? {}\n\n let hasNearConstraint = false\n\n if (where) {\n const constraints = flattenWhereToOperators(where)\n hasNearConstraint = constraints.some((prop) => Object.keys(prop).some((key) => key === 'near'))\n }\n\n const query = await buildQuery({\n adapter: this,\n collectionSlug,\n fields: collectionConfig.flattenedFields,\n locale,\n where,\n })\n\n // useEstimatedCount is faster, but not accurate, as it ignores any filters. It is thus set to true if there are no filters.\n const useEstimatedCount = hasNearConstraint || !query || Object.keys(query).length === 0\n\n const options: CountOptions = {\n session: await getSession(this, req),\n }\n\n if (this.collation) {\n const localizationConfig = this.payload.config.localization\n const defaultLocale =\n (typeof localizationConfig === 'object' && localizationConfig?.defaultLocale) || 'en'\n\n options.collation = {\n locale: locale && locale !== 'all' && locale !== '*' ? locale : defaultLocale,\n ...this.collation,\n }\n }\n\n if (!useEstimatedCount && Object.keys(query).length === 0 && this.disableIndexHints !== true) {\n // Improve the performance of the countDocuments query which is used if useEstimatedCount is set to false by adding\n // a hint. By default, if no hint is provided, MongoDB does not use an indexed field to count the returned documents,\n // which makes queries very slow. This only happens when no query (filter) is provided. If one is provided, it uses\n // the correct indexed field\n options.hint = {\n _id: 1,\n }\n }\n\n let result: number\n if (useEstimatedCount) {\n result = await Model.estimatedDocumentCount({ session: options.session })\n } else {\n result = await Model.countDocuments(query, options)\n }\n\n return {\n totalDocs: result,\n }\n}\n"],"names":["flattenWhereToOperators","resolveBranchQuery","buildQuery","getCollection","getSession","count","branch","collection","collectionSlug","locale","req","where","collectionConfig","Model","adapter","hasNearConstraint","constraints","some","prop","Object","keys","key","query","fields","flattenedFields","useEstimatedCount","length","options","session","collation","localizationConfig","payload","config","localization","defaultLocale","disableIndexHints","hint","_id","result","estimatedDocumentCount","countDocuments","totalDocs"],"mappings":"AAGA,SAASA,uBAAuB,EAAEC,kBAAkB,QAAQ,UAAS;AAIrE,SAASC,UAAU,QAAQ,0BAAyB;AACpD,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,UAAU,QAAQ,4BAA2B;AAEtD,OAAO,MAAMC,QAAe,eAAeA,MAEzC,EAAEC,MAAM,EAAEC,YAAYC,cAAc,EAAEC,MAAM,EAAEC,GAAG,EAAEC,QAAQ,CAAC,CAAC,EAAE;IAE/D,MAAM,EAAEC,gBAAgB,EAAEC,KAAK,EAAE,GAAGV,cAAc;QAAEW,SAAS,IAAI;QAAEN;IAAe;IAElFG,QAAQ,AAAC,MAAMV,mBAAmB;QAAEK;QAAQE;QAAgBE;QAAKC;IAAM,MAAO,CAAC;IAE/E,IAAII,oBAAoB;IAExB,IAAIJ,OAAO;QACT,MAAMK,cAAchB,wBAAwBW;QAC5CI,oBAAoBC,YAAYC,IAAI,CAAC,CAACC,OAASC,OAAOC,IAAI,CAACF,MAAMD,IAAI,CAAC,CAACI,MAAQA,QAAQ;IACzF;IAEA,MAAMC,QAAQ,MAAMpB,WAAW;QAC7BY,SAAS,IAAI;QACbN;QACAe,QAAQX,iBAAiBY,eAAe;QACxCf;QACAE;IACF;IAEA,4HAA4H;IAC5H,MAAMc,oBAAoBV,qBAAqB,CAACO,SAASH,OAAOC,IAAI,CAACE,OAAOI,MAAM,KAAK;IAEvF,MAAMC,UAAwB;QAC5BC,SAAS,MAAMxB,WAAW,IAAI,EAAEM;IAClC;IAEA,IAAI,IAAI,CAACmB,SAAS,EAAE;QAClB,MAAMC,qBAAqB,IAAI,CAACC,OAAO,CAACC,MAAM,CAACC,YAAY;QAC3D,MAAMC,gBACJ,AAAC,OAAOJ,uBAAuB,YAAYA,oBAAoBI,iBAAkB;QAEnFP,QAAQE,SAAS,GAAG;YAClBpB,QAAQA,UAAUA,WAAW,SAASA,WAAW,MAAMA,SAASyB;YAChE,GAAG,IAAI,CAACL,SAAS;QACnB;IACF;IAEA,IAAI,CAACJ,qBAAqBN,OAAOC,IAAI,CAACE,OAAOI,MAAM,KAAK,KAAK,IAAI,CAACS,iBAAiB,KAAK,MAAM;QAC5F,mHAAmH;QACnH,qHAAqH;QACrH,mHAAmH;QACnH,4BAA4B;QAC5BR,QAAQS,IAAI,GAAG;YACbC,KAAK;QACP;IACF;IAEA,IAAIC;IACJ,IAAIb,mBAAmB;QACrBa,SAAS,MAAMzB,MAAM0B,sBAAsB,CAAC;YAAEX,SAASD,QAAQC,OAAO;QAAC;IACzE,OAAO;QACLU,SAAS,MAAMzB,MAAM2B,cAAc,CAAClB,OAAOK;IAC7C;IAEA,OAAO;QACLc,WAAWH;IACb;AACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"countVersions.d.ts","sourceRoot":"","sources":["../src/countVersions.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"countVersions.d.ts","sourceRoot":"","sources":["../src/countVersions.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAc5C,eAAO,MAAM,aAAa,EAAE,aAkE3B,CAAA"}
|
package/dist/countVersions.js
CHANGED
|
@@ -1,13 +1,21 @@
|
|
|
1
|
-
import { buildVersionCollectionFields, flattenWhereToOperators } from 'payload';
|
|
1
|
+
import { buildVersionCollectionFields, flattenWhereToOperators, resolveBranchVersionHistoryQuery } from 'payload';
|
|
2
2
|
import { buildQuery } from './queries/buildQuery.js';
|
|
3
3
|
import { getCollection } from './utilities/getEntity.js';
|
|
4
4
|
import { getSession } from './utilities/getSession.js';
|
|
5
|
-
export const countVersions = async function countVersions({ collection: collectionSlug, locale, req, where = {} }) {
|
|
5
|
+
export const countVersions = async function countVersions({ branch, collection: collectionSlug, locale, req, where = {} }) {
|
|
6
6
|
const { collectionConfig, Model } = getCollection({
|
|
7
7
|
adapter: this,
|
|
8
8
|
collectionSlug,
|
|
9
9
|
versions: true
|
|
10
10
|
});
|
|
11
|
+
// Shares the list's predicate so the count in the Versions tab can never
|
|
12
|
+
// disagree with the rows the Versions view actually renders.
|
|
13
|
+
where = resolveBranchVersionHistoryQuery({
|
|
14
|
+
branch,
|
|
15
|
+
collectionSlug,
|
|
16
|
+
req,
|
|
17
|
+
where
|
|
18
|
+
}) ?? {};
|
|
11
19
|
let hasNearConstraint = false;
|
|
12
20
|
if (where) {
|
|
13
21
|
const constraints = flattenWhereToOperators(where);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/countVersions.ts"],"sourcesContent":["import type { CountOptions } from 'mongodb'\nimport type { CountVersions } from 'payload'\n\nimport {
|
|
1
|
+
{"version":3,"sources":["../src/countVersions.ts"],"sourcesContent":["import type { CountOptions } from 'mongodb'\nimport type { CountVersions } from 'payload'\n\nimport {\n buildVersionCollectionFields,\n flattenWhereToOperators,\n resolveBranchVersionHistoryQuery,\n} from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { buildQuery } from './queries/buildQuery.js'\nimport { getCollection } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\n\nexport const countVersions: CountVersions = async function countVersions(\n this: MongooseAdapter,\n { branch, collection: collectionSlug, locale, req, where = {} },\n) {\n const { collectionConfig, Model } = getCollection({\n adapter: this,\n collectionSlug,\n versions: true,\n })\n\n // Shares the list's predicate so the count in the Versions tab can never\n // disagree with the rows the Versions view actually renders.\n where = resolveBranchVersionHistoryQuery({ branch, collectionSlug, req, where }) ?? {}\n\n let hasNearConstraint = false\n\n if (where) {\n const constraints = flattenWhereToOperators(where)\n hasNearConstraint = constraints.some((prop) => Object.keys(prop).some((key) => key === 'near'))\n }\n\n const query = await buildQuery({\n adapter: this,\n fields: buildVersionCollectionFields(this.payload.config, collectionConfig, true),\n locale,\n where,\n })\n\n // useEstimatedCount is faster, but not accurate, as it ignores any filters. It is thus set to true if there are no filters.\n const useEstimatedCount = hasNearConstraint || !query || Object.keys(query).length === 0\n\n const options: CountOptions = {\n session: await getSession(this, req),\n }\n\n if (this.collation) {\n const localizationConfig = this.payload.config.localization\n const defaultLocale =\n (typeof localizationConfig === 'object' && localizationConfig?.defaultLocale) || 'en'\n\n options.collation = {\n locale: locale && locale !== 'all' && locale !== '*' ? locale : defaultLocale,\n ...this.collation,\n }\n }\n\n if (!useEstimatedCount && Object.keys(query).length === 0 && this.disableIndexHints !== true) {\n // Improve the performance of the countDocuments query which is used if useEstimatedCount is set to false by adding\n // a hint. By default, if no hint is provided, MongoDB does not use an indexed field to count the returned documents,\n // which makes queries very slow. This only happens when no query (filter) is provided. If one is provided, it uses\n // the correct indexed field\n options.hint = {\n _id: 1,\n }\n }\n\n let result: number\n if (useEstimatedCount) {\n result = await Model.estimatedDocumentCount({ session: options.session })\n } else {\n result = await Model.countDocuments(query, options)\n }\n\n return {\n totalDocs: result,\n }\n}\n"],"names":["buildVersionCollectionFields","flattenWhereToOperators","resolveBranchVersionHistoryQuery","buildQuery","getCollection","getSession","countVersions","branch","collection","collectionSlug","locale","req","where","collectionConfig","Model","adapter","versions","hasNearConstraint","constraints","some","prop","Object","keys","key","query","fields","payload","config","useEstimatedCount","length","options","session","collation","localizationConfig","localization","defaultLocale","disableIndexHints","hint","_id","result","estimatedDocumentCount","countDocuments","totalDocs"],"mappings":"AAGA,SACEA,4BAA4B,EAC5BC,uBAAuB,EACvBC,gCAAgC,QAC3B,UAAS;AAIhB,SAASC,UAAU,QAAQ,0BAAyB;AACpD,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,UAAU,QAAQ,4BAA2B;AAEtD,OAAO,MAAMC,gBAA+B,eAAeA,cAEzD,EAAEC,MAAM,EAAEC,YAAYC,cAAc,EAAEC,MAAM,EAAEC,GAAG,EAAEC,QAAQ,CAAC,CAAC,EAAE;IAE/D,MAAM,EAAEC,gBAAgB,EAAEC,KAAK,EAAE,GAAGV,cAAc;QAChDW,SAAS,IAAI;QACbN;QACAO,UAAU;IACZ;IAEA,yEAAyE;IACzE,6DAA6D;IAC7DJ,QAAQV,iCAAiC;QAAEK;QAAQE;QAAgBE;QAAKC;IAAM,MAAM,CAAC;IAErF,IAAIK,oBAAoB;IAExB,IAAIL,OAAO;QACT,MAAMM,cAAcjB,wBAAwBW;QAC5CK,oBAAoBC,YAAYC,IAAI,CAAC,CAACC,OAASC,OAAOC,IAAI,CAACF,MAAMD,IAAI,CAAC,CAACI,MAAQA,QAAQ;IACzF;IAEA,MAAMC,QAAQ,MAAMrB,WAAW;QAC7BY,SAAS,IAAI;QACbU,QAAQzB,6BAA6B,IAAI,CAAC0B,OAAO,CAACC,MAAM,EAAEd,kBAAkB;QAC5EH;QACAE;IACF;IAEA,4HAA4H;IAC5H,MAAMgB,oBAAoBX,qBAAqB,CAACO,SAASH,OAAOC,IAAI,CAACE,OAAOK,MAAM,KAAK;IAEvF,MAAMC,UAAwB;QAC5BC,SAAS,MAAM1B,WAAW,IAAI,EAAEM;IAClC;IAEA,IAAI,IAAI,CAACqB,SAAS,EAAE;QAClB,MAAMC,qBAAqB,IAAI,CAACP,OAAO,CAACC,MAAM,CAACO,YAAY;QAC3D,MAAMC,gBACJ,AAAC,OAAOF,uBAAuB,YAAYA,oBAAoBE,iBAAkB;QAEnFL,QAAQE,SAAS,GAAG;YAClBtB,QAAQA,UAAUA,WAAW,SAASA,WAAW,MAAMA,SAASyB;YAChE,GAAG,IAAI,CAACH,SAAS;QACnB;IACF;IAEA,IAAI,CAACJ,qBAAqBP,OAAOC,IAAI,CAACE,OAAOK,MAAM,KAAK,KAAK,IAAI,CAACO,iBAAiB,KAAK,MAAM;QAC5F,mHAAmH;QACnH,qHAAqH;QACrH,mHAAmH;QACnH,4BAA4B;QAC5BN,QAAQO,IAAI,GAAG;YACbC,KAAK;QACP;IACF;IAEA,IAAIC;IACJ,IAAIX,mBAAmB;QACrBW,SAAS,MAAMzB,MAAM0B,sBAAsB,CAAC;YAAET,SAASD,QAAQC,OAAO;QAAC;IACzE,OAAO;QACLQ,SAAS,MAAMzB,MAAM2B,cAAc,CAACjB,OAAOM;IAC7C;IAEA,OAAO;QACLY,WAAWH;IACb;AACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createGlobalVersion.d.ts","sourceRoot":"","sources":["../src/createGlobalVersion.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"createGlobalVersion.d.ts","sourceRoot":"","sources":["../src/createGlobalVersion.ts"],"names":[],"mappings":"AACA,OAAO,EAA4B,KAAK,mBAAmB,EAAE,MAAM,SAAS,CAAA;AAQ5E,eAAO,MAAM,mBAAmB,EAAE,mBA6FjC,CAAA"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { MAIN_BRANCH, resolveBranch } from 'payload';
|
|
1
2
|
import { buildVersionGlobalFields } from 'payload';
|
|
2
3
|
import { getGlobal } from './utilities/getEntity.js';
|
|
3
4
|
import { getSession } from './utilities/getSession.js';
|
|
@@ -8,7 +9,9 @@ export const createGlobalVersion = async function createGlobalVersion({ autosave
|
|
|
8
9
|
globalSlug,
|
|
9
10
|
versions: true
|
|
10
11
|
});
|
|
12
|
+
const versionBranch = req?.payload?.config?.branching?.branchableGlobals?.has(globalSlug) ? resolveBranch(req) : MAIN_BRANCH;
|
|
11
13
|
const data = {
|
|
14
|
+
_branch: versionBranch,
|
|
12
15
|
autosave,
|
|
13
16
|
createdAt,
|
|
14
17
|
latest: true,
|
|
@@ -35,6 +38,9 @@ export const createGlobalVersion = async function createGlobalVersion({ autosave
|
|
|
35
38
|
let [doc] = await Model.create([
|
|
36
39
|
data
|
|
37
40
|
], options, req);
|
|
41
|
+
// Scoped by `_branch`. Unlike collection versions, global versions have no
|
|
42
|
+
// `parent` to separate streams by — every version of a global shares one — so
|
|
43
|
+
// without this an unscoped clear would wipe main's latest flag from a branch.
|
|
38
44
|
await Model.updateMany({
|
|
39
45
|
$and: [
|
|
40
46
|
{
|
|
@@ -46,6 +52,22 @@ export const createGlobalVersion = async function createGlobalVersion({ autosave
|
|
|
46
52
|
latest: {
|
|
47
53
|
$eq: true
|
|
48
54
|
}
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
$or: [
|
|
58
|
+
{
|
|
59
|
+
_branch: {
|
|
60
|
+
$eq: versionBranch
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
...versionBranch === MAIN_BRANCH ? [
|
|
64
|
+
{
|
|
65
|
+
_branch: {
|
|
66
|
+
$exists: false
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
] : []
|
|
70
|
+
]
|
|
49
71
|
}
|
|
50
72
|
]
|
|
51
73
|
}, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/createGlobalVersion.ts"],"sourcesContent":["import { buildVersionGlobalFields, type CreateGlobalVersion } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { getGlobal } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\nimport { transform } from './utilities/transform.js'\n\nexport const createGlobalVersion: CreateGlobalVersion = async function createGlobalVersion(\n this: MongooseAdapter,\n {\n autosave,\n createdAt,\n globalSlug,\n publishedLocale,\n req,\n returning,\n snapshot,\n updatedAt,\n versionData,\n },\n) {\n const { globalConfig, Model } = getGlobal({ adapter: this, globalSlug, versions: true })\n\n const data = {\n autosave,\n createdAt,\n latest: true,\n publishedLocale,\n snapshot,\n updatedAt,\n version: versionData,\n }\n if (!data.createdAt) {\n data.createdAt = new Date().toISOString()\n }\n\n const fields = buildVersionGlobalFields(this.payload.config, globalConfig)\n\n transform({\n adapter: this,\n data,\n fields,\n operation: 'write',\n })\n\n const options = {\n session: await getSession(this, req),\n // Timestamps are manually added by the write transform\n timestamps: false,\n }\n\n let [doc] = await Model.create([data], options, req)\n\n await Model.updateMany(\n {\n $and: [\n {\n _id: {\n $ne: doc._id,\n },\n },\n {\n latest: {\n $eq: true,\n },\n },\n ],\n },\n { $unset: { latest: 1 } },\n options,\n )\n\n if (returning === false) {\n return null\n }\n\n doc = doc.toObject()\n\n transform({\n adapter: this,\n data: doc,\n fields,\n operation: 'read',\n })\n\n return doc\n}\n"],"names":["buildVersionGlobalFields","getGlobal","getSession","transform","createGlobalVersion","autosave","createdAt","globalSlug","publishedLocale","req","returning","snapshot","updatedAt","versionData","globalConfig","Model","adapter","versions","data","latest","version","Date","toISOString","fields","
|
|
1
|
+
{"version":3,"sources":["../src/createGlobalVersion.ts"],"sourcesContent":["import { MAIN_BRANCH, resolveBranch } from 'payload'\nimport { buildVersionGlobalFields, type CreateGlobalVersion } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { getGlobal } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\nimport { transform } from './utilities/transform.js'\n\nexport const createGlobalVersion: CreateGlobalVersion = async function createGlobalVersion(\n this: MongooseAdapter,\n {\n autosave,\n createdAt,\n globalSlug,\n publishedLocale,\n req,\n returning,\n snapshot,\n updatedAt,\n versionData,\n },\n) {\n const { globalConfig, Model } = getGlobal({ adapter: this, globalSlug, versions: true })\n\n const versionBranch = req?.payload?.config?.branching?.branchableGlobals?.has(globalSlug)\n ? resolveBranch(req as never)\n : MAIN_BRANCH\n\n const data = {\n _branch: versionBranch,\n autosave,\n createdAt,\n latest: true,\n publishedLocale,\n snapshot,\n updatedAt,\n version: versionData,\n }\n if (!data.createdAt) {\n data.createdAt = new Date().toISOString()\n }\n\n const fields = buildVersionGlobalFields(this.payload.config, globalConfig)\n\n transform({\n adapter: this,\n data,\n fields,\n operation: 'write',\n })\n\n const options = {\n session: await getSession(this, req),\n // Timestamps are manually added by the write transform\n timestamps: false,\n }\n\n let [doc] = await Model.create([data], options, req)\n\n // Scoped by `_branch`. Unlike collection versions, global versions have no\n // `parent` to separate streams by — every version of a global shares one — so\n // without this an unscoped clear would wipe main's latest flag from a branch.\n await Model.updateMany(\n {\n $and: [\n {\n _id: {\n $ne: doc._id,\n },\n },\n {\n latest: {\n $eq: true,\n },\n },\n {\n $or: [\n { _branch: { $eq: versionBranch } },\n ...(versionBranch === MAIN_BRANCH ? [{ _branch: { $exists: false } }] : []),\n ],\n },\n ],\n },\n { $unset: { latest: 1 } },\n options,\n )\n\n if (returning === false) {\n return null\n }\n\n doc = doc.toObject()\n\n transform({\n adapter: this,\n data: doc,\n fields,\n operation: 'read',\n })\n\n return doc\n}\n"],"names":["MAIN_BRANCH","resolveBranch","buildVersionGlobalFields","getGlobal","getSession","transform","createGlobalVersion","autosave","createdAt","globalSlug","publishedLocale","req","returning","snapshot","updatedAt","versionData","globalConfig","Model","adapter","versions","versionBranch","payload","config","branching","branchableGlobals","has","data","_branch","latest","version","Date","toISOString","fields","operation","options","session","timestamps","doc","create","updateMany","$and","_id","$ne","$eq","$or","$exists","$unset","toObject"],"mappings":"AAAA,SAASA,WAAW,EAAEC,aAAa,QAAQ,UAAS;AACpD,SAASC,wBAAwB,QAAkC,UAAS;AAI5E,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAASC,UAAU,QAAQ,4BAA2B;AACtD,SAASC,SAAS,QAAQ,2BAA0B;AAEpD,OAAO,MAAMC,sBAA2C,eAAeA,oBAErE,EACEC,QAAQ,EACRC,S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AGF,IAAItB,cAAc,OAAO;QACvB,OAAO;IACT;IAEAyB,MAAMA,IAAIU,QAAQ;IAElB1C,UAAU;QACRa,SAAS,IAAI;QACbQ,MAAMW;QACNL;QACAC,WAAW;IACb;IAEA,OAAOI;AACT,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createVersion.d.ts","sourceRoot":"","sources":["../src/createVersion.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"createVersion.d.ts","sourceRoot":"","sources":["../src/createVersion.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,aAAa,EAEnB,MAAM,SAAS,CAAA;AAQhB,eAAO,MAAM,aAAa,EAAE,aAkH3B,CAAA"}
|
package/dist/createVersion.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { buildVersionCollectionFields } from 'payload';
|
|
1
|
+
import { buildVersionCollectionFields, resolveBranchVersionParent } from 'payload';
|
|
2
2
|
import { getCollection } from './utilities/getEntity.js';
|
|
3
3
|
import { getSession } from './utilities/getSession.js';
|
|
4
4
|
import { transform } from './utilities/transform.js';
|
|
@@ -8,15 +8,25 @@ export const createVersion = async function createVersion({ autosave, collection
|
|
|
8
8
|
collectionSlug,
|
|
9
9
|
versions: true
|
|
10
10
|
});
|
|
11
|
+
const branched = await resolveBranchVersionParent({
|
|
12
|
+
collectionSlug,
|
|
13
|
+
parent,
|
|
14
|
+
req,
|
|
15
|
+
versionData: versionData
|
|
16
|
+
});
|
|
11
17
|
const data = {
|
|
12
18
|
autosave,
|
|
13
19
|
createdAt,
|
|
14
20
|
latest: true,
|
|
15
|
-
parent,
|
|
21
|
+
parent: branched.parent,
|
|
16
22
|
publishedLocale,
|
|
17
23
|
snapshot,
|
|
18
24
|
updatedAt,
|
|
19
|
-
version: versionData
|
|
25
|
+
version: versionData,
|
|
26
|
+
...branched.versionData._branch ? {
|
|
27
|
+
_branch: branched.versionData._branch,
|
|
28
|
+
_branchParent: branched.versionData._branchParent
|
|
29
|
+
} : {}
|
|
20
30
|
};
|
|
21
31
|
if (!data.createdAt) {
|
|
22
32
|
data.createdAt = new Date().toISOString();
|
|
@@ -36,6 +46,9 @@ export const createVersion = async function createVersion({ autosave, collection
|
|
|
36
46
|
let [doc] = await Model.create([
|
|
37
47
|
data
|
|
38
48
|
], options, req);
|
|
49
|
+
// No branch scoping needed here: a branch version's `parent` is the shadow
|
|
50
|
+
// row's own primary key, so main's chain and the branch's chain are already
|
|
51
|
+
// disjoint and `latest` clearing cannot cross between them.
|
|
39
52
|
const parentQuery = {
|
|
40
53
|
$or: [
|
|
41
54
|
{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/createVersion.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../src/createVersion.ts"],"sourcesContent":["import {\n buildVersionCollectionFields,\n type CreateVersion,\n resolveBranchVersionParent,\n} from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { getCollection } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\nimport { transform } from './utilities/transform.js'\n\nexport const createVersion: CreateVersion = async function createVersion(\n this: MongooseAdapter,\n {\n autosave,\n collectionSlug,\n createdAt,\n parent,\n publishedLocale,\n req,\n returning,\n snapshot,\n updatedAt,\n versionData,\n },\n) {\n const { collectionConfig, Model } = getCollection({\n adapter: this,\n collectionSlug,\n versions: true,\n })\n\n const branched = await resolveBranchVersionParent({\n collectionSlug,\n parent,\n req,\n versionData: versionData as Record<string, unknown>,\n })\n\n const data = {\n autosave,\n createdAt,\n latest: true,\n parent: branched.parent,\n publishedLocale,\n snapshot,\n updatedAt,\n version: versionData,\n ...(branched.versionData._branch\n ? { _branch: branched.versionData._branch, _branchParent: branched.versionData._branchParent }\n : {}),\n }\n if (!data.createdAt) {\n data.createdAt = new Date().toISOString()\n }\n\n const fields = buildVersionCollectionFields(this.payload.config, collectionConfig)\n\n transform({\n adapter: this,\n data,\n fields,\n operation: 'write',\n })\n\n const options = {\n session: await getSession(this, req),\n // Timestamps are manually added by the write transform\n timestamps: false,\n }\n\n let [doc] = await Model.create([data], options, req)\n\n // No branch scoping needed here: a branch version's `parent` is the shadow\n // row's own primary key, so main's chain and the branch's chain are already\n // disjoint and `latest` clearing cannot cross between them.\n const parentQuery = {\n $or: [\n {\n parent: {\n $eq: data.parent,\n },\n },\n ],\n }\n\n await Model.updateMany(\n {\n $and: [\n {\n _id: {\n $ne: doc._id,\n },\n },\n parentQuery,\n {\n latest: {\n $eq: true,\n },\n },\n {\n updatedAt: {\n $lt: new Date(doc.updatedAt),\n },\n },\n ],\n },\n { $unset: { latest: 1 } },\n options,\n )\n\n if (returning === false) {\n return null\n }\n\n doc = doc.toObject()\n\n transform({\n adapter: this,\n data: doc,\n fields,\n operation: 'read',\n })\n\n return doc\n}\n"],"names":["buildVersionCollectionFields","resolveBranchVersionParent","getCollection","getSession","transform","createVersion","autosave","collectionSlug","createdAt","parent","publishedLocale","req","returning","snapshot","updatedAt","versionData","collectionConfig","Model","adapter","versions","branched","data","latest","version","_branch","_branchParent","Date","toISOString","fields","payload","config","operation","options","session","timestamps","doc","create","parentQuery","$or","$eq","updateMany","$and","_id","$ne","$lt","$unset","toObject"],"mappings":"AAAA,SACEA,4BAA4B,EAE5BC,0BAA0B,QACrB,UAAS;AAIhB,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,UAAU,QAAQ,4BAA2B;AACtD,SAASC,SAAS,QAAQ,2BAA0B;AAEpD,OAAO,MAAMC,gBAA+B,eAAeA,cAEzD,EACEC,QAAQ,EACRC,cAAc,EACdC,SAAS,EACTC,MAAM,EACNC,eAAe,EACfC,GAAG,EACHC,SAAS,EACTC,QAAQ,EACRC,SAAS,EACTC,WAAW,EACZ;IAED,MAAM,EAAEC,gBAAgB,EAAEC,KAAK,EAAE,GAAGf,cAAc;QAChDgB,SAAS,IAAI;QACbX;QACAY,UAAU;IACZ;IAEA,MAAMC,WAAW,MAAMnB,2B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UAAU;QACRc,SAAS,IAAI;QACbG,MAAMc;QACNP;QACAG,WAAW;IACb;IAEA,OAAOI;AACT,EAAC"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { DeleteBranchGlobal } from 'payload';
|
|
2
|
+
/**
|
|
3
|
+
* Drops a branch's copy of a global.
|
|
4
|
+
*
|
|
5
|
+
* Every global lives in one discriminated collection here, so the branch's copy is a
|
|
6
|
+
* sibling row identified by `globalType` and `_branch` — addressed directly rather than
|
|
7
|
+
* through any generic delete, since no other part of Payload deletes a global.
|
|
8
|
+
*/
|
|
9
|
+
export declare const deleteBranchGlobal: DeleteBranchGlobal;
|
|
10
|
+
//# sourceMappingURL=deleteBranchGlobal.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"deleteBranchGlobal.d.ts","sourceRoot":"","sources":["../src/deleteBranchGlobal.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAA;AAOjD;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,EAAE,kBAUhC,CAAA"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { getGlobal } from './utilities/getEntity.js';
|
|
2
|
+
import { getSession } from './utilities/getSession.js';
|
|
3
|
+
/**
|
|
4
|
+
* Drops a branch's copy of a global.
|
|
5
|
+
*
|
|
6
|
+
* Every global lives in one discriminated collection here, so the branch's copy is a
|
|
7
|
+
* sibling row identified by `globalType` and `_branch` — addressed directly rather than
|
|
8
|
+
* through any generic delete, since no other part of Payload deletes a global.
|
|
9
|
+
*/ export const deleteBranchGlobal = async function deleteBranchGlobal({ branch, globalSlug, req }) {
|
|
10
|
+
const { Model } = getGlobal({
|
|
11
|
+
adapter: this,
|
|
12
|
+
globalSlug
|
|
13
|
+
});
|
|
14
|
+
await Model.deleteOne({
|
|
15
|
+
_branch: branch,
|
|
16
|
+
globalType: globalSlug
|
|
17
|
+
}, {
|
|
18
|
+
session: await getSession(this, req)
|
|
19
|
+
});
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
//# sourceMappingURL=deleteBranchGlobal.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/deleteBranchGlobal.ts"],"sourcesContent":["import type { DeleteBranchGlobal } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { getGlobal } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\n\n/**\n * Drops a branch's copy of a global.\n *\n * Every global lives in one discriminated collection here, so the branch's copy is a\n * sibling row identified by `globalType` and `_branch` — addressed directly rather than\n * through any generic delete, since no other part of Payload deletes a global.\n */\nexport const deleteBranchGlobal: DeleteBranchGlobal = async function deleteBranchGlobal(\n this: MongooseAdapter,\n { branch, globalSlug, req },\n) {\n const { Model } = getGlobal({ adapter: this, globalSlug })\n\n await Model.deleteOne(\n { _branch: branch, globalType: globalSlug },\n { session: await getSession(this, req) },\n )\n}\n"],"names":["getGlobal","getSession","deleteBranchGlobal","branch","globalSlug","req","Model","adapter","deleteOne","_branch","globalType","session"],"mappings":"AAIA,SAASA,SAAS,QAAQ,2BAA0B;AACpD,SAASC,UAAU,QAAQ,4BAA2B;AAEtD;;;;;;CAMC,GACD,OAAO,MAAMC,qBAAyC,eAAeA,mBAEnE,EAAEC,MAAM,EAAEC,UAAU,EAAEC,GAAG,EAAE;IAE3B,MAAM,EAAEC,KAAK,EAAE,GAAGN,UAAU;QAAEO,SAAS,IAAI;QAAEH;IAAW;IAExD,MAAME,MAAME,SAAS,CACnB;QAAEC,SAASN;QAAQO,YAAYN;IAAW,GAC1C;QAAEO,SAAS,MAAMV,WAAW,IAAI,EAAEI;IAAK;AAE3C,EAAC"}
|
package/dist/deleteOne.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"deleteOne.d.ts","sourceRoot":"","sources":["../src/deleteOne.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"deleteOne.d.ts","sourceRoot":"","sources":["../src/deleteOne.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,SAAS,CAAA;AAYxC,eAAO,MAAM,SAAS,EAAE,SAmDvB,CAAA"}
|
package/dist/deleteOne.js
CHANGED
|
@@ -1,13 +1,30 @@
|
|
|
1
|
+
import { resolveBranchDelete } from 'payload';
|
|
1
2
|
import { buildQuery } from './queries/buildQuery.js';
|
|
2
3
|
import { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js';
|
|
3
4
|
import { getCollection } from './utilities/getEntity.js';
|
|
4
5
|
import { getSession } from './utilities/getSession.js';
|
|
5
6
|
import { transform } from './utilities/transform.js';
|
|
6
|
-
export const deleteOne = async function deleteOne({ collection: collectionSlug, req, returning, select, where }) {
|
|
7
|
+
export const deleteOne = async function deleteOne({ branch, collection: collectionSlug, req, returning, select, where }) {
|
|
7
8
|
const { collectionConfig, Model } = getCollection({
|
|
8
9
|
adapter: this,
|
|
9
10
|
collectionSlug
|
|
10
11
|
});
|
|
12
|
+
const branchDelete = await resolveBranchDelete({
|
|
13
|
+
branch,
|
|
14
|
+
collectionSlug,
|
|
15
|
+
req,
|
|
16
|
+
where
|
|
17
|
+
});
|
|
18
|
+
if (branchDelete.tombstoned) {
|
|
19
|
+
return returning === false ? null : branchDelete.doc;
|
|
20
|
+
}
|
|
21
|
+
if (branchDelete.deleteRowID !== undefined) {
|
|
22
|
+
where = {
|
|
23
|
+
id: {
|
|
24
|
+
equals: branchDelete.deleteRowID
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
}
|
|
11
28
|
const query = await buildQuery({
|
|
12
29
|
adapter: this,
|
|
13
30
|
collectionSlug,
|
package/dist/deleteOne.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/deleteOne.ts"],"sourcesContent":["import type { QueryOptions } from 'mongoose'\nimport type { DeleteOne } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { buildQuery } from './queries/buildQuery.js'\nimport { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js'\nimport { getCollection } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\nimport { transform } from './utilities/transform.js'\n\nexport const deleteOne: DeleteOne = async function deleteOne(\n this: MongooseAdapter,\n { collection: collectionSlug, req, returning, select, where },\n) {\n const { collectionConfig, Model } = getCollection({ adapter: this, collectionSlug })\n\n const query = await buildQuery({\n adapter: this,\n collectionSlug,\n fields: collectionConfig.flattenedFields,\n where,\n })\n\n const options = {\n projection: buildProjectionFromSelect({\n adapter: this,\n fields: collectionConfig.flattenedFields,\n select,\n }),\n session: await getSession(this, req),\n } satisfies QueryOptions\n\n if (returning === false) {\n await Model.deleteOne(query, options)?.lean()\n return null\n }\n\n const doc = await Model.findOneAndDelete(query, options)?.lean()\n\n if (!doc) {\n return null\n }\n\n transform({\n adapter: this,\n data: doc,\n fields: collectionConfig.fields,\n operation: 'read',\n })\n\n return doc\n}\n"],"names":["buildQuery","buildProjectionFromSelect","getCollection","getSession","transform","deleteOne","collection","collectionSlug","req","returning","select","where","collectionConfig","Model","adapter","query","fields","flattenedFields","options","projection","session","lean","
|
|
1
|
+
{"version":3,"sources":["../src/deleteOne.ts"],"sourcesContent":["import type { QueryOptions } from 'mongoose'\nimport type { DeleteOne } from 'payload'\n\nimport { resolveBranchDelete } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { buildQuery } from './queries/buildQuery.js'\nimport { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js'\nimport { getCollection } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\nimport { transform } from './utilities/transform.js'\n\nexport const deleteOne: DeleteOne = async function deleteOne(\n this: MongooseAdapter,\n { branch, collection: collectionSlug, req, returning, select, where },\n) {\n const { collectionConfig, Model } = getCollection({ adapter: this, collectionSlug })\n\n const branchDelete = await resolveBranchDelete({ branch, collectionSlug, req, where })\n\n if (branchDelete.tombstoned) {\n return returning === false ? null : (branchDelete.doc as any)\n }\n\n if (branchDelete.deleteRowID !== undefined) {\n where = { id: { equals: branchDelete.deleteRowID } }\n }\n\n const query = await buildQuery({\n adapter: this,\n collectionSlug,\n fields: collectionConfig.flattenedFields,\n where,\n })\n\n const options = {\n projection: buildProjectionFromSelect({\n adapter: this,\n fields: collectionConfig.flattenedFields,\n select,\n }),\n session: await getSession(this, req),\n } satisfies QueryOptions\n\n if (returning === false) {\n await Model.deleteOne(query, options)?.lean()\n return null\n }\n\n const doc = await Model.findOneAndDelete(query, options)?.lean()\n\n if (!doc) {\n return null\n }\n\n transform({\n adapter: this,\n data: doc,\n fields: collectionConfig.fields,\n operation: 'read',\n })\n\n return doc\n}\n"],"names":["resolveBranchDelete","buildQuery","buildProjectionFromSelect","getCollection","getSession","transform","deleteOne","branch","collection","collectionSlug","req","returning","select","where","collectionConfig","Model","adapter","branchDelete","tombstoned","doc","deleteRowID","undefined","id","equals","query","fields","flattenedFields","options","projection","session","lean","findOneAndDelete","data","operation"],"mappings":"AAGA,SAASA,mBAAmB,QAAQ,UAAS;AAI7C,SAASC,UAAU,QAAQ,0BAAyB;AACpD,SAASC,yBAAyB,QAAQ,2CAA0C;AACpF,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,UAAU,QAAQ,4BAA2B;AACtD,SAASC,SAAS,QAAQ,2BAA0B;AAEpD,OAAO,MAAMC,YAAuB,eAAeA,UAEjD,EAAEC,MAAM,EAAEC,YAAYC,cAAc,EAAEC,GAAG,EAAEC,SAAS,EAAEC,MAAM,EAAEC,KAAK,EAAE;IAErE,MAAM,EAAEC,gBAAgB,EAAEC,KAAK,EAAE,GAAGZ,cAAc;QAAEa,SAAS,IAAI;QAAEP;IAAe;IAElF,MAAMQ,eAAe,MAAMjB,oBAAoB;QAAEO;QAAQE;QAAgBC;QAAKG;IAAM;IAEpF,IAAII,aAAaC,UAAU,EAAE;QAC3B,OAAOP,cAAc,QAAQ,OAAQM,aAAaE,GAAG;IACvD;IAEA,IAAIF,aAAaG,WAAW,KAAKC,WAAW;QAC1CR,QAAQ;YAAES,IAAI;gBAAEC,QAAQN,aAAaG,WAAW;YAAC;QAAE;IACrD;IAEA,MAAMI,QAAQ,MAAMvB,WAAW;QAC7Be,SAAS,IAAI;QACbP;QACAgB,QAAQX,iBAAiBY,eAAe;QACxCb;IACF;IAEA,MAAMc,UAAU;QACdC,YAAY1B,0BAA0B;YACpCc,SAAS,IAAI;YACbS,QAAQX,iBAAiBY,eAAe;YACxCd;QACF;QACAiB,SAAS,MAAMzB,WAAW,IAAI,EAAEM;IAClC;IAEA,IAAIC,cAAc,OAAO;QACvB,MAAMI,MAAMT,SAAS,CAACkB,OAAOG,UAAUG;QACvC,OAAO;IACT;IAEA,MAAMX,MAAM,MAAMJ,MAAMgB,gBAAgB,CAACP,OAAOG,UAAUG;IAE1D,IAAI,CAACX,KAAK;QACR,OAAO;IACT;IAEAd,UAAU;QACRW,SAAS,IAAI;QACbgB,MAAMb;QACNM,QAAQX,iBAAiBW,MAAM;QAC/BQ,WAAW;IACb;IAEA,OAAOd;AACT,EAAC"}
|
package/dist/find.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"find.d.ts","sourceRoot":"","sources":["../src/find.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"find.d.ts","sourceRoot":"","sources":["../src/find.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,SAAS,CAAA;AAqBnC,eAAO,MAAM,IAAI,EAAE,IA8LlB,CAAA"}
|
package/dist/find.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { flattenWhereToOperators } from 'payload';
|
|
1
|
+
import { applyBranchIDProjection, flattenWhereToOperators, resolveBranchQuery, withBranchIDSelect } from 'payload';
|
|
2
2
|
import { buildQuery } from './queries/buildQuery.js';
|
|
3
3
|
import { buildSortParam } from './queries/buildSortParam.js';
|
|
4
4
|
import { aggregatePaginate } from './utilities/aggregatePaginate.js';
|
|
@@ -8,11 +8,17 @@ import { getCollection } from './utilities/getEntity.js';
|
|
|
8
8
|
import { getSession } from './utilities/getSession.js';
|
|
9
9
|
import { resolveJoins } from './utilities/resolveJoins.js';
|
|
10
10
|
import { transform } from './utilities/transform.js';
|
|
11
|
-
export const find = async function find({ collection: collectionSlug, draftsEnabled, joins = {}, limit = 0, locale, page, pagination, projection, req, select, sort: sortArg, where = {} }) {
|
|
11
|
+
export const find = async function find({ branch, collection: collectionSlug, draftsEnabled, joins = {}, limit = 0, locale, page, pagination, projection, req, select, sort: sortArg, where = {} }) {
|
|
12
12
|
const { collectionConfig, Model } = getCollection({
|
|
13
13
|
adapter: this,
|
|
14
14
|
collectionSlug
|
|
15
15
|
});
|
|
16
|
+
where = await resolveBranchQuery({
|
|
17
|
+
branch,
|
|
18
|
+
collectionSlug,
|
|
19
|
+
req,
|
|
20
|
+
where
|
|
21
|
+
}) ?? {};
|
|
16
22
|
let hasNearConstraint = false;
|
|
17
23
|
if (where) {
|
|
18
24
|
const constraints = flattenWhereToOperators(where);
|
|
@@ -53,11 +59,17 @@ export const find = async function find({ collection: collectionSlug, draftsEnab
|
|
|
53
59
|
sort,
|
|
54
60
|
useEstimatedCount
|
|
55
61
|
};
|
|
56
|
-
|
|
62
|
+
const selectWithBranchID = withBranchIDSelect({
|
|
63
|
+
branch,
|
|
64
|
+
collectionSlug,
|
|
65
|
+
req,
|
|
66
|
+
select
|
|
67
|
+
});
|
|
68
|
+
if (selectWithBranchID) {
|
|
57
69
|
paginationOptions.projection = buildProjectionFromSelect({
|
|
58
70
|
adapter: this,
|
|
59
71
|
fields: collectionConfig.flattenedFields,
|
|
60
|
-
select
|
|
72
|
+
select: selectWithBranchID
|
|
61
73
|
});
|
|
62
74
|
}
|
|
63
75
|
if (this.collation) {
|
|
@@ -112,7 +124,8 @@ export const find = async function find({ collection: collectionSlug, draftsEnab
|
|
|
112
124
|
joins,
|
|
113
125
|
locale,
|
|
114
126
|
projection: paginationOptions.projection,
|
|
115
|
-
query
|
|
127
|
+
query,
|
|
128
|
+
req
|
|
116
129
|
});
|
|
117
130
|
if (aggregate || sortAggregation.length > 0) {
|
|
118
131
|
result = await aggregatePaginate({
|
|
@@ -148,6 +161,12 @@ export const find = async function find({ collection: collectionSlug, draftsEnab
|
|
|
148
161
|
fields: collectionConfig.fields,
|
|
149
162
|
operation: 'read'
|
|
150
163
|
});
|
|
164
|
+
applyBranchIDProjection({
|
|
165
|
+
branch,
|
|
166
|
+
collectionSlug,
|
|
167
|
+
docs: result.docs,
|
|
168
|
+
req
|
|
169
|
+
});
|
|
151
170
|
return result;
|
|
152
171
|
};
|
|
153
172
|
|
package/dist/find.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/find.ts"],"sourcesContent":["import type { PaginateOptions, PipelineStage } from 'mongoose'\nimport type { Find } from 'payload'\n\nimport { flattenWhereToOperators } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { buildQuery } from './queries/buildQuery.js'\nimport { buildSortParam } from './queries/buildSortParam.js'\nimport { aggregatePaginate } from './utilities/aggregatePaginate.js'\nimport { buildJoinAggregation } from './utilities/buildJoinAggregation.js'\nimport { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js'\nimport { getCollection } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\nimport { resolveJoins } from './utilities/resolveJoins.js'\nimport { transform } from './utilities/transform.js'\n\nexport const find: Find = async function find(\n this: MongooseAdapter,\n {\n collection: collectionSlug,\n draftsEnabled,\n joins = {},\n limit = 0,\n locale,\n page,\n pagination,\n projection,\n req,\n select,\n sort: sortArg,\n where = {},\n },\n) {\n const { collectionConfig, Model } = getCollection({ adapter: this, collectionSlug })\n\n let hasNearConstraint = false\n\n if (where) {\n const constraints = flattenWhereToOperators(where)\n hasNearConstraint = constraints.some((prop) => Object.keys(prop).some((key) => key === 'near'))\n }\n\n const sortAggregation: PipelineStage[] = []\n\n let sort\n if (!hasNearConstraint) {\n sort = buildSortParam({\n adapter: this,\n config: this.payload.config,\n fields: collectionConfig.flattenedFields,\n locale,\n sort: sortArg || collectionConfig.defaultSort,\n sortAggregation,\n timestamps: collectionConfig.timestamps || false,\n })\n }\n\n const query = await buildQuery({\n adapter: this,\n collectionSlug,\n fields: collectionConfig.flattenedFields,\n locale,\n where,\n })\n\n const session = await getSession(this, req)\n\n // useEstimatedCount is faster, but not accurate, as it ignores any filters. It is thus set to true if there are no filters.\n const useEstimatedCount = hasNearConstraint || !query || Object.keys(query).length === 0\n const paginationOptions: PaginateOptions = {\n lean: true,\n leanWithId: true,\n options: {\n session,\n },\n page,\n pagination,\n projection,\n sort,\n useEstimatedCount,\n }\n\n if (select) {\n paginationOptions.projection = buildProjectionFromSelect({\n adapter: this,\n fields: collectionConfig.flattenedFields,\n select,\n })\n }\n\n if (this.collation) {\n const localizationConfig = this.payload.config.localization\n const defaultLocale =\n (typeof localizationConfig === 'object' && localizationConfig?.defaultLocale) || 'en'\n\n paginationOptions.collation = {\n locale: locale && locale !== 'all' && locale !== '*' ? locale : defaultLocale,\n ...this.collation,\n }\n }\n\n if (!useEstimatedCount && Object.keys(query).length === 0 && this.disableIndexHints !== true) {\n // Improve the performance of the countDocuments query which is used if useEstimatedCount is set to false by adding\n // a hint. By default, if no hint is provided, MongoDB does not use an indexed field to count the returned documents,\n // which makes queries very slow. This only happens when no query (filter) is provided. If one is provided, it uses\n // the correct indexed field\n paginationOptions.useCustomCountFn = () => {\n return Promise.resolve(\n Model.countDocuments(query, {\n collation: paginationOptions.collation,\n hint: { _id: 1 },\n session,\n }),\n )\n }\n } else if (!useEstimatedCount && this.collation) {\n // Workaround for mongoose-paginate-v2 bug: chaining .collation() on countDocuments breaks\n // session context in transactions (mongoose 8.x). Provide custom count function that passes\n // collation as an option instead. See: https://github.com/aravindnc/mongoose-paginate-v2/pull/240\n // TODO: Remove this workaround once mongoose-paginate-v2 is updated with the fix.\n paginationOptions.useCustomCountFn = () => {\n return Promise.resolve(\n Model.countDocuments(query, {\n collation: paginationOptions.collation,\n session,\n }),\n )\n }\n }\n\n if (limit >= 0) {\n paginationOptions.limit = limit\n // limit must also be set here, it's ignored when pagination is false\n\n paginationOptions.options!.limit = limit\n\n // Disable pagination if limit is 0\n if (limit === 0) {\n paginationOptions.pagination = false\n }\n }\n\n let result\n\n const aggregate = await buildJoinAggregation({\n adapter: this,\n collection: collectionSlug,\n collectionConfig,\n draftsEnabled,\n joins,\n locale,\n projection: paginationOptions.projection,\n query,\n })\n\n if (aggregate || sortAggregation.length > 0) {\n result = await aggregatePaginate({\n adapter: this,\n collation: paginationOptions.collation,\n joinAggregation: aggregate,\n limit: paginationOptions.limit,\n Model,\n page: paginationOptions.page,\n pagination: paginationOptions.pagination,\n projection: paginationOptions.projection,\n query,\n session: paginationOptions.options?.session ?? undefined,\n sort: paginationOptions.sort as object,\n sortAggregation,\n useEstimatedCount: paginationOptions.useEstimatedCount,\n })\n } else {\n result = await Model.paginate(query, paginationOptions)\n }\n\n if (!this.useJoinAggregations) {\n await resolveJoins({\n adapter: this,\n collectionSlug,\n docs: result.docs as Record<string, unknown>[],\n joins,\n locale,\n })\n }\n\n transform({\n adapter: this,\n data: result.docs,\n fields: collectionConfig.fields,\n operation: 'read',\n })\n\n return result\n}\n"],"names":["flattenWhereToOperators","buildQuery","buildSortParam","aggregatePaginate","buildJoinAggregation","buildProjectionFromSelect","getCollection","getSession","resolveJoins","transform","find","collection","collectionSlug","draftsEnabled","joins","limit","locale","page","pagination","projection","req","select","sort","sortArg","where","collectionConfig","Model","adapter","hasNearConstraint","constraints","some","prop","Object","keys","key","sortAggregation","config","payload","fields","flattenedFields","defaultSort","timestamps","query","session","useEstimatedCount","length","paginationOptions","lean","leanWithId","options","collation","localizationConfig","localization","defaultLocale","disableIndexHints","useCustomCountFn","Promise","resolve","countDocuments","hint","_id","result","aggregate","joinAggregation","undefined","paginate","useJoinAggregations","docs","data","operation"],"mappings":"AAGA,SAASA,uBAAuB,QAAQ,UAAS;AAIjD,SAASC,UAAU,QAAQ,0BAAyB;AACpD,SAASC,cAAc,QAAQ,8BAA6B;AAC5D,SAASC,iBAAiB,QAAQ,mCAAkC;AACpE,SAASC,oBAAoB,QAAQ,sCAAqC;AAC1E,SAASC,yBAAyB,QAAQ,2CAA0C;AACpF,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,UAAU,QAAQ,4BAA2B;AACtD,SAASC,YAAY,QAAQ,8BAA6B;AAC1D,SAASC,SAAS,QAAQ,2BAA0B;AAEpD,OAAO,MAAMC,OAAa,eAAeA,KAEvC,EACEC,YAAYC,cAAc,EAC1BC,aAAa,EACbC,QAAQ,CAAC,CAAC,EACVC,QAAQ,CAAC,EACTC,MAAM,EACNC,IAAI,EACJC,UAAU,EACVC,UAAU,EACVC,GAAG,EACHC,MAAM,EACNC,MAAMC,OAAO,EACbC,QAAQ,CAAC,CAAC,EACX;IAED,MAAM,EAAEC,gBAAgB,EAAEC,KAAK,EAAE,GAAGpB,cAAc;QAAEqB,SAAS,IAAI;QAAEf;IAAe;IAElF,IAAIgB,oBAAoB;IAExB,IAAIJ,OAAO;QACT,MAAMK,cAAc7B,wBAAwBwB;QAC5CI,oBAAoBC,YAAYC,IAAI,CAAC,CAACC,OAASC,OAAOC,IAAI,CAACF,MAAMD,IAAI,CAAC,CAACI,MAAQA,QAAQ;IACzF;IAEA,MAAMC,kBAAmC,EAAE;IAE3C,IAAIb;IACJ,IAAI,CAACM,mBAAmB;QACtBN,OAAOpB,eAAe;YACpByB,SAAS,IAAI;YACbS,QAAQ,IAAI,CAACC,OAAO,CAACD,MAAM;YAC3BE,QAAQb,iBAAiBc,eAAe;YACxCvB;YACAM,MAAMC,WAAWE,iBAAiBe,WAAW;YAC7CL;YACAM,YAA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P,UAAU;QACRkB,SAAS,IAAI;QACbyC,MAAMP,OAAOM,IAAI;QACjB7B,QAAQb,iBAAiBa,MAAM;QAC/B+B,WAAW;IACb;IAEA,OAAOR;AACT,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../src/find.ts"],"sourcesContent":["import type { PaginateOptions, PipelineStage } from 'mongoose'\nimport type { Find } from 'payload'\n\nimport {\n applyBranchIDProjection,\n flattenWhereToOperators,\n resolveBranchQuery,\n withBranchIDSelect,\n} from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { buildQuery } from './queries/buildQuery.js'\nimport { buildSortParam } from './queries/buildSortParam.js'\nimport { aggregatePaginate } from './utilities/aggregatePaginate.js'\nimport { buildJoinAggregation } from './utilities/buildJoinAggregation.js'\nimport { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js'\nimport { getCollection } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\nimport { resolveJoins } from './utilities/resolveJoins.js'\nimport { transform } from './utilities/transform.js'\n\nexport const find: Find = async function find(\n this: MongooseAdapter,\n {\n branch,\n collection: collectionSlug,\n draftsEnabled,\n joins = {},\n limit = 0,\n locale,\n page,\n pagination,\n projection,\n req,\n select,\n sort: sortArg,\n where = {},\n },\n) {\n const { collectionConfig, Model } = getCollection({ adapter: this, collectionSlug })\n\n where = (await resolveBranchQuery({ branch, collectionSlug, req, where })) ?? {}\n\n let hasNearConstraint = false\n\n if (where) {\n const constraints = flattenWhereToOperators(where)\n hasNearConstraint = constraints.some((prop) => Object.keys(prop).some((key) => key === 'near'))\n }\n\n const sortAggregation: PipelineStage[] = []\n\n let sort\n if (!hasNearConstraint) {\n sort = buildSortParam({\n adapter: this,\n config: this.payload.config,\n fields: collectionConfig.flattenedFields,\n locale,\n sort: sortArg || collectionConfig.defaultSort,\n sortAggregation,\n timestamps: collectionConfig.timestamps || false,\n })\n }\n\n const query = await buildQuery({\n adapter: this,\n collectionSlug,\n fields: collectionConfig.flattenedFields,\n locale,\n where,\n })\n\n const session = await getSession(this, req)\n\n // useEstimatedCount is faster, but not accurate, as it ignores any filters. It is thus set to true if there are no filters.\n const useEstimatedCount = hasNearConstraint || !query || Object.keys(query).length === 0\n const paginationOptions: PaginateOptions = {\n lean: true,\n leanWithId: true,\n options: {\n session,\n },\n page,\n pagination,\n projection,\n sort,\n useEstimatedCount,\n }\n\n const selectWithBranchID = withBranchIDSelect({ branch, collectionSlug, req, select })\n\n if (selectWithBranchID) {\n paginationOptions.projection = buildProjectionFromSelect({\n adapter: this,\n fields: collectionConfig.flattenedFields,\n select: selectWithBranchID,\n })\n }\n\n if (this.collation) {\n const localizationConfig = this.payload.config.localization\n const defaultLocale =\n (typeof localizationConfig === 'object' && localizationConfig?.defaultLocale) || 'en'\n\n paginationOptions.collation = {\n locale: locale && locale !== 'all' && locale !== '*' ? locale : defaultLocale,\n ...this.collation,\n }\n }\n\n if (!useEstimatedCount && Object.keys(query).length === 0 && this.disableIndexHints !== true) {\n // Improve the performance of the countDocuments query which is used if useEstimatedCount is set to false by adding\n // a hint. By default, if no hint is provided, MongoDB does not use an indexed field to count the returned documents,\n // which makes queries very slow. This only happens when no query (filter) is provided. If one is provided, it uses\n // the correct indexed field\n paginationOptions.useCustomCountFn = () => {\n return Promise.resolve(\n Model.countDocuments(query, {\n collation: paginationOptions.collation,\n hint: { _id: 1 },\n session,\n }),\n )\n }\n } else if (!useEstimatedCount && this.collation) {\n // Workaround for mongoose-paginate-v2 bug: chaining .collation() on countDocuments breaks\n // session context in transactions (mongoose 8.x). Provide custom count function that passes\n // collation as an option instead. See: https://github.com/aravindnc/mongoose-paginate-v2/pull/240\n // TODO: Remove this workaround once mongoose-paginate-v2 is updated with the fix.\n paginationOptions.useCustomCountFn = () => {\n return Promise.resolve(\n Model.countDocuments(query, {\n collation: paginationOptions.collation,\n session,\n }),\n )\n }\n }\n\n if (limit >= 0) {\n paginationOptions.limit = limit\n // limit must also be set here, it's ignored when pagination is false\n\n paginationOptions.options!.limit = limit\n\n // Disable pagination if limit is 0\n if (limit === 0) {\n paginationOptions.pagination = false\n }\n }\n\n let result\n\n const aggregate = await buildJoinAggregation({\n adapter: this,\n collection: collectionSlug,\n collectionConfig,\n draftsEnabled,\n joins,\n locale,\n projection: paginationOptions.projection,\n query,\n req,\n })\n\n if (aggregate || sortAggregation.length > 0) {\n result = await aggregatePaginate({\n adapter: this,\n collation: paginationOptions.collation,\n joinAggregation: aggregate,\n limit: paginationOptions.limit,\n Model,\n page: paginationOptions.page,\n pagination: paginationOptions.pagination,\n projection: paginationOptions.projection,\n query,\n session: paginationOptions.options?.session ?? undefined,\n sort: paginationOptions.sort as object,\n sortAggregation,\n useEstimatedCount: paginationOptions.useEstimatedCount,\n })\n } else {\n result = await Model.paginate(query, paginationOptions)\n }\n\n if (!this.useJoinAggregations) {\n await resolveJoins({\n adapter: this,\n collectionSlug,\n docs: result.docs as Record<string, unknown>[],\n joins,\n locale,\n })\n }\n\n transform({\n adapter: this,\n data: result.docs,\n fields: collectionConfig.fields,\n operation: 'read',\n })\n\n applyBranchIDProjection({\n branch,\n collectionSlug,\n docs: result.docs as Record<string, unknown>[],\n req,\n })\n\n return result\n}\n"],"names":["applyBranchIDProjection","flattenWhereToOperators","resolveBranchQuery","withBranchIDSelect","buildQuery","buildSortParam","aggregatePaginate","buildJoinAggregation","buildProjectionFromSelect","getCollection","getSession","resolveJoins","transform","find","branch","collection","collectionSlug","draftsEnabled","joins","limit","locale","page","pagination","projection","req","select","sort","sortArg","where","collectionConfig","Model","adapter","hasNearConstraint","constraints","some","prop","Object","keys","key","sortAggregation","config","payload","fields","flattenedFields","defaultSort","timestamps","query","session","useEstimatedCount","length","paginationOptions","lean","leanWithId","options","selectWithBranchID","collation","localizationConfig","localization","defaultLocale","disableIndexHints","useCustomCountFn","Promise","resolve","countDocuments","hint","_id","result","aggregate","joinAggregation","undefined","paginate","useJoinAggregations","docs","data","operation"],"mappings":"AAGA,SACEA,uBAAuB,EACvBC,uBAAuB,EACvBC,kBA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ACbf;YACAwD,MAAMN,OAAOM,IAAI;YACjBtD;YACAE;QACF;IACF;IAEAR,UAAU;QACRmB,SAAS,IAAI;QACb0C,MAAMP,OAAOM,IAAI;QACjB9B,QAAQb,iBAAiBa,MAAM;QAC/BgC,WAAW;IACb;IAEA1E,wBAAwB;QACtBc;QACAE;QACAwD,MAAMN,OAAOM,IAAI;QACjBhD;IACF;IAEA,OAAO0C;AACT,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,YA+Q1B,CAAA"}
|
package/dist/findDistinct.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getFieldByPath } from 'payload';
|
|
1
|
+
import { getFieldByPath, resolveBranchQuery } from 'payload';
|
|
2
2
|
import { buildQuery } from './queries/buildQuery.js';
|
|
3
3
|
import { buildSortParam } from './queries/buildSortParam.js';
|
|
4
4
|
import { getCollection } from './utilities/getEntity.js';
|
|
@@ -29,7 +29,15 @@ export const findDistinct = async function(args) {
|
|
|
29
29
|
adapter: this,
|
|
30
30
|
collectionSlug: args.collection
|
|
31
31
|
});
|
|
32
|
-
|
|
32
|
+
// Distinct values describe the documents the caller can see, so they are subject to
|
|
33
|
+
// the same branch predicate as a list read. Without it a branch's shadow rows fed
|
|
34
|
+
// main's distinct values and the branch's own edits were invisible in its own.
|
|
35
|
+
const where = await resolveBranchQuery({
|
|
36
|
+
branch: args.branch,
|
|
37
|
+
collectionSlug: args.collection,
|
|
38
|
+
req: args.req,
|
|
39
|
+
where: args.where
|
|
40
|
+
}) ?? {};
|
|
33
41
|
let sortAggregation = [];
|
|
34
42
|
const sort = buildSortParam({
|
|
35
43
|
adapter: this,
|
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,SAASA,cA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AV,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, resolveBranchQuery } 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 // Distinct values describe the documents the caller can see, so they are subject to\n // the same branch predicate as a list read. Without it a branch's shadow rows fed\n // main's distinct values and the branch's own edits were invisible in its own.\n const where =\n (await resolveBranchQuery({\n branch: args.branch,\n collectionSlug: args.collection,\n req: args.req,\n where: args.where,\n })) ?? {}\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","resolveBranchQuery","buildQuery","buildSortParam","getCollection","getSession","sanitizeGroupID","id","_field","getSortAggregation","fieldPath","hasSortAggregationAndHasMany","sortDirection","sortProperty","resolvedSortProperty","findDistinct","args","collectionConfig","Model","adapter","collectionSlug","collection","where","branch","req","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","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,SAASA,cAAc,EAAEC,kBAAkB,QAAQ,UAAS;AAI5D,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;IAC9D;IAEA,OAAO;QAAE,CAAC,GAAGI,sBAAsB,CAAC,EAAEF;IAAc;AACtD;AAEA,OAAO,MAAMG,eAA6B,eAAuCC,IAAI;IACnF,MAAM,EAAEC,gBAAgB,EAAEC,KAAK,EAAE,GAAGd,cAAc;QAChDe,SAAS,IAAI;QACbC,gBAAgBJ,KAAKK,UAAU;IACjC;IAEA,oFAAoF;IACpF,kFAAkF;IAClF,+EAA+E;IAC/E,MAAMC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