diff --git a/packages/db-mongodb/src/count.ts b/packages/db-mongodb/src/count.ts index 17622cf4c5a..7d313461bbb 100644 --- a/packages/db-mongodb/src/count.ts +++ b/packages/db-mongodb/src/count.ts @@ -1,18 +1,20 @@ import type { CountOptions } from 'mongodb' -import type { Count, PayloadRequest } from 'payload' +import type { Count } from 'payload' import { flattenWhereToOperators } from 'payload' import type { MongooseAdapter } from './index.js' -import { withSession } from './withSession.js' +import { getSession } from './utilities/getSession.js' export const count: Count = async function count( this: MongooseAdapter, - { collection, locale, req = {} as PayloadRequest, where }, + { collection, locale, req, where }, ) { const Model = this.collections[collection] - const options: CountOptions = await withSession(this, req) + const options: CountOptions = { + session: await getSession(this, req), + } let hasNearConstraint = false diff --git a/packages/db-mongodb/src/countGlobalVersions.ts b/packages/db-mongodb/src/countGlobalVersions.ts index 48cf67cb899..296f2ca0771 100644 --- a/packages/db-mongodb/src/countGlobalVersions.ts +++ b/packages/db-mongodb/src/countGlobalVersions.ts @@ -1,18 +1,20 @@ import type { CountOptions } from 'mongodb' -import type { CountGlobalVersions, PayloadRequest } from 'payload' +import type { CountGlobalVersions } from 'payload' import { flattenWhereToOperators } from 'payload' import type { MongooseAdapter } from './index.js' -import { withSession } from './withSession.js' +import { getSession } from './utilities/getSession.js' export const countGlobalVersions: CountGlobalVersions = async function countGlobalVersions( this: MongooseAdapter, - { global, locale, req = {} as PayloadRequest, where }, + { global, locale, req, where }, ) { const Model = this.versions[global] - const options: CountOptions = await withSession(this, req) + const options: CountOptions = { + session: await getSession(this, req), + } let hasNearConstraint = false diff --git a/packages/db-mongodb/src/countVersions.ts b/packages/db-mongodb/src/countVersions.ts index 6c7633e26a0..0b91f94ac65 100644 --- a/packages/db-mongodb/src/countVersions.ts +++ b/packages/db-mongodb/src/countVersions.ts @@ -1,18 +1,20 @@ import type { CountOptions } from 'mongodb' -import type { CountVersions, PayloadRequest } from 'payload' +import type { CountVersions } from 'payload' import { flattenWhereToOperators } from 'payload' import type { MongooseAdapter } from './index.js' -import { withSession } from './withSession.js' +import { getSession } from './utilities/getSession.js' export const countVersions: CountVersions = async function countVersions( this: MongooseAdapter, - { collection, locale, req = {} as PayloadRequest, where }, + { collection, locale, req, where }, ) { const Model = this.versions[collection] - const options: CountOptions = await withSession(this, req) + const options: CountOptions = { + session: await getSession(this, req), + } let hasNearConstraint = false diff --git a/packages/db-mongodb/src/create.ts b/packages/db-mongodb/src/create.ts index 504cffd854a..49e549b7e47 100644 --- a/packages/db-mongodb/src/create.ts +++ b/packages/db-mongodb/src/create.ts @@ -1,17 +1,21 @@ -import type { Create, Document, PayloadRequest } from 'payload' +import type { CreateOptions } from 'mongoose' +import type { Create, Document } from 'payload' import type { MongooseAdapter } from './index.js' +import { getSession } from './utilities/getSession.js' import { handleError } from './utilities/handleError.js' import { sanitizeRelationshipIDs } from './utilities/sanitizeRelationshipIDs.js' -import { withSession } from './withSession.js' export const create: Create = async function create( this: MongooseAdapter, - { collection, data, req = {} as PayloadRequest }, + { collection, data, req }, ) { const Model = this.collections[collection] - const options = await withSession(this, req) + const options: CreateOptions = { + session: await getSession(this, req), + } + let doc const sanitizedData = sanitizeRelationshipIDs({ diff --git a/packages/db-mongodb/src/createGlobal.ts b/packages/db-mongodb/src/createGlobal.ts index d57c180f33d..969eeaed7ca 100644 --- a/packages/db-mongodb/src/createGlobal.ts +++ b/packages/db-mongodb/src/createGlobal.ts @@ -1,14 +1,15 @@ -import type { CreateGlobal, PayloadRequest } from 'payload' +import type { CreateOptions } from 'mongoose' +import type { CreateGlobal } from 'payload' import type { MongooseAdapter } from './index.js' +import { getSession } from './utilities/getSession.js' import { sanitizeInternalFields } from './utilities/sanitizeInternalFields.js' import { sanitizeRelationshipIDs } from './utilities/sanitizeRelationshipIDs.js' -import { withSession } from './withSession.js' export const createGlobal: CreateGlobal = async function createGlobal( this: MongooseAdapter, - { slug, data, req = {} as PayloadRequest }, + { slug, data, req }, ) { const Model = this.globals @@ -21,7 +22,9 @@ export const createGlobal: CreateGlobal = async function createGlobal( fields: this.payload.config.globals.find((globalConfig) => globalConfig.slug === slug).fields, }) - const options = await withSession(this, req) + const options: CreateOptions = { + session: await getSession(this, req), + } let [result] = (await Model.create([global], options)) as any diff --git a/packages/db-mongodb/src/createGlobalVersion.ts b/packages/db-mongodb/src/createGlobalVersion.ts index c149b7882f7..a6fe7ccb5f4 100644 --- a/packages/db-mongodb/src/createGlobalVersion.ts +++ b/packages/db-mongodb/src/createGlobalVersion.ts @@ -1,14 +1,11 @@ -import { - buildVersionGlobalFields, - type CreateGlobalVersion, - type Document, - type PayloadRequest, -} from 'payload' +import type { CreateOptions } from 'mongoose' + +import { buildVersionGlobalFields, type CreateGlobalVersion, type Document } from 'payload' import type { MongooseAdapter } from './index.js' +import { getSession } from './utilities/getSession.js' import { sanitizeRelationshipIDs } from './utilities/sanitizeRelationshipIDs.js' -import { withSession } from './withSession.js' export const createGlobalVersion: CreateGlobalVersion = async function createGlobalVersion( this: MongooseAdapter, @@ -18,14 +15,16 @@ export const createGlobalVersion: CreateGlobalVersion = async function createGlo globalSlug, parent, publishedLocale, - req = {} as PayloadRequest, + req, snapshot, updatedAt, versionData, }, ) { const VersionModel = this.versions[globalSlug] - const options = await withSession(this, req) + const options: CreateOptions = { + session: await getSession(this, req), + } const data = sanitizeRelationshipIDs({ config: this.payload.config, diff --git a/packages/db-mongodb/src/createVersion.ts b/packages/db-mongodb/src/createVersion.ts index 121a94c93d6..3482345e24c 100644 --- a/packages/db-mongodb/src/createVersion.ts +++ b/packages/db-mongodb/src/createVersion.ts @@ -1,15 +1,12 @@ +import type { CreateOptions } from 'mongoose' + import { Types } from 'mongoose' -import { - buildVersionCollectionFields, - type CreateVersion, - type Document, - type PayloadRequest, -} from 'payload' +import { buildVersionCollectionFields, type CreateVersion, type Document } from 'payload' import type { MongooseAdapter } from './index.js' +import { getSession } from './utilities/getSession.js' import { sanitizeRelationshipIDs } from './utilities/sanitizeRelationshipIDs.js' -import { withSession } from './withSession.js' export const createVersion: CreateVersion = async function createVersion( this: MongooseAdapter, @@ -19,14 +16,16 @@ export const createVersion: CreateVersion = async function createVersion( createdAt, parent, publishedLocale, - req = {} as PayloadRequest, + req, snapshot, updatedAt, versionData, }, ) { const VersionModel = this.versions[collectionSlug] - const options = await withSession(this, req) + const options: CreateOptions = { + session: await getSession(this, req), + } const data = sanitizeRelationshipIDs({ config: this.payload.config, diff --git a/packages/db-mongodb/src/deleteMany.ts b/packages/db-mongodb/src/deleteMany.ts index cc692e9e0eb..cdc5470e9b1 100644 --- a/packages/db-mongodb/src/deleteMany.ts +++ b/packages/db-mongodb/src/deleteMany.ts @@ -1,17 +1,17 @@ -import type { DeleteMany, PayloadRequest } from 'payload' +import type { DeleteOptions } from 'mongodb' +import type { DeleteMany } from 'payload' import type { MongooseAdapter } from './index.js' -import { withSession } from './withSession.js' +import { getSession } from './utilities/getSession.js' export const deleteMany: DeleteMany = async function deleteMany( this: MongooseAdapter, - { collection, req = {} as PayloadRequest, where }, + { collection, req, where }, ) { const Model = this.collections[collection] - const options = { - ...(await withSession(this, req)), - lean: true, + const options: DeleteOptions = { + session: await getSession(this, req), } const query = await Model.buildQuery({ diff --git a/packages/db-mongodb/src/deleteOne.ts b/packages/db-mongodb/src/deleteOne.ts index edf9ebb6dc0..3d9bc07f08f 100644 --- a/packages/db-mongodb/src/deleteOne.ts +++ b/packages/db-mongodb/src/deleteOne.ts @@ -1,31 +1,32 @@ -import type { DeleteOne, Document, PayloadRequest } from 'payload' +import type { QueryOptions } from 'mongoose' +import type { DeleteOne, Document } from 'payload' import type { MongooseAdapter } from './index.js' import { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js' +import { getSession } from './utilities/getSession.js' import { sanitizeInternalFields } from './utilities/sanitizeInternalFields.js' -import { withSession } from './withSession.js' export const deleteOne: DeleteOne = async function deleteOne( this: MongooseAdapter, - { collection, req = {} as PayloadRequest, select, where }, + { collection, req, select, where }, ) { const Model = this.collections[collection] - const options = await withSession(this, req) + const options: QueryOptions = { + projection: buildProjectionFromSelect({ + adapter: this, + fields: this.payload.collections[collection].config.flattenedFields, + select, + }), + session: await getSession(this, req), + } const query = await Model.buildQuery({ payload: this.payload, where, }) - const doc = await Model.findOneAndDelete(query, { - ...options, - projection: buildProjectionFromSelect({ - adapter: this, - fields: this.payload.collections[collection].config.flattenedFields, - select, - }), - }).lean() + const doc = await Model.findOneAndDelete(query, options).lean() let result: Document = JSON.parse(JSON.stringify(doc)) diff --git a/packages/db-mongodb/src/deleteVersions.ts b/packages/db-mongodb/src/deleteVersions.ts index cd36dbaeed3..5ee111f3a8f 100644 --- a/packages/db-mongodb/src/deleteVersions.ts +++ b/packages/db-mongodb/src/deleteVersions.ts @@ -1,18 +1,16 @@ -import type { DeleteVersions, PayloadRequest } from 'payload' +import type { DeleteVersions } from 'payload' import type { MongooseAdapter } from './index.js' -import { withSession } from './withSession.js' +import { getSession } from './utilities/getSession.js' export const deleteVersions: DeleteVersions = async function deleteVersions( this: MongooseAdapter, - { collection, locale, req = {} as PayloadRequest, where }, + { collection, locale, req, where }, ) { const VersionsModel = this.versions[collection] - const options = { - ...(await withSession(this, req)), - lean: true, - } + + const session = await getSession(this, req) const query = await VersionsModel.buildQuery({ locale, @@ -20,5 +18,5 @@ export const deleteVersions: DeleteVersions = async function deleteVersions( where, }) - await VersionsModel.deleteMany(query, options) + await VersionsModel.deleteMany(query, { session }) } diff --git a/packages/db-mongodb/src/find.ts b/packages/db-mongodb/src/find.ts index 9295f8829c8..d953c3484f2 100644 --- a/packages/db-mongodb/src/find.ts +++ b/packages/db-mongodb/src/find.ts @@ -1,5 +1,5 @@ import type { PaginateOptions } from 'mongoose' -import type { Find, PayloadRequest } from 'payload' +import type { Find } from 'payload' import { flattenWhereToOperators } from 'payload' @@ -8,8 +8,8 @@ import type { MongooseAdapter } from './index.js' import { buildSortParam } from './queries/buildSortParam.js' import { buildJoinAggregation } from './utilities/buildJoinAggregation.js' import { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js' +import { getSession } from './utilities/getSession.js' import { sanitizeInternalFields } from './utilities/sanitizeInternalFields.js' -import { withSession } from './withSession.js' export const find: Find = async function find( this: MongooseAdapter, @@ -21,7 +21,7 @@ export const find: Find = async function find( page, pagination, projection, - req = {} as PayloadRequest, + req, select, sort: sortArg, where, @@ -29,7 +29,8 @@ export const find: Find = async function find( ) { const Model = this.collections[collection] const collectionConfig = this.payload.collections[collection].config - const options = await withSession(this, req) + + const session = await getSession(this, req) let hasNearConstraint = false @@ -60,7 +61,9 @@ export const find: Find = async function find( const paginationOptions: PaginateOptions = { lean: true, leanWithId: true, - options, + options: { + session, + }, page, pagination, projection, @@ -92,8 +95,8 @@ export const find: Find = async function find( paginationOptions.useCustomCountFn = () => { return Promise.resolve( Model.countDocuments(query, { - ...options, hint: { _id: 1 }, + session, }), ) } diff --git a/packages/db-mongodb/src/findGlobal.ts b/packages/db-mongodb/src/findGlobal.ts index c89ef2e2960..ec51dba5b13 100644 --- a/packages/db-mongodb/src/findGlobal.ts +++ b/packages/db-mongodb/src/findGlobal.ts @@ -1,26 +1,27 @@ -import type { FindGlobal, PayloadRequest } from 'payload' +import type { QueryOptions } from 'mongoose' +import type { FindGlobal } from 'payload' import { combineQueries } from 'payload' import type { MongooseAdapter } from './index.js' import { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js' +import { getSession } from './utilities/getSession.js' import { sanitizeInternalFields } from './utilities/sanitizeInternalFields.js' -import { withSession } from './withSession.js' export const findGlobal: FindGlobal = async function findGlobal( this: MongooseAdapter, - { slug, locale, req = {} as PayloadRequest, select, where }, + { slug, locale, req, select, where }, ) { const Model = this.globals - const options = { - ...(await withSession(this, req)), + const options: QueryOptions = { lean: true, select: buildProjectionFromSelect({ adapter: this, fields: this.payload.globals.config.find((each) => each.slug === slug).flattenedFields, select, }), + session: await getSession(this, req), } const query = await Model.buildQuery({ diff --git a/packages/db-mongodb/src/findGlobalVersions.ts b/packages/db-mongodb/src/findGlobalVersions.ts index 406bac1f6d4..3166d894140 100644 --- a/packages/db-mongodb/src/findGlobalVersions.ts +++ b/packages/db-mongodb/src/findGlobalVersions.ts @@ -1,5 +1,5 @@ -import type { PaginateOptions } from 'mongoose' -import type { FindGlobalVersions, PayloadRequest } from 'payload' +import type { PaginateOptions, QueryOptions } from 'mongoose' +import type { FindGlobalVersions } from 'payload' import { buildVersionGlobalFields, flattenWhereToOperators } from 'payload' @@ -7,23 +7,12 @@ import type { MongooseAdapter } from './index.js' import { buildSortParam } from './queries/buildSortParam.js' import { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js' +import { getSession } from './utilities/getSession.js' import { sanitizeInternalFields } from './utilities/sanitizeInternalFields.js' -import { withSession } from './withSession.js' export const findGlobalVersions: FindGlobalVersions = async function findGlobalVersions( this: MongooseAdapter, - { - global, - limit, - locale, - page, - pagination, - req = {} as PayloadRequest, - select, - skip, - sort: sortArg, - where, - }, + { global, limit, locale, page, pagination, req, select, skip, sort: sortArg, where }, ) { const Model = this.versions[global] const versionFields = buildVersionGlobalFields( @@ -31,9 +20,11 @@ export const findGlobalVersions: FindGlobalVersions = async function findGlobalV this.payload.globals.config.find(({ slug }) => slug === global), true, ) - const options = { - ...(await withSession(this, req)), + + const session = await getSession(this, req) + const options: QueryOptions = { limit, + session, skip, } @@ -92,8 +83,8 @@ export const findGlobalVersions: FindGlobalVersions = async function findGlobalV paginationOptions.useCustomCountFn = () => { return Promise.resolve( Model.countDocuments(query, { - ...options, hint: { _id: 1 }, + session, }), ) } diff --git a/packages/db-mongodb/src/findOne.ts b/packages/db-mongodb/src/findOne.ts index 5b82fd9effa..10d13b6fcf6 100644 --- a/packages/db-mongodb/src/findOne.ts +++ b/packages/db-mongodb/src/findOne.ts @@ -1,22 +1,23 @@ -import type { MongooseQueryOptions, QueryOptions } from 'mongoose' -import type { Document, FindOne, PayloadRequest } from 'payload' +import type { AggregateOptions, QueryOptions } from 'mongoose' +import type { Document, FindOne } from 'payload' import type { MongooseAdapter } from './index.js' import { buildJoinAggregation } from './utilities/buildJoinAggregation.js' import { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js' +import { getSession } from './utilities/getSession.js' import { sanitizeInternalFields } from './utilities/sanitizeInternalFields.js' -import { withSession } from './withSession.js' export const findOne: FindOne = async function findOne( this: MongooseAdapter, - { collection, joins, locale, req = {} as PayloadRequest, select, where }, + { collection, joins, locale, req, select, where }, ) { const Model = this.collections[collection] const collectionConfig = this.payload.collections[collection].config - const options: MongooseQueryOptions = { - ...(await withSession(this, req)), + const session = await getSession(this, req) + const options: AggregateOptions & QueryOptions = { lean: true, + session, } const query = await Model.buildQuery({ @@ -44,7 +45,7 @@ export const findOne: FindOne = async function findOne( let doc if (aggregate) { - ;[doc] = await Model.aggregate(aggregate, options) + ;[doc] = await Model.aggregate(aggregate, { session }) } else { ;(options as Record).projection = projection doc = await Model.findOne(query, {}, options) diff --git a/packages/db-mongodb/src/findVersions.ts b/packages/db-mongodb/src/findVersions.ts index cb1810bf3bd..19abd38d443 100644 --- a/packages/db-mongodb/src/findVersions.ts +++ b/packages/db-mongodb/src/findVersions.ts @@ -1,5 +1,5 @@ -import type { PaginateOptions } from 'mongoose' -import type { FindVersions, PayloadRequest } from 'payload' +import type { PaginateOptions, QueryOptions } from 'mongoose' +import type { FindVersions } from 'payload' import { buildVersionCollectionFields, flattenWhereToOperators } from 'payload' @@ -7,29 +7,19 @@ import type { MongooseAdapter } from './index.js' import { buildSortParam } from './queries/buildSortParam.js' import { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js' +import { getSession } from './utilities/getSession.js' import { sanitizeInternalFields } from './utilities/sanitizeInternalFields.js' -import { withSession } from './withSession.js' export const findVersions: FindVersions = async function findVersions( this: MongooseAdapter, - { - collection, - limit, - locale, - page, - pagination, - req = {} as PayloadRequest, - select, - skip, - sort: sortArg, - where, - }, + { collection, limit, locale, page, pagination, req = {}, select, skip, sort: sortArg, where }, ) { const Model = this.versions[collection] const collectionConfig = this.payload.collections[collection].config - const options = { - ...(await withSession(this, req)), + const session = await getSession(this, req) + const options: QueryOptions = { limit, + session, skip, } @@ -91,8 +81,8 @@ export const findVersions: FindVersions = async function findVersions( paginationOptions.useCustomCountFn = () => { return Promise.resolve( Model.countDocuments(query, { - ...options, hint: { _id: 1 }, + session, }), ) } diff --git a/packages/db-mongodb/src/migrateFresh.ts b/packages/db-mongodb/src/migrateFresh.ts index c8207fbfd49..4db2e76c423 100644 --- a/packages/db-mongodb/src/migrateFresh.ts +++ b/packages/db-mongodb/src/migrateFresh.ts @@ -45,7 +45,7 @@ export async function migrateFresh( msg: `Found ${migrationFiles.length} migration files.`, }) - const req = { payload } as PayloadRequest + const req = { payload } // Run all migrate up for (const migration of migrationFiles) { diff --git a/packages/db-mongodb/src/predefinedMigrations/migrateRelationshipsV2_V3.ts b/packages/db-mongodb/src/predefinedMigrations/migrateRelationshipsV2_V3.ts index e5276891915..5d5e2e75907 100644 --- a/packages/db-mongodb/src/predefinedMigrations/migrateRelationshipsV2_V3.ts +++ b/packages/db-mongodb/src/predefinedMigrations/migrateRelationshipsV2_V3.ts @@ -5,8 +5,8 @@ import { buildVersionCollectionFields, buildVersionGlobalFields } from 'payload' import type { MongooseAdapter } from '../index.js' +import { getSession } from '../utilities/getSession.js' import { sanitizeRelationshipIDs } from '../utilities/sanitizeRelationshipIDs.js' -import { withSession } from '../withSession.js' const migrateModelWithBatching = async ({ batchSize, @@ -109,7 +109,7 @@ export async function migrateRelationshipsV2_V3({ const db = payload.db as MongooseAdapter const config = payload.config - const { session } = await withSession(db, req) + const session = await getSession(db, req) for (const collection of payload.config.collections.filter(hasRelationshipOrUploadField)) { payload.logger.info(`Migrating collection "${collection.slug}"`) diff --git a/packages/db-mongodb/src/predefinedMigrations/migrateVersionsV1_V2.ts b/packages/db-mongodb/src/predefinedMigrations/migrateVersionsV1_V2.ts index 2177f1dee39..199210f7ef6 100644 --- a/packages/db-mongodb/src/predefinedMigrations/migrateVersionsV1_V2.ts +++ b/packages/db-mongodb/src/predefinedMigrations/migrateVersionsV1_V2.ts @@ -3,12 +3,12 @@ import type { Payload, PayloadRequest } from 'payload' import type { MongooseAdapter } from '../index.js' -import { withSession } from '../withSession.js' +import { getSession } from '../utilities/getSession.js' export async function migrateVersionsV1_V2({ req }: { req: PayloadRequest }) { const { payload } = req - const { session } = await withSession(payload.db as MongooseAdapter, req) + const session = await getSession(payload.db as MongooseAdapter, req) // For each collection diff --git a/packages/db-mongodb/src/queryDrafts.ts b/packages/db-mongodb/src/queryDrafts.ts index 8b06e67ed33..3ea8cb34d7d 100644 --- a/packages/db-mongodb/src/queryDrafts.ts +++ b/packages/db-mongodb/src/queryDrafts.ts @@ -1,5 +1,5 @@ -import type { PaginateOptions } from 'mongoose' -import type { PayloadRequest, QueryDrafts } from 'payload' +import type { PaginateOptions, QueryOptions } from 'mongoose' +import type { QueryDrafts } from 'payload' import { buildVersionCollectionFields, combineQueries, flattenWhereToOperators } from 'payload' @@ -8,27 +8,18 @@ import type { MongooseAdapter } from './index.js' import { buildSortParam } from './queries/buildSortParam.js' import { buildJoinAggregation } from './utilities/buildJoinAggregation.js' import { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js' +import { getSession } from './utilities/getSession.js' import { sanitizeInternalFields } from './utilities/sanitizeInternalFields.js' -import { withSession } from './withSession.js' export const queryDrafts: QueryDrafts = async function queryDrafts( this: MongooseAdapter, - { - collection, - joins, - limit, - locale, - page, - pagination, - req = {} as PayloadRequest, - select, - sort: sortArg, - where, - }, + { collection, joins, limit, locale, page, pagination, req, select, sort: sortArg, where }, ) { const VersionModel = this.versions[collection] const collectionConfig = this.payload.collections[collection].config - const options = await withSession(this, req) + const options: QueryOptions = { + session: await getSession(this, req), + } let hasNearConstraint let sort diff --git a/packages/db-mongodb/src/updateGlobal.ts b/packages/db-mongodb/src/updateGlobal.ts index ed090077cb8..239fff5fd92 100644 --- a/packages/db-mongodb/src/updateGlobal.ts +++ b/packages/db-mongodb/src/updateGlobal.ts @@ -1,23 +1,22 @@ import type { QueryOptions } from 'mongoose' -import type { PayloadRequest, UpdateGlobal } from 'payload' +import type { UpdateGlobal } from 'payload' import type { MongooseAdapter } from './index.js' import { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js' +import { getSession } from './utilities/getSession.js' import { sanitizeInternalFields } from './utilities/sanitizeInternalFields.js' import { sanitizeRelationshipIDs } from './utilities/sanitizeRelationshipIDs.js' -import { withSession } from './withSession.js' export const updateGlobal: UpdateGlobal = async function updateGlobal( this: MongooseAdapter, - { slug, data, options: optionsArgs = {}, req = {} as PayloadRequest, select }, + { slug, data, options: optionsArgs = {}, req, select }, ) { const Model = this.globals const fields = this.payload.config.globals.find((global) => global.slug === slug).fields const options: QueryOptions = { ...optionsArgs, - ...(await withSession(this, req)), lean: true, new: true, projection: buildProjectionFromSelect({ @@ -25,6 +24,7 @@ export const updateGlobal: UpdateGlobal = async function updateGlobal( fields: this.payload.config.globals.find((global) => global.slug === slug).flattenedFields, select, }), + session: await getSession(this, req), } let result diff --git a/packages/db-mongodb/src/updateGlobalVersion.ts b/packages/db-mongodb/src/updateGlobalVersion.ts index 73101f5967b..af1453840b6 100644 --- a/packages/db-mongodb/src/updateGlobalVersion.ts +++ b/packages/db-mongodb/src/updateGlobalVersion.ts @@ -1,17 +1,12 @@ import type { QueryOptions } from 'mongoose' -import { - buildVersionGlobalFields, - type PayloadRequest, - type TypeWithID, - type UpdateGlobalVersionArgs, -} from 'payload' +import { buildVersionGlobalFields, type TypeWithID, type UpdateGlobalVersionArgs } from 'payload' import type { MongooseAdapter } from './index.js' import { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js' +import { getSession } from './utilities/getSession.js' import { sanitizeRelationshipIDs } from './utilities/sanitizeRelationshipIDs.js' -import { withSession } from './withSession.js' export async function updateGlobalVersion( this: MongooseAdapter, @@ -20,7 +15,7 @@ export async function updateGlobalVersion( global: globalSlug, locale, options: optionsArgs = {}, - req = {} as PayloadRequest, + req, select, versionData, where, @@ -34,7 +29,6 @@ export async function updateGlobalVersion( const options: QueryOptions = { ...optionsArgs, - ...(await withSession(this, req)), lean: true, new: true, projection: buildProjectionFromSelect({ @@ -42,6 +36,7 @@ export async function updateGlobalVersion( fields: buildVersionGlobalFields(this.payload.config, currentGlobal, true), select, }), + session: await getSession(this, req), } const query = await VersionModel.buildQuery({ diff --git a/packages/db-mongodb/src/updateOne.ts b/packages/db-mongodb/src/updateOne.ts index f70cb149f3b..555d46925b2 100644 --- a/packages/db-mongodb/src/updateOne.ts +++ b/packages/db-mongodb/src/updateOne.ts @@ -1,33 +1,23 @@ import type { QueryOptions } from 'mongoose' -import type { PayloadRequest, UpdateOne } from 'payload' +import type { UpdateOne } from 'payload' import type { MongooseAdapter } from './index.js' import { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js' +import { getSession } from './utilities/getSession.js' import { handleError } from './utilities/handleError.js' import { sanitizeInternalFields } from './utilities/sanitizeInternalFields.js' import { sanitizeRelationshipIDs } from './utilities/sanitizeRelationshipIDs.js' -import { withSession } from './withSession.js' export const updateOne: UpdateOne = async function updateOne( this: MongooseAdapter, - { - id, - collection, - data, - locale, - options: optionsArgs = {}, - req = {} as PayloadRequest, - select, - where: whereArg, - }, + { id, collection, data, locale, options: optionsArgs = {}, req, select, where: whereArg }, ) { const where = id ? { id: { equals: id } } : whereArg const Model = this.collections[collection] const fields = this.payload.collections[collection].config.fields const options: QueryOptions = { ...optionsArgs, - ...(await withSession(this, req)), lean: true, new: true, projection: buildProjectionFromSelect({ @@ -35,6 +25,7 @@ export const updateOne: UpdateOne = async function updateOne( fields: this.payload.collections[collection].config.flattenedFields, select, }), + session: await getSession(this, req), } const query = await Model.buildQuery({ diff --git a/packages/db-mongodb/src/updateVersion.ts b/packages/db-mongodb/src/updateVersion.ts index 7f814b4ea5b..9514e7cb73b 100644 --- a/packages/db-mongodb/src/updateVersion.ts +++ b/packages/db-mongodb/src/updateVersion.ts @@ -1,25 +1,16 @@ import type { QueryOptions } from 'mongoose' -import { buildVersionCollectionFields, type PayloadRequest, type UpdateVersion } from 'payload' +import { buildVersionCollectionFields, type UpdateVersion } from 'payload' import type { MongooseAdapter } from './index.js' import { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js' +import { getSession } from './utilities/getSession.js' import { sanitizeRelationshipIDs } from './utilities/sanitizeRelationshipIDs.js' -import { withSession } from './withSession.js' export const updateVersion: UpdateVersion = async function updateVersion( this: MongooseAdapter, - { - id, - collection, - locale, - options: optionsArgs = {}, - req = {} as PayloadRequest, - select, - versionData, - where, - }, + { id, collection, locale, options: optionsArgs = {}, req, select, versionData, where }, ) { const VersionModel = this.versions[collection] const whereToUse = where || { id: { equals: id } } @@ -30,7 +21,6 @@ export const updateVersion: UpdateVersion = async function updateVersion( const options: QueryOptions = { ...optionsArgs, - ...(await withSession(this, req)), lean: true, new: true, projection: buildProjectionFromSelect({ @@ -42,6 +32,7 @@ export const updateVersion: UpdateVersion = async function updateVersion( ), select, }), + session: await getSession(this, req), } const query = await VersionModel.buildQuery({ diff --git a/packages/db-mongodb/src/upsert.ts b/packages/db-mongodb/src/upsert.ts index 8f846c4a23e..3ee7303a195 100644 --- a/packages/db-mongodb/src/upsert.ts +++ b/packages/db-mongodb/src/upsert.ts @@ -1,10 +1,10 @@ -import type { PayloadRequest, Upsert } from 'payload' +import type { Upsert } from 'payload' import type { MongooseAdapter } from './index.js' export const upsert: Upsert = async function upsert( this: MongooseAdapter, - { collection, data, locale, req = {} as PayloadRequest, select, where }, + { collection, data, locale, req, select, where }, ) { return this.updateOne({ collection, data, locale, options: { upsert: true }, req, select, where }) } diff --git a/packages/db-mongodb/src/withSession.ts b/packages/db-mongodb/src/utilities/getSession.ts similarity index 57% rename from packages/db-mongodb/src/withSession.ts rename to packages/db-mongodb/src/utilities/getSession.ts index c9f43254e79..1bb0b8795df 100644 --- a/packages/db-mongodb/src/withSession.ts +++ b/packages/db-mongodb/src/utilities/getSession.ts @@ -1,23 +1,27 @@ import type { ClientSession } from 'mongoose' import type { PayloadRequest } from 'payload' -import type { MongooseAdapter } from './index.js' +import type { MongooseAdapter } from '../index.js' /** * returns the session belonging to the transaction of the req.session if exists * @returns ClientSession */ -export async function withSession( +export async function getSession( db: MongooseAdapter, - req: PayloadRequest, -): Promise<{ session: ClientSession } | Record> { + req?: Partial, +): Promise { + if (!req) { + return + } + let transactionID = req.transactionID if (transactionID instanceof Promise) { transactionID = await req.transactionID } - if (req) { - return db.sessions[transactionID] ? { session: db.sessions[transactionID] } : {} + if (transactionID) { + return db.sessions[transactionID] } } diff --git a/packages/db-mongodb/src/utilities/handleError.ts b/packages/db-mongodb/src/utilities/handleError.ts index 259f95f5d85..c05ed3b752b 100644 --- a/packages/db-mongodb/src/utilities/handleError.ts +++ b/packages/db-mongodb/src/utilities/handleError.ts @@ -1,3 +1,5 @@ +import type { PayloadRequest } from 'payload' + import httpStatus from 'http-status' import { APIError, ValidationError } from 'payload' @@ -8,28 +10,32 @@ export const handleError = ({ req, }: { collection?: string - error + error: unknown global?: string - req + req?: Partial }) => { + if (!error || typeof error !== 'object') { + throw error + } + + const message = req?.t ? 'error:valueMustBeUnique' : 'Value must be unique' + // Handle uniqueness error from MongoDB - if (error.code === 11000 && error.keyValue) { + if ('code' in error && error.code === 11000 && 'keyValue' in error && error.keyValue) { throw new ValidationError( { collection, errors: [ { - message: req.t('error:valueMustBeUnique'), + message, path: Object.keys(error.keyValue)[0], }, ], global, }, - req.t, + req?.t, ) - } else if (error.code === 11000) { - throw new APIError(req.t('error:valueMustBeUnique'), httpStatus.BAD_REQUEST) - } else { - throw error } + + throw new APIError(message, httpStatus.BAD_REQUEST) } diff --git a/packages/drizzle/src/count.ts b/packages/drizzle/src/count.ts index 6f638fd6822..7befdd8554f 100644 --- a/packages/drizzle/src/count.ts +++ b/packages/drizzle/src/count.ts @@ -5,6 +5,7 @@ import toSnakeCase from 'to-snake-case' import type { DrizzleAdapter } from './types.js' import buildQuery from './queries/buildQuery.js' +import { getTransaction } from './utilities/getTransaction.js' export const count: Count = async function count( this: DrizzleAdapter, @@ -14,7 +15,7 @@ export const count: Count = async function count( const tableName = this.tableNameMap.get(toSnakeCase(collectionConfig.slug)) - const db = this.sessions[await req?.transactionID]?.db || this.drizzle + const db = await getTransaction(this, req) const { joins, where } = buildQuery({ adapter: this, diff --git a/packages/drizzle/src/countGlobalVersions.ts b/packages/drizzle/src/countGlobalVersions.ts index a1101faa8a9..803a52a12f7 100644 --- a/packages/drizzle/src/countGlobalVersions.ts +++ b/packages/drizzle/src/countGlobalVersions.ts @@ -6,6 +6,7 @@ import toSnakeCase from 'to-snake-case' import type { DrizzleAdapter } from './types.js' import buildQuery from './queries/buildQuery.js' +import { getTransaction } from './utilities/getTransaction.js' export const countGlobalVersions: CountGlobalVersions = async function countGlobalVersions( this: DrizzleAdapter, @@ -19,7 +20,7 @@ export const countGlobalVersions: CountGlobalVersions = async function countGlob `_${toSnakeCase(globalConfig.slug)}${this.versionsSuffix}`, ) - const db = this.sessions[await req?.transactionID]?.db || this.drizzle + const db = await getTransaction(this, req) const fields = buildVersionGlobalFields(this.payload.config, globalConfig, true) diff --git a/packages/drizzle/src/countVersions.ts b/packages/drizzle/src/countVersions.ts index 7b9ea39e500..b975a0b1929 100644 --- a/packages/drizzle/src/countVersions.ts +++ b/packages/drizzle/src/countVersions.ts @@ -6,6 +6,7 @@ import toSnakeCase from 'to-snake-case' import type { DrizzleAdapter } from './types.js' import buildQuery from './queries/buildQuery.js' +import { getTransaction } from './utilities/getTransaction.js' export const countVersions: CountVersions = async function countVersions( this: DrizzleAdapter, @@ -17,7 +18,7 @@ export const countVersions: CountVersions = async function countVersions( `_${toSnakeCase(collectionConfig.slug)}${this.versionsSuffix}`, ) - const db = this.sessions[await req?.transactionID]?.db || this.drizzle + const db = await getTransaction(this, req) const fields = buildVersionCollectionFields(this.payload.config, collectionConfig, true) diff --git a/packages/drizzle/src/create.ts b/packages/drizzle/src/create.ts index 89d3132fc63..55e6a797bd7 100644 --- a/packages/drizzle/src/create.ts +++ b/packages/drizzle/src/create.ts @@ -5,12 +5,13 @@ import toSnakeCase from 'to-snake-case' import type { DrizzleAdapter } from './types.js' import { upsertRow } from './upsertRow/index.js' +import { getTransaction } from './utilities/getTransaction.js' export const create: Create = async function create( this: DrizzleAdapter, { collection: collectionSlug, data, req, select }, ) { - const db = this.sessions[await req?.transactionID]?.db || this.drizzle + const db = await getTransaction(this, req) const collection = this.payload.collections[collectionSlug].config const tableName = this.tableNameMap.get(toSnakeCase(collection.slug)) diff --git a/packages/drizzle/src/createGlobal.ts b/packages/drizzle/src/createGlobal.ts index 4ef9943e679..d76a27926b7 100644 --- a/packages/drizzle/src/createGlobal.ts +++ b/packages/drizzle/src/createGlobal.ts @@ -1,16 +1,17 @@ -import type { CreateGlobalArgs, PayloadRequest } from 'payload' +import type { CreateGlobalArgs } from 'payload' import toSnakeCase from 'to-snake-case' import type { DrizzleAdapter } from './types.js' import { upsertRow } from './upsertRow/index.js' +import { getTransaction } from './utilities/getTransaction.js' export async function createGlobal>( this: DrizzleAdapter, - { slug, data, req = {} as PayloadRequest }: CreateGlobalArgs, + { slug, data, req }: CreateGlobalArgs, ): Promise { - const db = this.sessions[await req?.transactionID]?.db || this.drizzle + const db = await getTransaction(this, req) const globalConfig = this.payload.globals.config.find((config) => config.slug === slug) const tableName = this.tableNameMap.get(toSnakeCase(globalConfig.slug)) diff --git a/packages/drizzle/src/createGlobalVersion.ts b/packages/drizzle/src/createGlobalVersion.ts index f2293f04389..c419e8f5844 100644 --- a/packages/drizzle/src/createGlobalVersion.ts +++ b/packages/drizzle/src/createGlobalVersion.ts @@ -1,4 +1,4 @@ -import type { CreateGlobalVersionArgs, PayloadRequest, TypeWithID, TypeWithVersion } from 'payload' +import type { CreateGlobalVersionArgs, TypeWithID, TypeWithVersion } from 'payload' import { sql } from 'drizzle-orm' import { buildVersionGlobalFields } from 'payload' @@ -7,6 +7,7 @@ import toSnakeCase from 'to-snake-case' import type { DrizzleAdapter } from './types.js' import { upsertRow } from './upsertRow/index.js' +import { getTransaction } from './utilities/getTransaction.js' export async function createGlobalVersion( this: DrizzleAdapter, @@ -15,14 +16,14 @@ export async function createGlobalVersion( createdAt, globalSlug, publishedLocale, - req = {} as PayloadRequest, + req, select, snapshot, updatedAt, versionData, }: CreateGlobalVersionArgs, ) { - const db = this.sessions[await req?.transactionID]?.db || this.drizzle + const db = await getTransaction(this, req) const global = this.payload.globals.config.find(({ slug }) => slug === globalSlug) const tableName = this.tableNameMap.get(`_${toSnakeCase(global.slug)}${this.versionsSuffix}`) diff --git a/packages/drizzle/src/createVersion.ts b/packages/drizzle/src/createVersion.ts index d40dc9db4e4..c7e880bf230 100644 --- a/packages/drizzle/src/createVersion.ts +++ b/packages/drizzle/src/createVersion.ts @@ -1,4 +1,4 @@ -import type { CreateVersionArgs, PayloadRequest, TypeWithID, TypeWithVersion } from 'payload' +import type { CreateVersionArgs, TypeWithID, TypeWithVersion } from 'payload' import { sql } from 'drizzle-orm' import { buildVersionCollectionFields } from 'payload' @@ -7,6 +7,7 @@ import toSnakeCase from 'to-snake-case' import type { DrizzleAdapter } from './types.js' import { upsertRow } from './upsertRow/index.js' +import { getTransaction } from './utilities/getTransaction.js' export async function createVersion( this: DrizzleAdapter, @@ -16,14 +17,14 @@ export async function createVersion( createdAt, parent, publishedLocale, - req = {} as PayloadRequest, + req, select, snapshot, updatedAt, versionData, }: CreateVersionArgs, ) { - const db = this.sessions[await req?.transactionID]?.db || this.drizzle + const db = await getTransaction(this, req) const collection = this.payload.collections[collectionSlug].config const defaultTableName = toSnakeCase(collection.slug) diff --git a/packages/drizzle/src/deleteMany.ts b/packages/drizzle/src/deleteMany.ts index b228a38416d..7cf0923add1 100644 --- a/packages/drizzle/src/deleteMany.ts +++ b/packages/drizzle/src/deleteMany.ts @@ -1,4 +1,4 @@ -import type { DeleteMany, PayloadRequest } from 'payload' +import type { DeleteMany } from 'payload' import { inArray } from 'drizzle-orm' import toSnakeCase from 'to-snake-case' @@ -6,12 +6,13 @@ import toSnakeCase from 'to-snake-case' import type { DrizzleAdapter } from './types.js' import { findMany } from './find/findMany.js' +import { getTransaction } from './utilities/getTransaction.js' export const deleteMany: DeleteMany = async function deleteMany( this: DrizzleAdapter, - { collection, req = {} as PayloadRequest, where }, + { collection, req, where }, ) { - const db = this.sessions[await req?.transactionID]?.db || this.drizzle + const db = await getTransaction(this, req) const collectionConfig = this.payload.collections[collection].config const tableName = this.tableNameMap.get(toSnakeCase(collectionConfig.slug)) @@ -21,7 +22,7 @@ export const deleteMany: DeleteMany = async function deleteMany( fields: collectionConfig.flattenedFields, joins: false, limit: 0, - locale: req.locale, + locale: req?.locale, page: 1, pagination: false, req, diff --git a/packages/drizzle/src/deleteOne.ts b/packages/drizzle/src/deleteOne.ts index 581b8760021..66b74098432 100644 --- a/packages/drizzle/src/deleteOne.ts +++ b/packages/drizzle/src/deleteOne.ts @@ -1,4 +1,4 @@ -import type { DeleteOne, PayloadRequest } from 'payload' +import type { DeleteOne } from 'payload' import { eq } from 'drizzle-orm' import toSnakeCase from 'to-snake-case' @@ -9,12 +9,13 @@ import { buildFindManyArgs } from './find/buildFindManyArgs.js' import buildQuery from './queries/buildQuery.js' import { selectDistinct } from './queries/selectDistinct.js' import { transform } from './transform/read/index.js' +import { getTransaction } from './utilities/getTransaction.js' export const deleteOne: DeleteOne = async function deleteOne( this: DrizzleAdapter, - { collection: collectionSlug, req = {} as PayloadRequest, select, where: whereArg }, + { collection: collectionSlug, req, select, where: whereArg }, ) { - const db = this.sessions[await req?.transactionID]?.db || this.drizzle + const db = await getTransaction(this, req) const collection = this.payload.collections[collectionSlug].config const tableName = this.tableNameMap.get(toSnakeCase(collection.slug)) @@ -24,7 +25,7 @@ export const deleteOne: DeleteOne = async function deleteOne( const { joins, selectFields, where } = buildQuery({ adapter: this, fields: collection.flattenedFields, - locale: req.locale, + locale: req?.locale, tableName, where: whereArg, }) diff --git a/packages/drizzle/src/deleteVersions.ts b/packages/drizzle/src/deleteVersions.ts index a62ac962c23..f510ef74b32 100644 --- a/packages/drizzle/src/deleteVersions.ts +++ b/packages/drizzle/src/deleteVersions.ts @@ -1,4 +1,4 @@ -import type { DeleteVersions, PayloadRequest, SanitizedCollectionConfig } from 'payload' +import type { DeleteVersions, SanitizedCollectionConfig } from 'payload' import { inArray } from 'drizzle-orm' import { buildVersionCollectionFields } from 'payload' @@ -7,12 +7,13 @@ import toSnakeCase from 'to-snake-case' import type { DrizzleAdapter } from './types.js' import { findMany } from './find/findMany.js' +import { getTransaction } from './utilities/getTransaction.js' export const deleteVersions: DeleteVersions = async function deleteVersion( this: DrizzleAdapter, - { collection, locale, req = {} as PayloadRequest, where: where }, + { collection, locale, req, where: where }, ) { - const db = this.sessions[await req?.transactionID]?.db || this.drizzle + const db = await getTransaction(this, req) const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config const tableName = this.tableNameMap.get( diff --git a/packages/drizzle/src/find.ts b/packages/drizzle/src/find.ts index 2cd87b486c6..14465726422 100644 --- a/packages/drizzle/src/find.ts +++ b/packages/drizzle/src/find.ts @@ -1,4 +1,4 @@ -import type { Find, PayloadRequest, SanitizedCollectionConfig } from 'payload' +import type { Find, SanitizedCollectionConfig } from 'payload' import toSnakeCase from 'to-snake-case' @@ -8,18 +8,7 @@ import { findMany } from './find/findMany.js' export const find: Find = async function find( this: DrizzleAdapter, - { - collection, - joins, - limit, - locale, - page = 1, - pagination, - req = {} as PayloadRequest, - select, - sort: sortArg, - where, - }, + { collection, joins, limit, locale, page = 1, pagination, req, select, sort: sortArg, where }, ) { const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config const sort = sortArg !== undefined && sortArg !== null ? sortArg : collectionConfig.defaultSort diff --git a/packages/drizzle/src/find/findMany.ts b/packages/drizzle/src/find/findMany.ts index 0c2b7a1b13b..9e8fdcb4d27 100644 --- a/packages/drizzle/src/find/findMany.ts +++ b/packages/drizzle/src/find/findMany.ts @@ -1,4 +1,4 @@ -import type { FindArgs, FlattenedField, PayloadRequest, TypeWithID } from 'payload' +import type { FindArgs, FlattenedField, TypeWithID } from 'payload' import { inArray } from 'drizzle-orm' @@ -8,6 +8,7 @@ import type { ChainedMethods } from './chainMethods.js' import buildQuery from '../queries/buildQuery.js' import { selectDistinct } from '../queries/selectDistinct.js' import { transform } from '../transform/read/index.js' +import { getTransaction } from '../utilities/getTransaction.js' import { buildFindManyArgs } from './buildFindManyArgs.js' type Args = { @@ -25,7 +26,7 @@ export const findMany = async function find({ locale, page = 1, pagination, - req = {} as PayloadRequest, + req, select, skip, sort, @@ -33,7 +34,7 @@ export const findMany = async function find({ versions, where: whereArg, }: Args) { - const db = adapter.sessions[await req.transactionID]?.db || adapter.drizzle + const db = await getTransaction(adapter, req) let limit = limitArg let totalDocs: number let totalPages: number diff --git a/packages/drizzle/src/findGlobalVersions.ts b/packages/drizzle/src/findGlobalVersions.ts index 85b5e4a687b..25584e5cf7f 100644 --- a/packages/drizzle/src/findGlobalVersions.ts +++ b/packages/drizzle/src/findGlobalVersions.ts @@ -1,4 +1,4 @@ -import type { FindGlobalVersions, PayloadRequest, SanitizedGlobalConfig } from 'payload' +import type { FindGlobalVersions, SanitizedGlobalConfig } from 'payload' import { buildVersionGlobalFields } from 'payload' import toSnakeCase from 'to-snake-case' @@ -9,18 +9,7 @@ import { findMany } from './find/findMany.js' export const findGlobalVersions: FindGlobalVersions = async function findGlobalVersions( this: DrizzleAdapter, - { - global, - limit, - locale, - page, - pagination, - req = {} as PayloadRequest, - select, - skip, - sort: sortArg, - where, - }, + { global, limit, locale, page, pagination, req, select, skip, sort: sortArg, where }, ) { const globalConfig: SanitizedGlobalConfig = this.payload.globals.config.find( ({ slug }) => slug === global, diff --git a/packages/drizzle/src/findOne.ts b/packages/drizzle/src/findOne.ts index 2bc418fc755..c8fa80ce936 100644 --- a/packages/drizzle/src/findOne.ts +++ b/packages/drizzle/src/findOne.ts @@ -1,4 +1,4 @@ -import type { FindOneArgs, PayloadRequest, SanitizedCollectionConfig, TypeWithID } from 'payload' +import type { FindOneArgs, SanitizedCollectionConfig, TypeWithID } from 'payload' import toSnakeCase from 'to-snake-case' @@ -8,7 +8,7 @@ import { findMany } from './find/findMany.js' export async function findOne( this: DrizzleAdapter, - { collection, joins, locale, req = {} as PayloadRequest, select, where }: FindOneArgs, + { collection, joins, locale, req, select, where }: FindOneArgs, ): Promise { const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config diff --git a/packages/drizzle/src/findVersions.ts b/packages/drizzle/src/findVersions.ts index eee7d864c0e..75d16c8cc67 100644 --- a/packages/drizzle/src/findVersions.ts +++ b/packages/drizzle/src/findVersions.ts @@ -1,4 +1,4 @@ -import type { FindVersions, PayloadRequest, SanitizedCollectionConfig } from 'payload' +import type { FindVersions, SanitizedCollectionConfig } from 'payload' import { buildVersionCollectionFields } from 'payload' import toSnakeCase from 'to-snake-case' @@ -9,18 +9,7 @@ import { findMany } from './find/findMany.js' export const findVersions: FindVersions = async function findVersions( this: DrizzleAdapter, - { - collection, - limit, - locale, - page, - pagination, - req = {} as PayloadRequest, - select, - skip, - sort: sortArg, - where, - }, + { collection, limit, locale, page, pagination, req, select, skip, sort: sortArg, where }, ) { const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config const sort = sortArg !== undefined && sortArg !== null ? sortArg : collectionConfig.defaultSort diff --git a/packages/drizzle/src/migrate.ts b/packages/drizzle/src/migrate.ts index 6bb37472e22..0256031ac6c 100644 --- a/packages/drizzle/src/migrate.ts +++ b/packages/drizzle/src/migrate.ts @@ -1,10 +1,17 @@ -import type { Payload, PayloadRequest } from 'payload' - -import { commitTransaction, initTransaction, killTransaction, readMigrationFiles } from 'payload' +import type { Payload } from 'payload' + +import { + commitTransaction, + createLocalReq, + initTransaction, + killTransaction, + readMigrationFiles, +} from 'payload' import prompts from 'prompts' import type { DrizzleAdapter, Migration } from './types.js' +import { getTransaction } from './utilities/getTransaction.js' import { migrationTableExists } from './utilities/migrationTableExists.js' import { parseError } from './utilities/parseError.js' @@ -79,14 +86,13 @@ export const migrate: DrizzleAdapter['migrate'] = async function migrate( async function runMigrationFile(payload: Payload, migration: Migration, batch: number) { const start = Date.now() - const req = { payload } as PayloadRequest - const adapter = payload.db as DrizzleAdapter + const req = await createLocalReq({}, payload) payload.logger.info({ msg: `Migrating: ${migration.name}` }) try { await initTransaction(req) - const db = adapter?.sessions[await req.transactionID]?.db || adapter.drizzle + const db = await getTransaction(payload.db as DrizzleAdapter, req) await migration.up({ db, payload, req }) payload.logger.info({ msg: `Migrated: ${migration.name} (${Date.now() - start}ms)` }) await payload.create({ diff --git a/packages/drizzle/src/migrateDown.ts b/packages/drizzle/src/migrateDown.ts index 5673e7c92b5..20eb8714d71 100644 --- a/packages/drizzle/src/migrateDown.ts +++ b/packages/drizzle/src/migrateDown.ts @@ -1,7 +1,6 @@ -import type { PayloadRequest } from 'payload' - import { commitTransaction, + createLocalReq, getMigrations, initTransaction, killTransaction, @@ -10,6 +9,7 @@ import { import type { DrizzleAdapter } from './types.js' +import { getTransaction } from './utilities/getTransaction.js' import { migrationTableExists } from './utilities/migrationTableExists.js' import { parseError } from './utilities/parseError.js' @@ -39,12 +39,12 @@ export async function migrateDown(this: DrizzleAdapter): Promise { } const start = Date.now() - const req = { payload } as PayloadRequest + const req = await createLocalReq({}, payload) try { payload.logger.info({ msg: `Migrating down: ${migrationFile.name}` }) await initTransaction(req) - const db = this.sessions[await req.transactionID]?.db || this.drizzle + const db = await getTransaction(this, req) await migrationFile.down({ db, payload, req }) payload.logger.info({ msg: `Migrated down: ${migrationFile.name} (${Date.now() - start}ms)`, diff --git a/packages/drizzle/src/migrateFresh.ts b/packages/drizzle/src/migrateFresh.ts index 6583098644a..c88d6c97939 100644 --- a/packages/drizzle/src/migrateFresh.ts +++ b/packages/drizzle/src/migrateFresh.ts @@ -1,10 +1,15 @@ -import type { PayloadRequest } from 'payload' - -import { commitTransaction, initTransaction, killTransaction, readMigrationFiles } from 'payload' +import { + commitTransaction, + createLocalReq, + initTransaction, + killTransaction, + readMigrationFiles, +} from 'payload' import prompts from 'prompts' import type { DrizzleAdapter } from './types.js' +import { getTransaction } from './utilities/getTransaction.js' import { parseError } from './utilities/parseError.js' /** @@ -47,7 +52,7 @@ export async function migrateFresh( msg: `Found ${migrationFiles.length} migration files.`, }) - const req = { payload } as PayloadRequest + const req = await createLocalReq({}, payload) if ('createExtensions' in this && typeof this.createExtensions === 'function') { await this.createExtensions() @@ -59,7 +64,7 @@ export async function migrateFresh( try { const start = Date.now() await initTransaction(req) - const db = this.sessions[await req.transactionID]?.db || this.drizzle + const db = await getTransaction(this, req) await migration.up({ db, payload, req }) await payload.create({ collection: 'payload-migrations', diff --git a/packages/drizzle/src/migrateRefresh.ts b/packages/drizzle/src/migrateRefresh.ts index fde077dbb8b..1a56c825a1f 100644 --- a/packages/drizzle/src/migrateRefresh.ts +++ b/packages/drizzle/src/migrateRefresh.ts @@ -1,7 +1,6 @@ -import type { PayloadRequest } from 'payload' - import { commitTransaction, + createLocalReq, getMigrations, initTransaction, killTransaction, @@ -10,6 +9,7 @@ import { import type { DrizzleAdapter } from './types.js' +import { getTransaction } from './utilities/getTransaction.js' import { migrationTableExists } from './utilities/migrationTableExists.js' import { parseError } from './utilities/parseError.js' @@ -33,7 +33,7 @@ export async function migrateRefresh(this: DrizzleAdapter) { msg: `Rolling back batch ${latestBatch} consisting of ${existingMigrations.length} migration(s).`, }) - const req = { payload } as PayloadRequest + const req = await createLocalReq({}, payload) // Reverse order of migrations to rollback existingMigrations.reverse() @@ -48,7 +48,7 @@ export async function migrateRefresh(this: DrizzleAdapter) { payload.logger.info({ msg: `Migrating down: ${migration.name}` }) const start = Date.now() await initTransaction(req) - const db = this.sessions[await req.transactionID]?.db || this.drizzle + const db = await getTransaction(this, req) await migrationFile.down({ db, payload, req }) payload.logger.info({ msg: `Migrated down: ${migration.name} (${Date.now() - start}ms)`, diff --git a/packages/drizzle/src/migrateReset.ts b/packages/drizzle/src/migrateReset.ts index 940429d1be1..ce0d7a35463 100644 --- a/packages/drizzle/src/migrateReset.ts +++ b/packages/drizzle/src/migrateReset.ts @@ -1,7 +1,6 @@ -import type { PayloadRequest } from 'payload' - import { commitTransaction, + createLocalReq, getMigrations, initTransaction, killTransaction, @@ -10,6 +9,7 @@ import { import type { DrizzleAdapter } from './types.js' +import { getTransaction } from './utilities/getTransaction.js' import { migrationTableExists } from './utilities/migrationTableExists.js' /** @@ -26,7 +26,7 @@ export async function migrateReset(this: DrizzleAdapter): Promise { return } - const req = { payload } as PayloadRequest + const req = await createLocalReq({}, payload) // Rollback all migrations in order for (const migration of existingMigrations) { @@ -39,7 +39,7 @@ export async function migrateReset(this: DrizzleAdapter): Promise { const start = Date.now() payload.logger.info({ msg: `Migrating down: ${migrationFile.name}` }) await initTransaction(req) - const db = this.sessions[await req.transactionID]?.db || this.drizzle + const db = await getTransaction(this, req) await migrationFile.down({ db, payload, req }) payload.logger.info({ msg: `Migrated down: ${migrationFile.name} (${Date.now() - start}ms)`, diff --git a/packages/drizzle/src/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.ts b/packages/drizzle/src/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.ts index 6cd33455ff7..789a337117f 100644 --- a/packages/drizzle/src/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.ts +++ b/packages/drizzle/src/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.ts @@ -1,7 +1,6 @@ import type { FlattenedField, Payload, PayloadRequest } from 'payload' -import type { TransactionPg } from '../../../../types.js' -import type { BasePostgresAdapter } from '../../../types.js' +import type { BasePostgresAdapter, PostgresDB } from '../../../types.js' import type { DocsToResave } from '../types.js' import { upsertRow } from '../../../../upsertRow/index.js' @@ -10,14 +9,14 @@ import { traverseFields } from './traverseFields.js' type Args = { adapter: BasePostgresAdapter collectionSlug?: string - db: TransactionPg + db: PostgresDB debug: boolean docsToResave: DocsToResave fields: FlattenedField[] globalSlug?: string isVersions: boolean payload: Payload - req: PayloadRequest + req?: Partial tableName: string } diff --git a/packages/drizzle/src/postgres/predefinedMigrations/v2-v3/index.ts b/packages/drizzle/src/postgres/predefinedMigrations/v2-v3/index.ts index 211674e1ff6..02156229283 100644 --- a/packages/drizzle/src/postgres/predefinedMigrations/v2-v3/index.ts +++ b/packages/drizzle/src/postgres/predefinedMigrations/v2-v3/index.ts @@ -6,10 +6,10 @@ import fs from 'fs' import { buildVersionCollectionFields, buildVersionGlobalFields } from 'payload' import toSnakeCase from 'to-snake-case' -import type { TransactionPg } from '../../../types.js' import type { BasePostgresAdapter } from '../../types.js' import type { PathsToQuery } from './types.js' +import { getTransaction } from '../../../utilities/getTransaction.js' import { groupUpSQLStatements } from './groupUpSQLStatements.js' import { migrateRelationships } from './migrateRelationships.js' import { traverseFields } from './traverseFields.js' @@ -36,7 +36,7 @@ type Args = { */ export const migratePostgresV2toV3 = async ({ debug, payload, req }: Args) => { const adapter = payload.db as unknown as BasePostgresAdapter - const db = adapter.sessions[await req.transactionID].db as TransactionPg + const db = await getTransaction(adapter, req) const dir = payload.db.migrationDir // get the drizzle migrateUpSQL from drizzle using the last schema diff --git a/packages/drizzle/src/postgres/predefinedMigrations/v2-v3/migrateRelationships.ts b/packages/drizzle/src/postgres/predefinedMigrations/v2-v3/migrateRelationships.ts index cd893bac23d..eb9e4afd02a 100644 --- a/packages/drizzle/src/postgres/predefinedMigrations/v2-v3/migrateRelationships.ts +++ b/packages/drizzle/src/postgres/predefinedMigrations/v2-v3/migrateRelationships.ts @@ -2,8 +2,7 @@ import type { FlattenedField, Payload, PayloadRequest } from 'payload' import { sql } from 'drizzle-orm' -import type { TransactionPg } from '../../../types.js' -import type { BasePostgresAdapter } from '../../types.js' +import type { BasePostgresAdapter, PostgresDB } from '../../types.js' import type { DocsToResave, PathsToQuery } from './types.js' import { fetchAndResave } from './fetchAndResave/index.js' @@ -11,7 +10,7 @@ import { fetchAndResave } from './fetchAndResave/index.js' type Args = { adapter: BasePostgresAdapter collectionSlug?: string - db: TransactionPg + db: PostgresDB debug: boolean fields: FlattenedField[] globalSlug?: string @@ -95,7 +94,7 @@ export const migrateRelationships = async ({ globalSlug, isVersions, payload, - req: req as unknown as PayloadRequest, + req, tableName, }) } diff --git a/packages/drizzle/src/postgres/predefinedMigrations/v2-v3/traverseFields.ts b/packages/drizzle/src/postgres/predefinedMigrations/v2-v3/traverseFields.ts index 9f1995fea93..1a6b6cea2c3 100644 --- a/packages/drizzle/src/postgres/predefinedMigrations/v2-v3/traverseFields.ts +++ b/packages/drizzle/src/postgres/predefinedMigrations/v2-v3/traverseFields.ts @@ -2,15 +2,14 @@ import type { FlattenedField, Payload } from 'payload' import toSnakeCase from 'to-snake-case' -import type { TransactionPg } from '../../../types.js' -import type { BasePostgresAdapter } from '../../types.js' +import type { BasePostgresAdapter, PostgresDB } from '../../types.js' import type { PathsToQuery } from './types.js' type Args = { adapter: BasePostgresAdapter collectionSlug?: string columnPrefix: string - db: TransactionPg + db: PostgresDB disableNotNull: boolean fields: FlattenedField[] globalSlug?: string diff --git a/packages/drizzle/src/queryDrafts.ts b/packages/drizzle/src/queryDrafts.ts index 199be9953a5..dd41bd3c66a 100644 --- a/packages/drizzle/src/queryDrafts.ts +++ b/packages/drizzle/src/queryDrafts.ts @@ -1,4 +1,4 @@ -import type { PayloadRequest, QueryDrafts, SanitizedCollectionConfig } from 'payload' +import type { QueryDrafts, SanitizedCollectionConfig } from 'payload' import { buildVersionCollectionFields, combineQueries } from 'payload' import toSnakeCase from 'to-snake-case' @@ -9,18 +9,7 @@ import { findMany } from './find/findMany.js' export const queryDrafts: QueryDrafts = async function queryDrafts( this: DrizzleAdapter, - { - collection, - joins, - limit, - locale, - page = 1, - pagination, - req = {} as PayloadRequest, - select, - sort, - where, - }, + { collection, joins, limit, locale, page = 1, pagination, req, select, sort, where }, ) { const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config const tableName = this.tableNameMap.get( diff --git a/packages/drizzle/src/update.ts b/packages/drizzle/src/update.ts index 86c41e0aac1..935133fd714 100644 --- a/packages/drizzle/src/update.ts +++ b/packages/drizzle/src/update.ts @@ -8,12 +8,13 @@ import { buildFindManyArgs } from './find/buildFindManyArgs.js' import buildQuery from './queries/buildQuery.js' import { selectDistinct } from './queries/selectDistinct.js' import { upsertRow } from './upsertRow/index.js' +import { getTransaction } from './utilities/getTransaction.js' export const updateOne: UpdateOne = async function updateOne( this: DrizzleAdapter, { id, collection: collectionSlug, data, joins: joinQuery, locale, req, select, where: whereArg }, ) { - const db = this.sessions[await req?.transactionID]?.db || this.drizzle + const db = await getTransaction(this, req) const collection = this.payload.collections[collectionSlug].config const tableName = this.tableNameMap.get(toSnakeCase(collection.slug)) const whereToUse = whereArg || { id: { equals: id } } diff --git a/packages/drizzle/src/updateGlobal.ts b/packages/drizzle/src/updateGlobal.ts index b7bd6ba032b..088c42b78d0 100644 --- a/packages/drizzle/src/updateGlobal.ts +++ b/packages/drizzle/src/updateGlobal.ts @@ -1,16 +1,17 @@ -import type { PayloadRequest, UpdateGlobalArgs } from 'payload' +import type { UpdateGlobalArgs } from 'payload' import toSnakeCase from 'to-snake-case' import type { DrizzleAdapter } from './types.js' import { upsertRow } from './upsertRow/index.js' +import { getTransaction } from './utilities/getTransaction.js' export async function updateGlobal>( this: DrizzleAdapter, - { slug, data, req = {} as PayloadRequest, select }: UpdateGlobalArgs, + { slug, data, req, select }: UpdateGlobalArgs, ): Promise { - const db = this.sessions[await req?.transactionID]?.db || this.drizzle + const db = await getTransaction(this, req) const globalConfig = this.payload.globals.config.find((config) => config.slug === slug) const tableName = this.tableNameMap.get(toSnakeCase(globalConfig.slug)) diff --git a/packages/drizzle/src/updateGlobalVersion.ts b/packages/drizzle/src/updateGlobalVersion.ts index 3c5a223537f..8cb4572a358 100644 --- a/packages/drizzle/src/updateGlobalVersion.ts +++ b/packages/drizzle/src/updateGlobalVersion.ts @@ -1,5 +1,4 @@ import type { - PayloadRequest, SanitizedGlobalConfig, TypeWithID, TypeWithVersion, @@ -13,20 +12,13 @@ import type { DrizzleAdapter } from './types.js' import buildQuery from './queries/buildQuery.js' import { upsertRow } from './upsertRow/index.js' +import { getTransaction } from './utilities/getTransaction.js' export async function updateGlobalVersion( this: DrizzleAdapter, - { - id, - global, - locale, - req = {} as PayloadRequest, - select, - versionData, - where: whereArg, - }: UpdateGlobalVersionArgs, + { id, global, locale, req, select, versionData, where: whereArg }: UpdateGlobalVersionArgs, ) { - const db = this.sessions[await req?.transactionID]?.db || this.drizzle + const db = await getTransaction(this, req) const globalConfig: SanitizedGlobalConfig = this.payload.globals.config.find( ({ slug }) => slug === global, ) diff --git a/packages/drizzle/src/updateVersion.ts b/packages/drizzle/src/updateVersion.ts index 09fcaf0dbd5..d5bb55c6573 100644 --- a/packages/drizzle/src/updateVersion.ts +++ b/packages/drizzle/src/updateVersion.ts @@ -1,5 +1,4 @@ import type { - PayloadRequest, SanitizedCollectionConfig, TypeWithID, TypeWithVersion, @@ -13,20 +12,13 @@ import type { DrizzleAdapter } from './types.js' import buildQuery from './queries/buildQuery.js' import { upsertRow } from './upsertRow/index.js' +import { getTransaction } from './utilities/getTransaction.js' export async function updateVersion( this: DrizzleAdapter, - { - id, - collection, - locale, - req = {} as PayloadRequest, - select, - versionData, - where: whereArg, - }: UpdateVersionArgs, + { id, collection, locale, req, select, versionData, where: whereArg }: UpdateVersionArgs, ) { - const db = this.sessions[await req?.transactionID]?.db || this.drizzle + const db = await getTransaction(this, req) const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config const whereToUse = whereArg || { id: { equals: id } } const tableName = this.tableNameMap.get( diff --git a/packages/drizzle/src/upsertRow/index.ts b/packages/drizzle/src/upsertRow/index.ts index 07d7a365f73..a91e46ee2b4 100644 --- a/packages/drizzle/src/upsertRow/index.ts +++ b/packages/drizzle/src/upsertRow/index.ts @@ -394,12 +394,12 @@ export const upsertRow = async | TypeWithID>( id, errors: [ { - message: req.t('error:valueMustBeUnique'), + message: req?.t ? 'error:valueMustBeUnique' : 'Value must be unique', path: fieldName, }, ], }, - req.t, + req?.t, ) } else { throw error diff --git a/packages/drizzle/src/upsertRow/types.ts b/packages/drizzle/src/upsertRow/types.ts index 5f69d59bc3d..991540c7275 100644 --- a/packages/drizzle/src/upsertRow/types.ts +++ b/packages/drizzle/src/upsertRow/types.ts @@ -15,7 +15,7 @@ type BaseArgs = { ignoreResult?: boolean joinQuery?: JoinQuery path?: string - req: PayloadRequest + req?: Partial tableName: string } diff --git a/packages/drizzle/src/utilities/getTransaction.ts b/packages/drizzle/src/utilities/getTransaction.ts new file mode 100644 index 00000000000..910674fd9f7 --- /dev/null +++ b/packages/drizzle/src/utilities/getTransaction.ts @@ -0,0 +1,17 @@ +import type { PayloadRequest } from 'payload' + +import type { DrizzleAdapter } from '../types.js' + +/** + * Returns current db transaction instance from req or adapter.drizzle itself + */ +export const getTransaction = async ( + adapter: T, + req?: Partial, +): Promise => { + if (!req?.transactionID) { + return adapter.drizzle + } + + return (adapter.sessions[await req.transactionID]?.db as T['drizzle']) || adapter.drizzle +} diff --git a/packages/payload/src/auth/operations/local/forgotPassword.ts b/packages/payload/src/auth/operations/local/forgotPassword.ts index bfe7a774484..2cf8dd00ee3 100644 --- a/packages/payload/src/auth/operations/local/forgotPassword.ts +++ b/packages/payload/src/auth/operations/local/forgotPassword.ts @@ -14,7 +14,7 @@ export type Options = { } disableEmail?: boolean expiration?: number - req?: PayloadRequest + req?: Partial } async function localForgotPassword( diff --git a/packages/payload/src/auth/operations/local/login.ts b/packages/payload/src/auth/operations/local/login.ts index c3dd186d896..15b97d48d59 100644 --- a/packages/payload/src/auth/operations/local/login.ts +++ b/packages/payload/src/auth/operations/local/login.ts @@ -20,7 +20,7 @@ export type Options = { fallbackLocale?: string locale?: string overrideAccess?: boolean - req?: PayloadRequest + req?: Partial showHiddenFields?: boolean } diff --git a/packages/payload/src/auth/operations/local/resetPassword.ts b/packages/payload/src/auth/operations/local/resetPassword.ts index ec46188b069..cfcc722a044 100644 --- a/packages/payload/src/auth/operations/local/resetPassword.ts +++ b/packages/payload/src/auth/operations/local/resetPassword.ts @@ -14,7 +14,7 @@ export type Options = { token: string } overrideAccess: boolean - req?: PayloadRequest + req?: Partial } async function localResetPassword( diff --git a/packages/payload/src/auth/operations/local/unlock.ts b/packages/payload/src/auth/operations/local/unlock.ts index 9776c203285..47ee9797d8b 100644 --- a/packages/payload/src/auth/operations/local/unlock.ts +++ b/packages/payload/src/auth/operations/local/unlock.ts @@ -15,7 +15,7 @@ export type Options = { context?: RequestContext data: AuthOperationsFromCollectionSlug['unlock'] overrideAccess: boolean - req?: PayloadRequest + req?: Partial } async function localUnlock( diff --git a/packages/payload/src/auth/operations/local/verifyEmail.ts b/packages/payload/src/auth/operations/local/verifyEmail.ts index c12bae6fa8d..1d882003c86 100644 --- a/packages/payload/src/auth/operations/local/verifyEmail.ts +++ b/packages/payload/src/auth/operations/local/verifyEmail.ts @@ -8,7 +8,7 @@ import { verifyEmailOperation } from '../verifyEmail.js' export type Options = { collection: T context?: RequestContext - req?: PayloadRequest + req?: Partial token: string } diff --git a/packages/payload/src/collections/operations/local/count.ts b/packages/payload/src/collections/operations/local/count.ts index 9aa4916d61b..9b1646595e8 100644 --- a/packages/payload/src/collections/operations/local/count.ts +++ b/packages/payload/src/collections/operations/local/count.ts @@ -15,7 +15,7 @@ export type Options = { disableErrors?: boolean locale?: TypedLocale overrideAccess?: boolean - req?: PayloadRequest + req?: Partial user?: Document where?: Where } diff --git a/packages/payload/src/collections/operations/local/countVersions.ts b/packages/payload/src/collections/operations/local/countVersions.ts index 9218e9d0712..30bc96a31ee 100644 --- a/packages/payload/src/collections/operations/local/countVersions.ts +++ b/packages/payload/src/collections/operations/local/countVersions.ts @@ -15,7 +15,7 @@ export type Options = { disableErrors?: boolean locale?: TypedLocale overrideAccess?: boolean - req?: PayloadRequest + req?: Partial user?: Document where?: Where } diff --git a/packages/payload/src/collections/operations/local/create.ts b/packages/payload/src/collections/operations/local/create.ts index e680ea13920..ce8b18ff5a7 100644 --- a/packages/payload/src/collections/operations/local/create.ts +++ b/packages/payload/src/collections/operations/local/create.ts @@ -37,7 +37,7 @@ export type Options = overrideAccess?: boolean overwriteExistingFiles?: boolean populate?: PopulateType - req?: PayloadRequest + req?: Partial select?: TSelect showHiddenFields?: boolean user?: Document diff --git a/packages/payload/src/collections/operations/local/delete.ts b/packages/payload/src/collections/operations/local/delete.ts index d9e6a01478c..0680da7754c 100644 --- a/packages/payload/src/collections/operations/local/delete.ts +++ b/packages/payload/src/collections/operations/local/delete.ts @@ -27,7 +27,7 @@ export type BaseOptions select?: TSelect showHiddenFields?: boolean user?: Document diff --git a/packages/payload/src/collections/operations/local/duplicate.ts b/packages/payload/src/collections/operations/local/duplicate.ts index 747bb679da3..d4a998967cc 100644 --- a/packages/payload/src/collections/operations/local/duplicate.ts +++ b/packages/payload/src/collections/operations/local/duplicate.ts @@ -33,7 +33,7 @@ export type Options = locale?: TypedLocale overrideAccess?: boolean populate?: PopulateType - req?: PayloadRequest + req?: Partial select?: TSelect showHiddenFields?: boolean user?: Document diff --git a/packages/payload/src/collections/operations/local/find.ts b/packages/payload/src/collections/operations/local/find.ts index 2b16dea9e95..1ea8c7d0810 100644 --- a/packages/payload/src/collections/operations/local/find.ts +++ b/packages/payload/src/collections/operations/local/find.ts @@ -40,7 +40,7 @@ export type Options = page?: number pagination?: boolean populate?: PopulateType - req?: PayloadRequest + req?: Partial select?: TSelect showHiddenFields?: boolean sort?: Sort diff --git a/packages/payload/src/collections/operations/local/findByID.ts b/packages/payload/src/collections/operations/local/findByID.ts index 334e1f05df9..b2a4b273bc0 100644 --- a/packages/payload/src/collections/operations/local/findByID.ts +++ b/packages/payload/src/collections/operations/local/findByID.ts @@ -41,7 +41,7 @@ export type Options< locale?: 'all' | TypedLocale overrideAccess?: boolean populate?: PopulateType - req?: PayloadRequest + req?: Partial select?: TSelect showHiddenFields?: boolean user?: Document diff --git a/packages/payload/src/collections/operations/local/findVersionByID.ts b/packages/payload/src/collections/operations/local/findVersionByID.ts index a606e52d828..581fb5a5c18 100644 --- a/packages/payload/src/collections/operations/local/findVersionByID.ts +++ b/packages/payload/src/collections/operations/local/findVersionByID.ts @@ -21,7 +21,7 @@ export type Options = { locale?: 'all' | TypedLocale overrideAccess?: boolean populate?: PopulateType - req?: PayloadRequest + req?: Partial select?: SelectType showHiddenFields?: boolean user?: Document diff --git a/packages/payload/src/collections/operations/local/findVersions.ts b/packages/payload/src/collections/operations/local/findVersions.ts index 842cade1902..664076d9901 100644 --- a/packages/payload/src/collections/operations/local/findVersions.ts +++ b/packages/payload/src/collections/operations/local/findVersions.ts @@ -29,7 +29,7 @@ export type Options = { overrideAccess?: boolean page?: number populate?: PopulateType - req?: PayloadRequest + req?: Partial select?: SelectType showHiddenFields?: boolean sort?: Sort diff --git a/packages/payload/src/collections/operations/local/restoreVersion.ts b/packages/payload/src/collections/operations/local/restoreVersion.ts index e961b53c8c5..6ce4bff4853 100644 --- a/packages/payload/src/collections/operations/local/restoreVersion.ts +++ b/packages/payload/src/collections/operations/local/restoreVersion.ts @@ -19,7 +19,7 @@ export type Options = { locale?: TypedLocale overrideAccess?: boolean populate?: PopulateType - req?: PayloadRequest + req?: Partial select?: SelectType showHiddenFields?: boolean user?: Document diff --git a/packages/payload/src/collections/operations/local/update.ts b/packages/payload/src/collections/operations/local/update.ts index f99cadf3622..ddf0ee46240 100644 --- a/packages/payload/src/collections/operations/local/update.ts +++ b/packages/payload/src/collections/operations/local/update.ts @@ -42,7 +42,7 @@ export type BaseOptions select?: TSelect showHiddenFields?: boolean user?: Document diff --git a/packages/payload/src/database/migrations/migrate.ts b/packages/payload/src/database/migrations/migrate.ts index ecf12340629..f3e0e73191b 100644 --- a/packages/payload/src/database/migrations/migrate.ts +++ b/packages/payload/src/database/migrations/migrate.ts @@ -1,7 +1,7 @@ -import type { PayloadRequest } from '../../types/index.js' import type { BaseDatabaseAdapter } from '../types.js' import { commitTransaction } from '../../utilities/commitTransaction.js' +import { createLocalReq } from '../../utilities/createLocalReq.js' import { initTransaction } from '../../utilities/initTransaction.js' import { killTransaction } from '../../utilities/killTransaction.js' import { getMigrations } from './getMigrations.js' @@ -29,7 +29,7 @@ export const migrate: BaseDatabaseAdapter['migrate'] = async function migrate( } const start = Date.now() - const req = { payload } as PayloadRequest + const req = await createLocalReq({}, payload) payload.logger.info({ msg: `Migrating: ${migration.name}` }) diff --git a/packages/payload/src/database/migrations/migrateDown.ts b/packages/payload/src/database/migrations/migrateDown.ts index 40ae1915e11..19bcb957499 100644 --- a/packages/payload/src/database/migrations/migrateDown.ts +++ b/packages/payload/src/database/migrations/migrateDown.ts @@ -1,7 +1,7 @@ -import type { PayloadRequest } from '../../types/index.js' import type { BaseDatabaseAdapter } from '../types.js' import { commitTransaction } from '../../utilities/commitTransaction.js' +import { createLocalReq } from '../../utilities/createLocalReq.js' import { initTransaction } from '../../utilities/initTransaction.js' import { killTransaction } from '../../utilities/killTransaction.js' import { getMigrations } from './getMigrations.js' @@ -33,7 +33,7 @@ export async function migrateDown(this: BaseDatabaseAdapter): Promise { } const start = Date.now() - const req = { payload } as PayloadRequest + const req = await createLocalReq({}, payload) try { payload.logger.info({ msg: `Migrating down: ${migrationFile.name}` }) diff --git a/packages/payload/src/database/migrations/migrateRefresh.ts b/packages/payload/src/database/migrations/migrateRefresh.ts index f07d464d091..98a2d1f71cb 100644 --- a/packages/payload/src/database/migrations/migrateRefresh.ts +++ b/packages/payload/src/database/migrations/migrateRefresh.ts @@ -1,7 +1,7 @@ -import type { PayloadRequest } from '../../types/index.js' import type { BaseDatabaseAdapter } from '../types.js' import { commitTransaction } from '../../utilities/commitTransaction.js' +import { createLocalReq } from '../../utilities/createLocalReq.js' import { initTransaction } from '../../utilities/initTransaction.js' import { killTransaction } from '../../utilities/killTransaction.js' import { getMigrations } from './getMigrations.js' @@ -18,7 +18,7 @@ export async function migrateRefresh(this: BaseDatabaseAdapter) { payload, }) - const req = { payload } as PayloadRequest + const req = await createLocalReq({}, payload) if (existingMigrations?.length) { payload.logger.info({ diff --git a/packages/payload/src/database/migrations/migrateReset.ts b/packages/payload/src/database/migrations/migrateReset.ts index bb63d14ab34..10cf733e9a4 100644 --- a/packages/payload/src/database/migrations/migrateReset.ts +++ b/packages/payload/src/database/migrations/migrateReset.ts @@ -1,7 +1,7 @@ -import type { PayloadRequest } from '../../types/index.js' import type { BaseDatabaseAdapter } from '../types.js' import { commitTransaction } from '../../utilities/commitTransaction.js' +import { createLocalReq } from '../../utilities/createLocalReq.js' import { initTransaction } from '../../utilities/initTransaction.js' import { killTransaction } from '../../utilities/killTransaction.js' import { getMigrations } from './getMigrations.js' @@ -18,7 +18,7 @@ export async function migrateReset(this: BaseDatabaseAdapter): Promise { return } - const req = { payload } as PayloadRequest + const req = await createLocalReq({}, payload) // Rollback all migrations in order for (const migration of migrationFiles) { diff --git a/packages/payload/src/database/types.ts b/packages/payload/src/database/types.ts index 36a54bc14a4..cee966f9da9 100644 --- a/packages/payload/src/database/types.ts +++ b/packages/payload/src/database/types.ts @@ -191,7 +191,7 @@ export type QueryDraftsArgs = { locale?: string page?: number pagination?: boolean - req: PayloadRequest + req?: Partial select?: SelectType sort?: Sort where?: Where @@ -203,7 +203,7 @@ export type FindOneArgs = { collection: CollectionSlug joins?: JoinQuery locale?: string - req: PayloadRequest + req?: Partial select?: SelectType where?: Where } @@ -219,7 +219,7 @@ export type FindArgs = { page?: number pagination?: boolean projection?: Record - req: PayloadRequest + req?: Partial select?: SelectType skip?: number sort?: Sort @@ -232,7 +232,7 @@ export type Find = (args: FindArgs) => Promise> export type CountArgs = { collection: CollectionSlug locale?: string - req: PayloadRequest + req?: Partial where?: Where } @@ -243,7 +243,7 @@ export type CountVersions = (args: CountArgs) => Promise<{ totalDocs: number }> export type CountGlobalVersionArgs = { global: string locale?: string - req: PayloadRequest + req?: Partial where?: Where } @@ -254,7 +254,7 @@ type BaseVersionArgs = { locale?: string page?: number pagination?: boolean - req: PayloadRequest + req?: Partial select?: SelectType skip?: number sort?: Sort @@ -276,7 +276,7 @@ export type FindGlobalVersionsArgs = { export type FindGlobalArgs = { locale?: string - req: PayloadRequest + req?: Partial select?: SelectType slug: string where?: Where @@ -289,7 +289,7 @@ export type UpdateGlobalVersionArgs = { * Additional database adapter specific options to pass to the query */ options?: Record - req: PayloadRequest + req?: Partial select?: SelectType versionData: T } & ( @@ -313,7 +313,7 @@ export type FindGlobal = = any>( export type CreateGlobalArgs = any> = { data: T - req: PayloadRequest + req?: Partial slug: string } export type CreateGlobal = = any>( @@ -326,7 +326,7 @@ export type UpdateGlobalArgs = any> = { * Additional database adapter specific options to pass to the query */ options?: Record - req: PayloadRequest + req?: Partial select?: SelectType slug: string } @@ -342,7 +342,7 @@ export type FindGlobalVersions = ( export type DeleteVersionsArgs = { collection: CollectionSlug locale?: string - req: PayloadRequest + req?: Partial sort?: { [key: string]: string } @@ -356,7 +356,7 @@ export type CreateVersionArgs = { /** ID of the parent document for which the version should be created for */ parent: number | string publishedLocale?: string - req: PayloadRequest + req?: Partial select?: SelectType snapshot?: true updatedAt: string @@ -374,7 +374,7 @@ export type CreateGlobalVersionArgs = { /** ID of the parent document for which the version should be created for */ parent: number | string publishedLocale?: string - req: PayloadRequest + req?: Partial select?: SelectType snapshot?: true updatedAt: string @@ -394,7 +394,7 @@ export type UpdateVersionArgs = { * Additional database adapter specific options to pass to the query */ options?: Record - req: PayloadRequest + req?: Partial select?: SelectType versionData: T } & ( @@ -417,7 +417,7 @@ export type CreateArgs = { data: Record draft?: boolean locale?: string - req: PayloadRequest + req?: Partial select?: SelectType } @@ -433,7 +433,7 @@ export type UpdateOneArgs = { * Additional database adapter specific options to pass to the query */ options?: Record - req: PayloadRequest + req?: Partial select?: SelectType } & ( | { @@ -453,7 +453,7 @@ export type UpsertArgs = { data: Record joins?: JoinQuery locale?: string - req: PayloadRequest + req?: Partial select?: SelectType where: Where } @@ -463,7 +463,7 @@ export type Upsert = (args: UpsertArgs) => Promise export type DeleteOneArgs = { collection: CollectionSlug joins?: JoinQuery - req: PayloadRequest + req?: Partial select?: SelectType where: Where } @@ -473,7 +473,7 @@ export type DeleteOne = (args: DeleteOneArgs) => Promise export type DeleteManyArgs = { collection: CollectionSlug joins?: JoinQuery - req: PayloadRequest + req?: Partial where: Where } diff --git a/packages/payload/src/globals/operations/local/countGlobalVersions.ts b/packages/payload/src/globals/operations/local/countGlobalVersions.ts index 70a6696c71a..979cdbd54a7 100644 --- a/packages/payload/src/globals/operations/local/countGlobalVersions.ts +++ b/packages/payload/src/globals/operations/local/countGlobalVersions.ts @@ -15,7 +15,7 @@ export type CountGlobalVersionsOptions = { global: TSlug locale?: TypedLocale overrideAccess?: boolean - req?: PayloadRequest + req?: Partial user?: Document where?: Where } diff --git a/packages/payload/src/globals/operations/local/findOne.ts b/packages/payload/src/globals/operations/local/findOne.ts index 69f04541df4..1e626d1c663 100644 --- a/packages/payload/src/globals/operations/local/findOne.ts +++ b/packages/payload/src/globals/operations/local/findOne.ts @@ -21,7 +21,7 @@ export type Options = { locale?: 'all' | TypedLocale overrideAccess?: boolean populate?: PopulateType - req?: PayloadRequest + req?: Partial select?: TSelect showHiddenFields?: boolean slug: TSlug diff --git a/packages/payload/src/globals/operations/local/findVersionByID.ts b/packages/payload/src/globals/operations/local/findVersionByID.ts index 1b5fe298ba3..3cb132af4c8 100644 --- a/packages/payload/src/globals/operations/local/findVersionByID.ts +++ b/packages/payload/src/globals/operations/local/findVersionByID.ts @@ -16,7 +16,7 @@ export type Options = { locale?: 'all' | TypedLocale overrideAccess?: boolean populate?: PopulateType - req?: PayloadRequest + req?: Partial select?: SelectType showHiddenFields?: boolean slug: TSlug diff --git a/packages/payload/src/globals/operations/local/findVersions.ts b/packages/payload/src/globals/operations/local/findVersions.ts index 0393209c97c..42d78b6fc86 100644 --- a/packages/payload/src/globals/operations/local/findVersions.ts +++ b/packages/payload/src/globals/operations/local/findVersions.ts @@ -25,7 +25,7 @@ export type Options = { overrideAccess?: boolean page?: number populate?: PopulateType - req?: PayloadRequest + req?: Partial select?: SelectType showHiddenFields?: boolean slug: TSlug diff --git a/packages/payload/src/globals/operations/local/restoreVersion.ts b/packages/payload/src/globals/operations/local/restoreVersion.ts index fb9f91ba819..6b2d7b5050e 100644 --- a/packages/payload/src/globals/operations/local/restoreVersion.ts +++ b/packages/payload/src/globals/operations/local/restoreVersion.ts @@ -15,7 +15,7 @@ export type Options = { locale?: TypedLocale overrideAccess?: boolean populate?: PopulateType - req?: PayloadRequest + req?: Partial showHiddenFields?: boolean slug: TSlug user?: Document diff --git a/packages/payload/src/globals/operations/local/update.ts b/packages/payload/src/globals/operations/local/update.ts index d89a3d8ec6e..bee39bcdf7e 100644 --- a/packages/payload/src/globals/operations/local/update.ts +++ b/packages/payload/src/globals/operations/local/update.ts @@ -25,7 +25,7 @@ export type Options = { overrideLock?: boolean populate?: PopulateType publishSpecificLocale?: TypedLocale - req?: PayloadRequest + req?: Partial select?: TSelect showHiddenFields?: boolean slug: TSlug diff --git a/packages/payload/src/types/index.ts b/packages/payload/src/types/index.ts index 5c88ee67cda..6ced569e0d3 100644 --- a/packages/payload/src/types/index.ts +++ b/packages/payload/src/types/index.ts @@ -62,6 +62,7 @@ export type CustomPayloadRequestProperties = { transactionID?: number | Promise | string /** * Used to ensure consistency when multiple operations try to create a transaction concurrently on the same request + * @deprecated This is not used anywhere, instead `transactionID` is used for the above. Will be removed in next major version. */ transactionIDPromise?: Promise /** The signed-in user */ diff --git a/packages/payload/src/utilities/commitTransaction.ts b/packages/payload/src/utilities/commitTransaction.ts index 45384e31152..07d336d95b6 100644 --- a/packages/payload/src/utilities/commitTransaction.ts +++ b/packages/payload/src/utilities/commitTransaction.ts @@ -1,9 +1,13 @@ +import type { MarkRequired } from 'ts-essentials' + import type { PayloadRequest } from '../types/index.js' /** * complete a transaction calling adapter db.commitTransaction and delete the transactionID from req */ -export async function commitTransaction(req: PayloadRequest): Promise { +export async function commitTransaction( + req: MarkRequired, 'payload'>, +): Promise { const { payload, transactionID } = req await payload.db.commitTransaction(transactionID) diff --git a/packages/payload/src/utilities/initTransaction.ts b/packages/payload/src/utilities/initTransaction.ts index fbbb758b4d8..152957b811b 100644 --- a/packages/payload/src/utilities/initTransaction.ts +++ b/packages/payload/src/utilities/initTransaction.ts @@ -1,10 +1,14 @@ +import type { MarkRequired } from 'ts-essentials' + import type { PayloadRequest } from '../types/index.js' /** * Starts a new transaction using the db adapter with a random id and then assigns it to the req.transaction * @returns true if beginning a transaction and false when req already has a transaction to use */ -export async function initTransaction(req: PayloadRequest): Promise { +export async function initTransaction( + req: MarkRequired, 'payload'>, +): Promise { const { payload, transactionID } = req if (transactionID instanceof Promise) { // wait for whoever else is already creating the transaction diff --git a/packages/payload/src/utilities/killTransaction.ts b/packages/payload/src/utilities/killTransaction.ts index e8cacb4dffc..3d702d79851 100644 --- a/packages/payload/src/utilities/killTransaction.ts +++ b/packages/payload/src/utilities/killTransaction.ts @@ -1,9 +1,13 @@ +import type { MarkRequired } from 'ts-essentials' + import type { PayloadRequest } from '../types/index.js' /** * Rollback the transaction from the req using the db adapter and removes it from the req */ -export async function killTransaction(req: PayloadRequest): Promise { +export async function killTransaction( + req: MarkRequired, 'payload'>, +): Promise { const { payload, transactionID } = req if (transactionID && !(transactionID instanceof Promise)) { try {