chore!: simplify api handler (#6910)

Removes PayloadRequestWithData in favour of just PayloadRequest with
optional types for `data` and `locale`

`addDataAndFileToRequest` and `addLocalesToRequestFromData` now takes in
a single argument instead of an object

```ts
// before
await addDataAndFileToRequest({ request: req })
addLocalesToRequestFromData({ request: req })

// current
await addDataAndFileToRequest(req)
addLocalesToRequestFromData(req)
```

---------

Co-authored-by: Paul Popus <paul@nouance.io>
This commit is contained in:
Jarrod Flesch
2024-07-02 09:47:03 -04:00
committed by GitHub
parent fd7d500be1
commit 0711f880ff
231 changed files with 737 additions and 815 deletions

View File

@@ -598,15 +598,37 @@ export const Orders: CollectionConfig = {
{ {
path: '/:id/tracking', path: '/:id/tracking',
method: 'get', method: 'get',
handler: async (req, res, next) => { handler: (req) => {
const tracking = await getTrackingInfo(req.params.id) const tracking = await getTrackingInfo(req.params.id)
if (tracking) {
res.status(200).send({ tracking }) if (!tracking) {
} else { return Response.json({ error: 'not found' }, { status: 404})
res.status(404).send({ error: 'not found' })
} }
return Response.json({
message: `Hello ${req.routeParams.name as string} @ ${req.routeParams.group as string}`,
})
}, },
}, },
{
path: '/:id/tracking',
method: 'post',
handler: (req) => {
// `data` is not automatically appended to the request
// if you would like to read the body of the request
// you can use `data = await req.json()`
const data = await req.json()
await req.payload.update({
collection: 'tracking',
data: {
// data to update the document with
}
})
return Response.json({
message: 'successfully updated tracking info'
})
}
}
], ],
// highlight-end // highlight-end
} }
@@ -619,6 +641,56 @@ export const Orders: CollectionConfig = {
calls like req.payload.find() that will make use of access control and hooks. calls like req.payload.find() that will make use of access control and hooks.
</Banner> </Banner>
#### Helpful tips
`req.data`
Data is not automatically appended to the request. You can read the body data by calling `await req.json()`.
Or you could use our helper function that mutates the request and appends data and file if found.
```ts
import { addDataAndFileToRequest } from '@payloadcms/next/utilities'
// custom endpoint example
{
path: '/:id/tracking',
method: 'post',
handler: (req) => {
await addDataAndFileToRequest(req)
await req.payload.update({
collection: 'tracking',
data: {
// data to update the document with
}
})
return Response.json({
message: 'successfully updated tracking info'
})
}
}
```
`req.locale` & `req.fallbackLocale`
The locale and the fallback locale are not automatically appended to custom endpoint requests. If you would like to add them you can use this helper function.
```ts
import { addLocalesToRequestFromData } from '@payloadcms/next/utilities'
// custom endpoint example
{
path: '/:id/tracking',
method: 'post',
handler: (req) => {
await addLocalesToRequestFromData(req)
// you now can access req.locale & req.fallbackLocale
return Response.json({ message: 'success' })
}
}
```
## Method Override for GET Requests ## Method Override for GET Requests
Payload supports a method override feature that allows you to send GET requests using the HTTP POST method. This can be particularly useful in scenarios when the query string in a regular GET request is too long. Payload supports a method override feature that allows you to send GET requests using the HTTP POST method. This can be particularly useful in scenarios when the query string in a regular GET request is too long.

View File

@@ -1,7 +1,7 @@
'use client' 'use client'
import type { Permissions } from 'payload/auth' import type { Permissions } from 'payload/auth'
import type { PayloadRequestWithData } from 'payload/types' import type { PayloadRequest } from 'payload/types'
import { useEffect } from 'react' import { useEffect } from 'react'
@@ -9,7 +9,7 @@ import { useAuth } from '../../_providers/Auth'
export const HydrateClientUser: React.FC<{ export const HydrateClientUser: React.FC<{
permissions: Permissions permissions: Permissions
user: PayloadRequestWithData['user'] user: PayloadRequest['user']
}> = ({ permissions, user }) => { }> = ({ permissions, user }) => {
const { setPermissions, setUser } = useAuth() const { setPermissions, setUser } = useAuth()

View File

@@ -1,5 +1,5 @@
import type { QueryOptions } from 'mongoose' import type { QueryOptions } from 'mongoose'
import type { Count, PayloadRequestWithData } from 'payload' import type { Count, PayloadRequest } from 'payload'
import { flattenWhereToOperators } from 'payload' import { flattenWhereToOperators } from 'payload'
@@ -9,7 +9,7 @@ import { withSession } from './withSession.js'
export const count: Count = async function count( export const count: Count = async function count(
this: MongooseAdapter, this: MongooseAdapter,
{ collection, locale, req = {} as PayloadRequestWithData, where }, { collection, locale, req = {} as PayloadRequest, where },
) { ) {
const Model = this.collections[collection] const Model = this.collections[collection]
const options: QueryOptions = withSession(this, req.transactionID) const options: QueryOptions = withSession(this, req.transactionID)

View File

@@ -1,4 +1,4 @@
import type { Create, Document, PayloadRequestWithData } from 'payload' import type { Create, Document, PayloadRequest } from 'payload'
import type { MongooseAdapter } from './index.js' import type { MongooseAdapter } from './index.js'
@@ -7,7 +7,7 @@ import { withSession } from './withSession.js'
export const create: Create = async function create( export const create: Create = async function create(
this: MongooseAdapter, this: MongooseAdapter,
{ collection, data, req = {} as PayloadRequestWithData }, { collection, data, req = {} as PayloadRequest },
) { ) {
const Model = this.collections[collection] const Model = this.collections[collection]
const options = withSession(this, req.transactionID) const options = withSession(this, req.transactionID)

View File

@@ -1,4 +1,4 @@
import type { CreateGlobal, PayloadRequestWithData } from 'payload' import type { CreateGlobal, PayloadRequest } from 'payload'
import type { MongooseAdapter } from './index.js' import type { MongooseAdapter } from './index.js'
@@ -7,7 +7,7 @@ import { withSession } from './withSession.js'
export const createGlobal: CreateGlobal = async function createGlobal( export const createGlobal: CreateGlobal = async function createGlobal(
this: MongooseAdapter, this: MongooseAdapter,
{ slug, data, req = {} as PayloadRequestWithData }, { slug, data, req = {} as PayloadRequest },
) { ) {
const Model = this.globals const Model = this.globals
const global = { const global = {

View File

@@ -1,4 +1,4 @@
import type { CreateGlobalVersion, Document, PayloadRequestWithData } from 'payload' import type { CreateGlobalVersion, Document, PayloadRequest } from 'payload'
import type { MongooseAdapter } from './index.js' import type { MongooseAdapter } from './index.js'
@@ -6,15 +6,7 @@ import { withSession } from './withSession.js'
export const createGlobalVersion: CreateGlobalVersion = async function createGlobalVersion( export const createGlobalVersion: CreateGlobalVersion = async function createGlobalVersion(
this: MongooseAdapter, this: MongooseAdapter,
{ { autosave, createdAt, globalSlug, parent, req = {} as PayloadRequest, updatedAt, versionData },
autosave,
createdAt,
globalSlug,
parent,
req = {} as PayloadRequestWithData,
updatedAt,
versionData,
},
) { ) {
const VersionModel = this.versions[globalSlug] const VersionModel = this.versions[globalSlug]
const options = withSession(this, req.transactionID) const options = withSession(this, req.transactionID)

View File

@@ -1,4 +1,4 @@
import type { CreateVersion, Document, PayloadRequestWithData } from 'payload' import type { CreateVersion, Document, PayloadRequest } from 'payload'
import type { MongooseAdapter } from './index.js' import type { MongooseAdapter } from './index.js'
@@ -11,7 +11,7 @@ export const createVersion: CreateVersion = async function createVersion(
collectionSlug, collectionSlug,
createdAt, createdAt,
parent, parent,
req = {} as PayloadRequestWithData, req = {} as PayloadRequest,
updatedAt, updatedAt,
versionData, versionData,
}, },

View File

@@ -1,4 +1,4 @@
import type { DeleteMany, PayloadRequestWithData } from 'payload' import type { DeleteMany, PayloadRequest } from 'payload'
import type { MongooseAdapter } from './index.js' import type { MongooseAdapter } from './index.js'
@@ -6,7 +6,7 @@ import { withSession } from './withSession.js'
export const deleteMany: DeleteMany = async function deleteMany( export const deleteMany: DeleteMany = async function deleteMany(
this: MongooseAdapter, this: MongooseAdapter,
{ collection, req = {} as PayloadRequestWithData, where }, { collection, req = {} as PayloadRequest, where },
) { ) {
const Model = this.collections[collection] const Model = this.collections[collection]
const options = { const options = {

View File

@@ -1,4 +1,4 @@
import type { DeleteOne, Document, PayloadRequestWithData } from 'payload' import type { DeleteOne, Document, PayloadRequest } from 'payload'
import type { MongooseAdapter } from './index.js' import type { MongooseAdapter } from './index.js'
@@ -7,7 +7,7 @@ import { withSession } from './withSession.js'
export const deleteOne: DeleteOne = async function deleteOne( export const deleteOne: DeleteOne = async function deleteOne(
this: MongooseAdapter, this: MongooseAdapter,
{ collection, req = {} as PayloadRequestWithData, where }, { collection, req = {} as PayloadRequest, where },
) { ) {
const Model = this.collections[collection] const Model = this.collections[collection]
const options = withSession(this, req.transactionID) const options = withSession(this, req.transactionID)

View File

@@ -1,4 +1,4 @@
import type { DeleteVersions, PayloadRequestWithData } from 'payload' import type { DeleteVersions, PayloadRequest } from 'payload'
import type { MongooseAdapter } from './index.js' import type { MongooseAdapter } from './index.js'
@@ -6,7 +6,7 @@ import { withSession } from './withSession.js'
export const deleteVersions: DeleteVersions = async function deleteVersions( export const deleteVersions: DeleteVersions = async function deleteVersions(
this: MongooseAdapter, this: MongooseAdapter,
{ collection, locale, req = {} as PayloadRequestWithData, where }, { collection, locale, req = {} as PayloadRequest, where },
) { ) {
const VersionsModel = this.versions[collection] const VersionsModel = this.versions[collection]
const options = { const options = {

View File

@@ -1,5 +1,5 @@
import type { PaginateOptions } from 'mongoose' import type { PaginateOptions } from 'mongoose'
import type { Find, PayloadRequestWithData } from 'payload' import type { Find, PayloadRequest } from 'payload'
import { flattenWhereToOperators } from 'payload' import { flattenWhereToOperators } from 'payload'
@@ -11,16 +11,7 @@ import { withSession } from './withSession.js'
export const find: Find = async function find( export const find: Find = async function find(
this: MongooseAdapter, this: MongooseAdapter,
{ { collection, limit, locale, page, pagination, req = {} as PayloadRequest, sort: sortArg, where },
collection,
limit,
locale,
page,
pagination,
req = {} as PayloadRequestWithData,
sort: sortArg,
where,
},
) { ) {
const Model = this.collections[collection] const Model = this.collections[collection]
const collectionConfig = this.payload.collections[collection].config const collectionConfig = this.payload.collections[collection].config

View File

@@ -1,4 +1,4 @@
import type { FindGlobal, PayloadRequestWithData } from 'payload' import type { FindGlobal, PayloadRequest } from 'payload'
import { combineQueries } from 'payload' import { combineQueries } from 'payload'
@@ -9,7 +9,7 @@ import { withSession } from './withSession.js'
export const findGlobal: FindGlobal = async function findGlobal( export const findGlobal: FindGlobal = async function findGlobal(
this: MongooseAdapter, this: MongooseAdapter,
{ slug, locale, req = {} as PayloadRequestWithData, where }, { slug, locale, req = {} as PayloadRequest, where },
) { ) {
const Model = this.globals const Model = this.globals
const options = { const options = {

View File

@@ -1,5 +1,5 @@
import type { PaginateOptions } from 'mongoose' import type { PaginateOptions } from 'mongoose'
import type { FindGlobalVersions, PayloadRequestWithData } from 'payload' import type { FindGlobalVersions, PayloadRequest } from 'payload'
import { buildVersionGlobalFields, flattenWhereToOperators } from 'payload' import { buildVersionGlobalFields, flattenWhereToOperators } from 'payload'
@@ -17,7 +17,7 @@ export const findGlobalVersions: FindGlobalVersions = async function findGlobalV
locale, locale,
page, page,
pagination, pagination,
req = {} as PayloadRequestWithData, req = {} as PayloadRequest,
skip, skip,
sort: sortArg, sort: sortArg,
where, where,

View File

@@ -1,5 +1,5 @@
import type { MongooseQueryOptions } from 'mongoose' import type { MongooseQueryOptions } from 'mongoose'
import type { Document, FindOne, PayloadRequestWithData } from 'payload' import type { Document, FindOne, PayloadRequest } from 'payload'
import type { MongooseAdapter } from './index.js' import type { MongooseAdapter } from './index.js'
@@ -8,7 +8,7 @@ import { withSession } from './withSession.js'
export const findOne: FindOne = async function findOne( export const findOne: FindOne = async function findOne(
this: MongooseAdapter, this: MongooseAdapter,
{ collection, locale, req = {} as PayloadRequestWithData, where }, { collection, locale, req = {} as PayloadRequest, where },
) { ) {
const Model = this.collections[collection] const Model = this.collections[collection]
const options: MongooseQueryOptions = { const options: MongooseQueryOptions = {

View File

@@ -1,5 +1,5 @@
import type { PaginateOptions } from 'mongoose' import type { PaginateOptions } from 'mongoose'
import type { FindVersions, PayloadRequestWithData } from 'payload' import type { FindVersions, PayloadRequest } from 'payload'
import { flattenWhereToOperators } from 'payload' import { flattenWhereToOperators } from 'payload'
@@ -17,7 +17,7 @@ export const findVersions: FindVersions = async function findVersions(
locale, locale,
page, page,
pagination, pagination,
req = {} as PayloadRequestWithData, req = {} as PayloadRequest,
skip, skip,
sort: sortArg, sort: sortArg,
where, where,

View File

@@ -1,4 +1,4 @@
import type { PayloadRequestWithData } from 'payload' import type { PayloadRequest } from 'payload'
import { commitTransaction, initTransaction, killTransaction, readMigrationFiles } from 'payload' import { commitTransaction, initTransaction, killTransaction, readMigrationFiles } from 'payload'
import prompts from 'prompts' import prompts from 'prompts'
@@ -45,7 +45,7 @@ export async function migrateFresh(
msg: `Found ${migrationFiles.length} migration files.`, msg: `Found ${migrationFiles.length} migration files.`,
}) })
const req = { payload } as PayloadRequestWithData const req = { payload } as PayloadRequest
// Run all migrate up // Run all migrate up
for (const migration of migrationFiles) { for (const migration of migrationFiles) {

View File

@@ -1,5 +1,5 @@
import type { PaginateOptions } from 'mongoose' import type { PaginateOptions } from 'mongoose'
import type { PayloadRequestWithData, QueryDrafts } from 'payload' import type { PayloadRequest, QueryDrafts } from 'payload'
import { combineQueries, flattenWhereToOperators } from 'payload' import { combineQueries, flattenWhereToOperators } from 'payload'
@@ -11,16 +11,7 @@ import { withSession } from './withSession.js'
export const queryDrafts: QueryDrafts = async function queryDrafts( export const queryDrafts: QueryDrafts = async function queryDrafts(
this: MongooseAdapter, this: MongooseAdapter,
{ { collection, limit, locale, page, pagination, req = {} as PayloadRequest, sort: sortArg, where },
collection,
limit,
locale,
page,
pagination,
req = {} as PayloadRequestWithData,
sort: sortArg,
where,
},
) { ) {
const VersionModel = this.versions[collection] const VersionModel = this.versions[collection]
const collectionConfig = this.payload.collections[collection].config const collectionConfig = this.payload.collections[collection].config

View File

@@ -1,4 +1,4 @@
import type { PayloadRequestWithData, UpdateGlobal } from 'payload' import type { PayloadRequest, UpdateGlobal } from 'payload'
import type { MongooseAdapter } from './index.js' import type { MongooseAdapter } from './index.js'
@@ -7,7 +7,7 @@ import { withSession } from './withSession.js'
export const updateGlobal: UpdateGlobal = async function updateGlobal( export const updateGlobal: UpdateGlobal = async function updateGlobal(
this: MongooseAdapter, this: MongooseAdapter,
{ slug, data, req = {} as PayloadRequestWithData }, { slug, data, req = {} as PayloadRequest },
) { ) {
const Model = this.globals const Model = this.globals
const options = { const options = {

View File

@@ -1,4 +1,4 @@
import type { PayloadRequestWithData, TypeWithID, UpdateGlobalVersionArgs } from 'payload' import type { PayloadRequest, TypeWithID, UpdateGlobalVersionArgs } from 'payload'
import type { MongooseAdapter } from './index.js' import type { MongooseAdapter } from './index.js'
@@ -10,7 +10,7 @@ export async function updateGlobalVersion<T extends TypeWithID>(
id, id,
global, global,
locale, locale,
req = {} as PayloadRequestWithData, req = {} as PayloadRequest,
versionData, versionData,
where, where,
}: UpdateGlobalVersionArgs<T>, }: UpdateGlobalVersionArgs<T>,

View File

@@ -1,4 +1,4 @@
import type { PayloadRequestWithData, UpdateOne } from 'payload' import type { PayloadRequest, UpdateOne } from 'payload'
import type { MongooseAdapter } from './index.js' import type { MongooseAdapter } from './index.js'
@@ -8,7 +8,7 @@ import { withSession } from './withSession.js'
export const updateOne: UpdateOne = async function updateOne( export const updateOne: UpdateOne = async function updateOne(
this: MongooseAdapter, this: MongooseAdapter,
{ id, collection, data, locale, req = {} as PayloadRequestWithData, where: whereArg }, { id, collection, data, locale, req = {} as PayloadRequest, where: whereArg },
) { ) {
const where = id ? { id: { equals: id } } : whereArg const where = id ? { id: { equals: id } } : whereArg
const Model = this.collections[collection] const Model = this.collections[collection]

View File

@@ -1,4 +1,4 @@
import type { PayloadRequestWithData, UpdateVersion } from 'payload' import type { PayloadRequest, UpdateVersion } from 'payload'
import type { MongooseAdapter } from './index.js' import type { MongooseAdapter } from './index.js'
@@ -6,7 +6,7 @@ import { withSession } from './withSession.js'
export const updateVersion: UpdateVersion = async function updateVersion( export const updateVersion: UpdateVersion = async function updateVersion(
this: MongooseAdapter, this: MongooseAdapter,
{ id, collection, locale, req = {} as PayloadRequestWithData, versionData, where }, { id, collection, locale, req = {} as PayloadRequest, versionData, where },
) { ) {
const VersionModel = this.versions[collection] const VersionModel = this.versions[collection]
const whereToUse = where || { id: { equals: id } } const whereToUse = where || { id: { equals: id } }

View File

@@ -1,4 +1,4 @@
import type { CreateGlobalArgs, PayloadRequestWithData } from 'payload' import type { CreateGlobalArgs, PayloadRequest } from 'payload'
import toSnakeCase from 'to-snake-case' import toSnakeCase from 'to-snake-case'
@@ -8,7 +8,7 @@ import { upsertRow } from './upsertRow/index.js'
export async function createGlobal<T extends Record<string, unknown>>( export async function createGlobal<T extends Record<string, unknown>>(
this: PostgresAdapter, this: PostgresAdapter,
{ slug, data, req = {} as PayloadRequestWithData }: CreateGlobalArgs, { slug, data, req = {} as PayloadRequest }: CreateGlobalArgs,
): Promise<T> { ): Promise<T> {
const db = this.sessions[req.transactionID]?.db || this.drizzle const db = this.sessions[req.transactionID]?.db || this.drizzle
const globalConfig = this.payload.globals.config.find((config) => config.slug === slug) const globalConfig = this.payload.globals.config.find((config) => config.slug === slug)

View File

@@ -1,4 +1,4 @@
import type { PayloadRequestWithData, TypeWithID, TypeWithVersion } from 'payload' import type { PayloadRequest, TypeWithID, TypeWithVersion } from 'payload'
import { sql } from 'drizzle-orm' import { sql } from 'drizzle-orm'
import { type CreateGlobalVersionArgs, buildVersionGlobalFields } from 'payload' import { type CreateGlobalVersionArgs, buildVersionGlobalFields } from 'payload'
@@ -10,12 +10,7 @@ import { upsertRow } from './upsertRow/index.js'
export async function createGlobalVersion<T extends TypeWithID>( export async function createGlobalVersion<T extends TypeWithID>(
this: PostgresAdapter, this: PostgresAdapter,
{ { autosave, globalSlug, req = {} as PayloadRequest, versionData }: CreateGlobalVersionArgs,
autosave,
globalSlug,
req = {} as PayloadRequestWithData,
versionData,
}: CreateGlobalVersionArgs,
) { ) {
const db = this.sessions[req.transactionID]?.db || this.drizzle const db = this.sessions[req.transactionID]?.db || this.drizzle
const global = this.payload.globals.config.find(({ slug }) => slug === globalSlug) const global = this.payload.globals.config.find(({ slug }) => slug === globalSlug)

View File

@@ -1,9 +1,4 @@
import type { import type { CreateVersionArgs, PayloadRequest, TypeWithID, TypeWithVersion } from 'payload'
CreateVersionArgs,
PayloadRequestWithData,
TypeWithID,
TypeWithVersion,
} from 'payload'
import { sql } from 'drizzle-orm' import { sql } from 'drizzle-orm'
import { buildVersionCollectionFields } from 'payload' import { buildVersionCollectionFields } from 'payload'
@@ -19,7 +14,7 @@ export async function createVersion<T extends TypeWithID>(
autosave, autosave,
collectionSlug, collectionSlug,
parent, parent,
req = {} as PayloadRequestWithData, req = {} as PayloadRequest,
versionData, versionData,
}: CreateVersionArgs<T>, }: CreateVersionArgs<T>,
) { ) {

View File

@@ -1,4 +1,4 @@
import type { DeleteMany, PayloadRequestWithData } from 'payload' import type { DeleteMany, PayloadRequest } from 'payload'
import { inArray } from 'drizzle-orm' import { inArray } from 'drizzle-orm'
import toSnakeCase from 'to-snake-case' import toSnakeCase from 'to-snake-case'
@@ -9,7 +9,7 @@ import { findMany } from './find/findMany.js'
export const deleteMany: DeleteMany = async function deleteMany( export const deleteMany: DeleteMany = async function deleteMany(
this: PostgresAdapter, this: PostgresAdapter,
{ collection, req = {} as PayloadRequestWithData, where }, { collection, req = {} as PayloadRequest, where },
) { ) {
const db = this.sessions[req.transactionID]?.db || this.drizzle const db = this.sessions[req.transactionID]?.db || this.drizzle
const collectionConfig = this.payload.collections[collection].config const collectionConfig = this.payload.collections[collection].config

View File

@@ -1,4 +1,4 @@
import type { DeleteOne, PayloadRequestWithData } from 'payload' import type { DeleteOne, PayloadRequest } from 'payload'
import { eq } from 'drizzle-orm' import { eq } from 'drizzle-orm'
import toSnakeCase from 'to-snake-case' import toSnakeCase from 'to-snake-case'
@@ -12,7 +12,7 @@ import { transform } from './transform/read/index.js'
export const deleteOne: DeleteOne = async function deleteOne( export const deleteOne: DeleteOne = async function deleteOne(
this: PostgresAdapter, this: PostgresAdapter,
{ collection: collectionSlug, req = {} as PayloadRequestWithData, where: whereArg }, { collection: collectionSlug, req = {} as PayloadRequest, where: whereArg },
) { ) {
const db = this.sessions[req.transactionID]?.db || this.drizzle const db = this.sessions[req.transactionID]?.db || this.drizzle
const collection = this.payload.collections[collectionSlug].config const collection = this.payload.collections[collectionSlug].config

View File

@@ -1,4 +1,4 @@
import type { DeleteVersions, PayloadRequestWithData, SanitizedCollectionConfig } from 'payload' import type { DeleteVersions, PayloadRequest, SanitizedCollectionConfig } from 'payload'
import { inArray } from 'drizzle-orm' import { inArray } from 'drizzle-orm'
import { buildVersionCollectionFields } from 'payload' import { buildVersionCollectionFields } from 'payload'
@@ -10,7 +10,7 @@ import { findMany } from './find/findMany.js'
export const deleteVersions: DeleteVersions = async function deleteVersion( export const deleteVersions: DeleteVersions = async function deleteVersion(
this: PostgresAdapter, this: PostgresAdapter,
{ collection, locale, req = {} as PayloadRequestWithData, where: where }, { collection, locale, req = {} as PayloadRequest, where: where },
) { ) {
const db = this.sessions[req.transactionID]?.db || this.drizzle const db = this.sessions[req.transactionID]?.db || this.drizzle
const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config

View File

@@ -1,4 +1,4 @@
import type { Find, PayloadRequestWithData, SanitizedCollectionConfig } from 'payload' import type { Find, PayloadRequest, SanitizedCollectionConfig } from 'payload'
import toSnakeCase from 'to-snake-case' import toSnakeCase from 'to-snake-case'
@@ -14,7 +14,7 @@ export const find: Find = async function find(
locale, locale,
page = 1, page = 1,
pagination, pagination,
req = {} as PayloadRequestWithData, req = {} as PayloadRequest,
sort: sortArg, sort: sortArg,
where, where,
}, },

View File

@@ -1,4 +1,4 @@
import type { Field, FindArgs, PayloadRequestWithData, TypeWithID } from 'payload' import type { Field, FindArgs, PayloadRequest, TypeWithID } from 'payload'
import { inArray, sql } from 'drizzle-orm' import { inArray, sql } from 'drizzle-orm'
@@ -24,7 +24,7 @@ export const findMany = async function find({
locale, locale,
page = 1, page = 1,
pagination, pagination,
req = {} as PayloadRequestWithData, req = {} as PayloadRequest,
skip, skip,
sort, sort,
tableName, tableName,

View File

@@ -1,4 +1,4 @@
import type { FindGlobalVersions, PayloadRequestWithData, SanitizedGlobalConfig } from 'payload' import type { FindGlobalVersions, PayloadRequest, SanitizedGlobalConfig } from 'payload'
import { buildVersionGlobalFields } from 'payload' import { buildVersionGlobalFields } from 'payload'
import toSnakeCase from 'to-snake-case' import toSnakeCase from 'to-snake-case'
@@ -15,7 +15,7 @@ export const findGlobalVersions: FindGlobalVersions = async function findGlobalV
locale, locale,
page, page,
pagination, pagination,
req = {} as PayloadRequestWithData, req = {} as PayloadRequest,
skip, skip,
sort: sortArg, sort: sortArg,
where, where,

View File

@@ -1,9 +1,4 @@
import type { import type { FindOneArgs, PayloadRequest, SanitizedCollectionConfig, TypeWithID } from 'payload'
FindOneArgs,
PayloadRequestWithData,
SanitizedCollectionConfig,
TypeWithID,
} from 'payload'
import toSnakeCase from 'to-snake-case' import toSnakeCase from 'to-snake-case'
@@ -13,7 +8,7 @@ import { findMany } from './find/findMany.js'
export async function findOne<T extends TypeWithID>( export async function findOne<T extends TypeWithID>(
this: PostgresAdapter, this: PostgresAdapter,
{ collection, locale, req = {} as PayloadRequestWithData, where }: FindOneArgs, { collection, locale, req = {} as PayloadRequest, where }: FindOneArgs,
): Promise<T> { ): Promise<T> {
const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config

View File

@@ -1,4 +1,4 @@
import type { FindVersions, PayloadRequestWithData, SanitizedCollectionConfig } from 'payload' import type { FindVersions, PayloadRequest, SanitizedCollectionConfig } from 'payload'
import { buildVersionCollectionFields } from 'payload' import { buildVersionCollectionFields } from 'payload'
import toSnakeCase from 'to-snake-case' import toSnakeCase from 'to-snake-case'
@@ -15,7 +15,7 @@ export const findVersions: FindVersions = async function findVersions(
locale, locale,
page, page,
pagination, pagination,
req = {} as PayloadRequestWithData, req = {} as PayloadRequest,
skip, skip,
sort: sortArg, sort: sortArg,
where, where,

View File

@@ -1,6 +1,6 @@
/* eslint-disable no-restricted-syntax, no-await-in-loop */ /* eslint-disable no-restricted-syntax, no-await-in-loop */
import type { Payload } from 'payload' import type { Payload } from 'payload'
import type { PayloadRequestWithData } from 'payload' import type { PayloadRequest } from 'payload'
import type { Migration } from 'payload' import type { Migration } from 'payload'
import { createRequire } from 'module' import { createRequire } from 'module'
@@ -83,7 +83,7 @@ async function runMigrationFile(payload: Payload, migration: Migration, batch: n
const { generateDrizzleJson } = require('drizzle-kit/payload') const { generateDrizzleJson } = require('drizzle-kit/payload')
const start = Date.now() const start = Date.now()
const req = { payload } as PayloadRequestWithData const req = { payload } as PayloadRequest
payload.logger.info({ msg: `Migrating: ${migration.name}` }) payload.logger.info({ msg: `Migrating: ${migration.name}` })

View File

@@ -1,5 +1,5 @@
/* eslint-disable no-restricted-syntax, no-await-in-loop */ /* eslint-disable no-restricted-syntax, no-await-in-loop */
import type { PayloadRequestWithData } from 'payload' import type { PayloadRequest } from 'payload'
import { import {
commitTransaction, commitTransaction,
@@ -40,7 +40,7 @@ export async function migrateDown(this: PostgresAdapter): Promise<void> {
} }
const start = Date.now() const start = Date.now()
const req = { payload } as PayloadRequestWithData const req = { payload } as PayloadRequest
try { try {
payload.logger.info({ msg: `Migrating down: ${migrationFile.name}` }) payload.logger.info({ msg: `Migrating down: ${migrationFile.name}` })

View File

@@ -1,4 +1,4 @@
import type { PayloadRequestWithData } from 'payload' import type { PayloadRequest } from 'payload'
import { sql } from 'drizzle-orm' import { sql } from 'drizzle-orm'
import { commitTransaction, initTransaction, killTransaction, readMigrationFiles } from 'payload' import { commitTransaction, initTransaction, killTransaction, readMigrationFiles } from 'payload'
@@ -51,7 +51,7 @@ export async function migrateFresh(
msg: `Found ${migrationFiles.length} migration files.`, msg: `Found ${migrationFiles.length} migration files.`,
}) })
const req = { payload } as PayloadRequestWithData const req = { payload } as PayloadRequest
// Run all migrate up // Run all migrate up
for (const migration of migrationFiles) { for (const migration of migrationFiles) {
payload.logger.info({ msg: `Migrating: ${migration.name}` }) payload.logger.info({ msg: `Migrating: ${migration.name}` })

View File

@@ -1,5 +1,5 @@
/* eslint-disable no-restricted-syntax, no-await-in-loop */ /* eslint-disable no-restricted-syntax, no-await-in-loop */
import type { PayloadRequestWithData } from 'payload' import type { PayloadRequest } from 'payload'
import { import {
commitTransaction, commitTransaction,
@@ -34,7 +34,7 @@ export async function migrateRefresh(this: PostgresAdapter) {
msg: `Rolling back batch ${latestBatch} consisting of ${existingMigrations.length} migration(s).`, msg: `Rolling back batch ${latestBatch} consisting of ${existingMigrations.length} migration(s).`,
}) })
const req = { payload } as PayloadRequestWithData const req = { payload } as PayloadRequest
// Reverse order of migrations to rollback // Reverse order of migrations to rollback
existingMigrations.reverse() existingMigrations.reverse()

View File

@@ -1,5 +1,5 @@
/* eslint-disable no-restricted-syntax, no-await-in-loop */ /* eslint-disable no-restricted-syntax, no-await-in-loop */
import type { PayloadRequestWithData } from 'payload' import type { PayloadRequest } from 'payload'
import { import {
commitTransaction, commitTransaction,
@@ -27,7 +27,7 @@ export async function migrateReset(this: PostgresAdapter): Promise<void> {
return return
} }
const req = { payload } as PayloadRequestWithData const req = { payload } as PayloadRequest
// Rollback all migrations in order // Rollback all migrations in order
for (const migration of existingMigrations) { for (const migration of existingMigrations) {

View File

@@ -1,4 +1,4 @@
import type { Field, Payload, PayloadRequestWithData } from 'payload' import type { Field, Payload, PayloadRequest } from 'payload'
import type { DrizzleTransaction, PostgresAdapter } from '../../../types.js' import type { DrizzleTransaction, PostgresAdapter } from '../../../types.js'
import type { DocsToResave } from '../types.js' import type { DocsToResave } from '../types.js'
@@ -16,7 +16,7 @@ type Args = {
globalSlug?: string globalSlug?: string
isVersions: boolean isVersions: boolean
payload: Payload payload: Payload
req: PayloadRequestWithData req: PayloadRequest
tableName: string tableName: string
} }

View File

@@ -1,5 +1,5 @@
import type { DrizzleSnapshotJSON } from 'drizzle-kit/payload' import type { DrizzleSnapshotJSON } from 'drizzle-kit/payload'
import type { Payload, PayloadRequestWithData } from 'payload' import type { Payload, PayloadRequest } from 'payload'
import { sql } from 'drizzle-orm' import { sql } from 'drizzle-orm'
import fs from 'fs' import fs from 'fs'
@@ -19,7 +19,7 @@ const require = createRequire(import.meta.url)
type Args = { type Args = {
debug?: boolean debug?: boolean
payload: Payload payload: Payload
req?: Partial<PayloadRequestWithData> req?: Partial<PayloadRequest>
} }
/** /**

View File

@@ -1,4 +1,4 @@
import type { Field, Payload, PayloadRequestWithData } from 'payload' import type { Field, Payload, PayloadRequest } from 'payload'
import { sql } from 'drizzle-orm' import { sql } from 'drizzle-orm'
@@ -17,7 +17,7 @@ type Args = {
isVersions: boolean isVersions: boolean
pathsToQuery: PathsToQuery pathsToQuery: PathsToQuery
payload: Payload payload: Payload
req?: Partial<PayloadRequestWithData> req?: Partial<PayloadRequest>
tableName: string tableName: string
} }
@@ -88,7 +88,7 @@ export const migrateRelationships = async ({
globalSlug, globalSlug,
isVersions, isVersions,
payload, payload,
req: req as unknown as PayloadRequestWithData, req: req as unknown as PayloadRequest,
tableName, tableName,
}) })
} }

View File

@@ -1,4 +1,4 @@
import type { PayloadRequestWithData, SanitizedCollectionConfig } from 'payload' import type { PayloadRequest, SanitizedCollectionConfig } from 'payload'
import { type QueryDrafts, buildVersionCollectionFields, combineQueries } from 'payload' import { type QueryDrafts, buildVersionCollectionFields, combineQueries } from 'payload'
import toSnakeCase from 'to-snake-case' import toSnakeCase from 'to-snake-case'
@@ -9,16 +9,7 @@ import { findMany } from './find/findMany.js'
export const queryDrafts: QueryDrafts = async function queryDrafts( export const queryDrafts: QueryDrafts = async function queryDrafts(
this: PostgresAdapter, this: PostgresAdapter,
{ { collection, limit, locale, page = 1, pagination, req = {} as PayloadRequest, sort, where },
collection,
limit,
locale,
page = 1,
pagination,
req = {} as PayloadRequestWithData,
sort,
where,
},
) { ) {
const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config
const tableName = this.tableNameMap.get( const tableName = this.tableNameMap.get(

View File

@@ -15,7 +15,7 @@ import type {
PgTransaction, PgTransaction,
} from 'drizzle-orm/pg-core' } from 'drizzle-orm/pg-core'
import type { PgTableFn } from 'drizzle-orm/pg-core/table' import type { PgTableFn } from 'drizzle-orm/pg-core/table'
import type { BaseDatabaseAdapter, Payload, PayloadRequestWithData } from 'payload' import type { BaseDatabaseAdapter, Payload, PayloadRequest } from 'payload'
import type { Pool, PoolConfig } from 'pg' import type { Pool, PoolConfig } from 'pg'
export type DrizzleDB = NodePgDatabase<Record<string, unknown>> export type DrizzleDB = NodePgDatabase<Record<string, unknown>>
@@ -96,8 +96,8 @@ export type IDType = 'integer' | 'numeric' | 'uuid' | 'varchar'
export type PostgresAdapterResult = (args: { payload: Payload }) => PostgresAdapter export type PostgresAdapterResult = (args: { payload: Payload }) => PostgresAdapter
export type MigrateUpArgs = { payload: Payload; req?: Partial<PayloadRequestWithData> } export type MigrateUpArgs = { payload: Payload; req?: Partial<PayloadRequest> }
export type MigrateDownArgs = { payload: Payload; req?: Partial<PayloadRequestWithData> } export type MigrateDownArgs = { payload: Payload; req?: Partial<PayloadRequest> }
declare module 'payload' { declare module 'payload' {
export interface DatabaseAdapter export interface DatabaseAdapter

View File

@@ -1,4 +1,4 @@
import type { PayloadRequestWithData, UpdateGlobalArgs } from 'payload' import type { PayloadRequest, UpdateGlobalArgs } from 'payload'
import toSnakeCase from 'to-snake-case' import toSnakeCase from 'to-snake-case'
@@ -8,7 +8,7 @@ import { upsertRow } from './upsertRow/index.js'
export async function updateGlobal<T extends Record<string, unknown>>( export async function updateGlobal<T extends Record<string, unknown>>(
this: PostgresAdapter, this: PostgresAdapter,
{ slug, data, req = {} as PayloadRequestWithData }: UpdateGlobalArgs, { slug, data, req = {} as PayloadRequest }: UpdateGlobalArgs,
): Promise<T> { ): Promise<T> {
const db = this.sessions[req.transactionID]?.db || this.drizzle const db = this.sessions[req.transactionID]?.db || this.drizzle
const globalConfig = this.payload.globals.config.find((config) => config.slug === slug) const globalConfig = this.payload.globals.config.find((config) => config.slug === slug)

View File

@@ -1,5 +1,5 @@
import type { import type {
PayloadRequestWithData, PayloadRequest,
SanitizedGlobalConfig, SanitizedGlobalConfig,
TypeWithID, TypeWithID,
TypeWithVersion, TypeWithVersion,
@@ -20,7 +20,7 @@ export async function updateGlobalVersion<T extends TypeWithID>(
id, id,
global, global,
locale, locale,
req = {} as PayloadRequestWithData, req = {} as PayloadRequest,
versionData, versionData,
where: whereArg, where: whereArg,
}: UpdateGlobalVersionArgs<T>, }: UpdateGlobalVersionArgs<T>,

View File

@@ -1,5 +1,5 @@
import type { import type {
PayloadRequestWithData, PayloadRequest,
SanitizedCollectionConfig, SanitizedCollectionConfig,
TypeWithID, TypeWithID,
TypeWithVersion, TypeWithVersion,
@@ -20,7 +20,7 @@ export async function updateVersion<T extends TypeWithID>(
id, id,
collection, collection,
locale, locale,
req = {} as PayloadRequestWithData, req = {} as PayloadRequest,
versionData, versionData,
where: whereArg, where: whereArg,
}: UpdateVersionArgs<T>, }: UpdateVersionArgs<T>,

View File

@@ -1,5 +1,5 @@
import type { SQL } from 'drizzle-orm' import type { SQL } from 'drizzle-orm'
import type { Field, PayloadRequestWithData } from 'payload' import type { Field, PayloadRequest } from 'payload'
import type { DrizzleDB, GenericColumn, PostgresAdapter } from '../types.js' import type { DrizzleDB, GenericColumn, PostgresAdapter } from '../types.js'
@@ -14,7 +14,7 @@ type BaseArgs = {
*/ */
ignoreResult?: boolean ignoreResult?: boolean
path?: string path?: string
req: PayloadRequestWithData req: PayloadRequest
tableName: string tableName: string
} }

View File

@@ -1,4 +1,4 @@
import type { Collection, PayloadRequestWithData, Where } from 'payload' import type { Collection, PayloadRequest, Where } from 'payload'
import { countOperation, isolateObjectProperty } from 'payload' import { countOperation, isolateObjectProperty } from 'payload'
@@ -12,7 +12,7 @@ export type Resolver = (
where?: Where where?: Where
}, },
context: { context: {
req: PayloadRequestWithData req: PayloadRequest
}, },
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
) => Promise<{ totalDocs: number }> ) => Promise<{ totalDocs: number }>

View File

@@ -2,7 +2,7 @@ import type {
Collection, Collection,
CollectionSlug, CollectionSlug,
DataFromCollectionSlug, DataFromCollectionSlug,
PayloadRequestWithData, PayloadRequest,
RequiredDataFromCollectionSlug, RequiredDataFromCollectionSlug,
} from 'payload' } from 'payload'
@@ -18,7 +18,7 @@ export type Resolver<TSlug extends CollectionSlug> = (
locale?: string locale?: string
}, },
context: { context: {
req: PayloadRequestWithData req: PayloadRequest
}, },
) => Promise<DataFromCollectionSlug<TSlug>> ) => Promise<DataFromCollectionSlug<TSlug>>

View File

@@ -1,9 +1,4 @@
import type { import type { Collection, CollectionSlug, DataFromCollectionSlug, PayloadRequest } from 'payload'
Collection,
CollectionSlug,
DataFromCollectionSlug,
PayloadRequestWithData,
} from 'payload'
import { deleteByIDOperation, isolateObjectProperty } from 'payload' import { deleteByIDOperation, isolateObjectProperty } from 'payload'
@@ -18,7 +13,7 @@ export type Resolver<TSlug extends CollectionSlug> = (
locale?: string locale?: string
}, },
context: { context: {
req: PayloadRequestWithData req: PayloadRequest
}, },
) => Promise<DataFromCollectionSlug<TSlug>> ) => Promise<DataFromCollectionSlug<TSlug>>

View File

@@ -1,9 +1,4 @@
import type { import type { Collection, CollectionPermission, GlobalPermission, PayloadRequest } from 'payload'
Collection,
CollectionPermission,
GlobalPermission,
PayloadRequestWithData,
} from 'payload'
import { docAccessOperation, isolateObjectProperty } from 'payload' import { docAccessOperation, isolateObjectProperty } from 'payload'
@@ -15,7 +10,7 @@ export type Resolver = (
id: number | string id: number | string
}, },
context: { context: {
req: PayloadRequestWithData req: PayloadRequest
}, },
) => Promise<CollectionPermission | GlobalPermission> ) => Promise<CollectionPermission | GlobalPermission>

View File

@@ -1,9 +1,4 @@
import type { import type { Collection, CollectionSlug, DataFromCollectionSlug, PayloadRequest } from 'payload'
Collection,
CollectionSlug,
DataFromCollectionSlug,
PayloadRequestWithData,
} from 'payload'
import { duplicateOperation, isolateObjectProperty } from 'payload' import { duplicateOperation, isolateObjectProperty } from 'payload'
@@ -18,7 +13,7 @@ export type Resolver<TData> = (
locale?: string locale?: string
}, },
context: { context: {
req: PayloadRequestWithData req: PayloadRequest
}, },
) => Promise<TData> ) => Promise<TData>

View File

@@ -1,4 +1,4 @@
import type { Collection, PaginatedDocs, PayloadRequestWithData, Where } from 'payload' import type { Collection, PaginatedDocs, PayloadRequest, Where } from 'payload'
import { findOperation, isolateObjectProperty } from 'payload' import { findOperation, isolateObjectProperty } from 'payload'
@@ -17,7 +17,7 @@ export type Resolver = (
where?: Where where?: Where
}, },
context: { context: {
req: PayloadRequestWithData req: PayloadRequest
}, },
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
) => Promise<PaginatedDocs<any>> ) => Promise<PaginatedDocs<any>>

View File

@@ -1,9 +1,4 @@
import type { import type { Collection, CollectionSlug, DataFromCollectionSlug, PayloadRequest } from 'payload'
Collection,
CollectionSlug,
DataFromCollectionSlug,
PayloadRequestWithData,
} from 'payload'
import { findByIDOperation, isolateObjectProperty } from 'payload' import { findByIDOperation, isolateObjectProperty } from 'payload'
@@ -18,7 +13,7 @@ export type Resolver<TData> = (
locale?: string locale?: string
}, },
context: { context: {
req: PayloadRequestWithData req: PayloadRequest
}, },
) => Promise<TData> ) => Promise<TData>

View File

@@ -1,4 +1,4 @@
import type { Collection, PayloadRequestWithData, TypeWithID, TypeWithVersion } from 'payload' import type { Collection, PayloadRequest, TypeWithID, TypeWithVersion } from 'payload'
import { findVersionByIDOperation, isolateObjectProperty } from 'payload' import { findVersionByIDOperation, isolateObjectProperty } from 'payload'
@@ -12,7 +12,7 @@ export type Resolver<T extends TypeWithID = any> = (
locale?: string locale?: string
}, },
context: { context: {
req: PayloadRequestWithData req: PayloadRequest
}, },
) => Promise<TypeWithVersion<T>> ) => Promise<TypeWithVersion<T>>

View File

@@ -1,4 +1,4 @@
import type { Collection, PaginatedDocs, PayloadRequestWithData, Where } from 'payload' import type { Collection, PaginatedDocs, PayloadRequest, Where } from 'payload'
import { findVersionsOperation, isolateObjectProperty } from 'payload' import { findVersionsOperation, isolateObjectProperty } from 'payload'
@@ -16,7 +16,7 @@ export type Resolver = (
where: Where where: Where
}, },
context: { context: {
req: PayloadRequestWithData req: PayloadRequest
}, },
) => Promise<PaginatedDocs<any>> ) => Promise<PaginatedDocs<any>>

View File

@@ -1,4 +1,4 @@
import type { Collection, PayloadRequestWithData } from 'payload' import type { Collection, PayloadRequest } from 'payload'
import { isolateObjectProperty, restoreVersionOperation } from 'payload' import { isolateObjectProperty, restoreVersionOperation } from 'payload'
@@ -10,7 +10,7 @@ export type Resolver = (
id: number | string id: number | string
}, },
context: { context: {
req: PayloadRequestWithData req: PayloadRequest
}, },
) => Promise<Document> ) => Promise<Document>

View File

@@ -1,9 +1,4 @@
import type { import type { Collection, CollectionSlug, DataFromCollectionSlug, PayloadRequest } from 'payload'
Collection,
CollectionSlug,
DataFromCollectionSlug,
PayloadRequestWithData,
} from 'payload'
import { isolateObjectProperty, updateByIDOperation } from 'payload' import { isolateObjectProperty, updateByIDOperation } from 'payload'
@@ -20,7 +15,7 @@ export type Resolver<TSlug extends CollectionSlug> = (
locale?: string locale?: string
}, },
context: { context: {
req: PayloadRequestWithData req: PayloadRequest
}, },
) => Promise<DataFromCollectionSlug<TSlug>> ) => Promise<DataFromCollectionSlug<TSlug>>

View File

@@ -1,7 +1,7 @@
import type { import type {
CollectionPermission, CollectionPermission,
GlobalPermission, GlobalPermission,
PayloadRequestWithData, PayloadRequest,
SanitizedGlobalConfig, SanitizedGlobalConfig,
} from 'payload' } from 'payload'
@@ -12,7 +12,7 @@ import type { Context } from '../types.js'
export type Resolver = ( export type Resolver = (
_: unknown, _: unknown,
context: { context: {
req: PayloadRequestWithData req: PayloadRequest
}, },
) => Promise<CollectionPermission | GlobalPermission> ) => Promise<CollectionPermission | GlobalPermission>

View File

@@ -1,4 +1,4 @@
import type { Document, PayloadRequestWithData, SanitizedGlobalConfig } from 'payload' import type { Document, PayloadRequest, SanitizedGlobalConfig } from 'payload'
import { findVersionByIDOperationGlobal, isolateObjectProperty } from 'payload' import { findVersionByIDOperationGlobal, isolateObjectProperty } from 'payload'
@@ -13,7 +13,7 @@ export type Resolver = (
locale?: string locale?: string
}, },
context: { context: {
req: PayloadRequestWithData req: PayloadRequest
}, },
) => Promise<Document> ) => Promise<Document>

View File

@@ -1,4 +1,4 @@
import type { Document, PayloadRequestWithData, SanitizedGlobalConfig, Where } from 'payload' import type { Document, PayloadRequest, SanitizedGlobalConfig, Where } from 'payload'
import { findVersionsOperationGlobal, isolateObjectProperty } from 'payload' import { findVersionsOperationGlobal, isolateObjectProperty } from 'payload'
@@ -15,7 +15,7 @@ export type Resolver = (
where: Where where: Where
}, },
context: { context: {
req: PayloadRequestWithData req: PayloadRequest
}, },
) => Promise<Document> ) => Promise<Document>

View File

@@ -1,4 +1,4 @@
import type { Document, PayloadRequestWithData, SanitizedGlobalConfig } from 'payload' import type { Document, PayloadRequest, SanitizedGlobalConfig } from 'payload'
import { isolateObjectProperty, restoreVersionOperationGlobal } from 'payload' import { isolateObjectProperty, restoreVersionOperationGlobal } from 'payload'
@@ -10,7 +10,7 @@ type Resolver = (
id: number | string id: number | string
}, },
context: { context: {
req: PayloadRequestWithData req: PayloadRequest
}, },
) => Promise<Document> ) => Promise<Document>
export default function restoreVersionResolver(globalConfig: SanitizedGlobalConfig): Resolver { export default function restoreVersionResolver(globalConfig: SanitizedGlobalConfig): Resolver {

View File

@@ -1,9 +1,4 @@
import type { import type { DataFromGlobalSlug, GlobalSlug, PayloadRequest, SanitizedGlobalConfig } from 'payload'
DataFromGlobalSlug,
GlobalSlug,
PayloadRequestWithData,
SanitizedGlobalConfig,
} from 'payload'
import type { DeepPartial } from 'ts-essentials' import type { DeepPartial } from 'ts-essentials'
import { isolateObjectProperty, updateOperationGlobal } from 'payload' import { isolateObjectProperty, updateOperationGlobal } from 'payload'
@@ -19,7 +14,7 @@ type Resolver<TSlug extends GlobalSlug> = (
locale?: string locale?: string
}, },
context: { context: {
req: PayloadRequestWithData req: PayloadRequest
}, },
) => Promise<DataFromGlobalSlug<TSlug>> ) => Promise<DataFromGlobalSlug<TSlug>>

View File

@@ -1,8 +1,8 @@
import type { PayloadRequestWithData } from 'payload' import type { PayloadRequest } from 'payload'
export type Context = { export type Context = {
headers: { headers: {
[key: string]: string [key: string]: string
} }
req: PayloadRequestWithData req: PayloadRequest
} }

View File

@@ -1,10 +1,10 @@
import type { ObjMap } from 'graphql/jsutils/ObjMap.js' import type { ObjMap } from 'graphql/jsutils/ObjMap.js'
import type { GraphQLFieldConfig, GraphQLFieldResolver } from 'graphql/type/definition.js' import type { GraphQLFieldConfig, GraphQLFieldResolver } from 'graphql/type/definition.js'
import type { PayloadRequestWithData } from 'payload' import type { PayloadRequest } from 'payload'
import { isolateObjectProperty } from 'payload' import { isolateObjectProperty } from 'payload'
type PayloadContext = { req: PayloadRequestWithData } type PayloadContext = { req: PayloadRequest }
function wrapCustomResolver<TSource, TArgs, TResult>( function wrapCustomResolver<TSource, TArgs, TResult>(
resolver: GraphQLFieldResolver<TSource, PayloadContext, TArgs, TResult>, resolver: GraphQLFieldResolver<TSource, PayloadContext, TArgs, TResult>,

View File

@@ -84,24 +84,24 @@ export const getGraphql = async (config: Promise<SanitizedConfig> | SanitizedCon
export const POST = export const POST =
(config: Promise<SanitizedConfig> | SanitizedConfig) => async (request: Request) => { (config: Promise<SanitizedConfig> | SanitizedConfig) => async (request: Request) => {
const originalRequest = request.clone() const originalRequest = request.clone()
const basePayloadRequest = await createPayloadRequest({ const req = await createPayloadRequest({
config, config,
request, request,
}) })
const reqWithData = await addDataAndFileToRequest({ request: basePayloadRequest }) await addDataAndFileToRequest(req)
const payloadRequest = addLocalesToRequestFromData({ request: reqWithData }) addLocalesToRequestFromData(req)
const { schema, validationRules } = await getGraphql(config) const { schema, validationRules } = await getGraphql(config)
const { payload } = payloadRequest const { payload } = req
const afterErrorHook = const afterErrorHook =
typeof payload.config.hooks.afterError === 'function' ? payload.config.hooks.afterError : null typeof payload.config.hooks.afterError === 'function' ? payload.config.hooks.afterError : null
const headers = {} const headers = {}
const apiResponse = await createHandler({ const apiResponse = await createHandler({
context: { headers, req: payloadRequest }, context: { headers, req },
onOperation: async (request, args, result) => { onOperation: async (request, args, result) => {
const response = const response =
typeof payload.extensions === 'function' typeof payload.extensions === 'function'
@@ -128,15 +128,15 @@ export const POST =
const resHeaders = headersWithCors({ const resHeaders = headersWithCors({
headers: new Headers(apiResponse.headers), headers: new Headers(apiResponse.headers),
req: payloadRequest, req,
}) })
for (const key in headers) { for (const key in headers) {
resHeaders.append(key, headers[key]) resHeaders.append(key, headers[key])
} }
if (basePayloadRequest.responseHeaders) { if (req.responseHeaders) {
mergeHeaders(basePayloadRequest.responseHeaders, resHeaders) mergeHeaders(req.responseHeaders, resHeaders)
} }
return new Response(apiResponse.body, { return new Response(apiResponse.body, {

View File

@@ -1,4 +1,4 @@
import type { PayloadRequestWithData } from 'payload' import type { PayloadRequest } from 'payload'
import { buildFormState as buildFormStateFn } from '@payloadcms/ui/utilities/buildFormState' import { buildFormState as buildFormStateFn } from '@payloadcms/ui/utilities/buildFormState'
import httpStatus from 'http-status' import httpStatus from 'http-status'
@@ -6,7 +6,7 @@ import httpStatus from 'http-status'
import { headersWithCors } from '../../utilities/headersWithCors.js' import { headersWithCors } from '../../utilities/headersWithCors.js'
import { routeError } from './routeError.js' import { routeError } from './routeError.js'
export const buildFormState = async ({ req }: { req: PayloadRequestWithData }) => { export const buildFormState = async ({ req }: { req: PayloadRequest }) => {
const headers = headersWithCors({ const headers = headersWithCors({
headers: new Headers(), headers: new Headers(),
req, req,

View File

@@ -1,4 +1,4 @@
import type { Collection, PayloadRequestWithData, TypeWithID, Where } from 'payload' import type { Collection, PayloadRequest, TypeWithID, Where } from 'payload'
import { Forbidden, executeAccess } from 'payload' import { Forbidden, executeAccess } from 'payload'
@@ -11,7 +11,7 @@ export async function checkFileAccess({
}: { }: {
collection: Collection collection: Collection
filename: string filename: string
req: PayloadRequestWithData req: PayloadRequest
}): Promise<Response | TypeWithID> { }): Promise<Response | TypeWithID> {
const { config } = collection const { config } = collection
const disableEndpoints = endpointsAreDisabled({ endpoints: config.endpoints, request: req }) const disableEndpoints = endpointsAreDisabled({ endpoints: config.endpoints, request: req })

View File

@@ -1,4 +1,4 @@
import type { Collection, PayloadRequestWithData } from 'payload' import type { Collection, PayloadRequest } from 'payload'
import { fileTypeFromFile } from 'file-type' import { fileTypeFromFile } from 'file-type'
import fsPromises from 'fs/promises' import fsPromises from 'fs/promises'
@@ -16,7 +16,7 @@ import { getFileTypeFallback } from './getFileTypeFallback.js'
type Args = { type Args = {
collection: Collection collection: Collection
filename: string filename: string
req: PayloadRequestWithData req: PayloadRequest
} }
export const getFile = async ({ collection, filename, req }: Args): Promise<Response> => { export const getFile = async ({ collection, filename, req }: Args): Promise<Response> => {
try { try {

View File

@@ -1,11 +1,4 @@
import type { import type { Collection, Endpoint, GlobalConfig, PayloadRequest, SanitizedConfig } from 'payload'
Collection,
Endpoint,
GlobalConfig,
PayloadRequest,
PayloadRequestData,
SanitizedConfig,
} from 'payload'
import httpStatus from 'http-status' import httpStatus from 'http-status'
import { match } from 'path-to-regexp' import { match } from 'path-to-regexp'
@@ -126,22 +119,22 @@ const endpoints = {
const handleCustomEndpoints = async ({ const handleCustomEndpoints = async ({
endpoints, endpoints,
entitySlug, entitySlug,
payloadRequest, req,
}: { }: {
endpoints: Endpoint[] | GlobalConfig['endpoints'] endpoints: Endpoint[] | GlobalConfig['endpoints']
entitySlug?: string entitySlug?: string
payloadRequest: PayloadRequest req: PayloadRequest
}): Promise<Response> => { }): Promise<Response> => {
if (endpoints && endpoints.length > 0) { if (endpoints && endpoints.length > 0) {
let handlerParams = {} let handlerParams = {}
const { pathname } = payloadRequest const { pathname } = req
/* /*
* This makes sure the next.js basePath property is supported. If basePath is used, payload config.routes.api should include it. This makes all outgoing frontend request * This makes sure the next.js basePath property is supported. If basePath is used, payload config.routes.api should include it. This makes all outgoing frontend request
* target the correct API endpoint starting with basePath, which is good! * target the correct API endpoint starting with basePath, which is good!
* *
* The incoming request (here) will not include the basePath though, as it's automatically stripped by Next.js. Since we are adding the basePath to the pathPrefix below though * The incoming request (here) will not include the basePath though, as it's automatically stripped by Next.js. Since we are adding the basePath to the pathPrefix below though
* (from payloadRequest.payload.config.routes.api) we need to add it to pathname, which does not contain the basePath. Otherwise, no endpoint will be matched if basePath is set. * (from req.payload.config.routes.api) we need to add it to pathname, which does not contain the basePath. Otherwise, no endpoint will be matched if basePath is set.
*/ */
let adjustedPathname = pathname let adjustedPathname = pathname
@@ -149,11 +142,10 @@ const handleCustomEndpoints = async ({
adjustedPathname = process.env.NEXT_BASE_PATH + pathname adjustedPathname = process.env.NEXT_BASE_PATH + pathname
} }
const pathPrefix = const pathPrefix = req.payload.config.routes.api + (entitySlug ? `/${entitySlug}` : '')
payloadRequest.payload.config.routes.api + (entitySlug ? `/${entitySlug}` : '')
const customEndpoint = endpoints.find((endpoint) => { const customEndpoint = endpoints.find((endpoint) => {
if (endpoint.method === payloadRequest.method.toLowerCase()) { if (endpoint.method === req.method.toLowerCase()) {
const pathMatchFn = match(`${pathPrefix}${endpoint.path}`, { const pathMatchFn = match(`${pathPrefix}${endpoint.path}`, {
decode: decodeURIComponent, decode: decodeURIComponent,
}) })
@@ -167,15 +159,15 @@ const handleCustomEndpoints = async ({
}) })
if (customEndpoint) { if (customEndpoint) {
payloadRequest.routeParams = { req.routeParams = {
...payloadRequest.routeParams, ...req.routeParams,
...handlerParams, ...handlerParams,
} }
const res = await customEndpoint.handler(payloadRequest) const res = await customEndpoint.handler(req)
if (res instanceof Response) { if (res instanceof Response) {
if (payloadRequest.responseHeaders) { if (req.responseHeaders) {
mergeHeaders(payloadRequest.responseHeaders, res.headers) mergeHeaders(req.responseHeaders, res.headers)
} }
return res return res
@@ -233,7 +225,7 @@ export const GET =
(config: Promise<SanitizedConfig> | SanitizedConfig) => (config: Promise<SanitizedConfig> | SanitizedConfig) =>
async (request: Request, { params: { slug } }: { params: { slug: string[] } }) => { async (request: Request, { params: { slug } }: { params: { slug: string[] } }) => {
const [slug1, slug2, slug3, slug4] = slug const [slug1, slug2, slug3, slug4] = slug
let req: PayloadRequest | (PayloadRequest & PayloadRequestData) let req: PayloadRequest
let res: Response let res: Response
let collection: Collection let collection: Collection
@@ -263,19 +255,19 @@ export const GET =
const customEndpointResponse = await handleCustomEndpoints({ const customEndpointResponse = await handleCustomEndpoints({
endpoints: collection.config.endpoints, endpoints: collection.config.endpoints,
entitySlug: slug1, entitySlug: slug1,
payloadRequest: req, req,
}) })
if (customEndpointResponse) { if (customEndpointResponse) {
return customEndpointResponse return customEndpointResponse
} else { } else {
const reqWithData = await addDataAndFileToRequest({ request: req }) await addDataAndFileToRequest(req)
const payloadRequest = addLocalesToRequestFromData({ request: reqWithData }) addLocalesToRequestFromData(req)
switch (slug.length) { switch (slug.length) {
case 1: case 1:
// /:collection // /:collection
res = await endpoints.collection.GET.find({ collection, req: payloadRequest }) res = await endpoints.collection.GET.find({ collection, req })
break break
case 2: case 2:
if (slug2 in endpoints.collection.GET) { if (slug2 in endpoints.collection.GET) {
@@ -285,14 +277,14 @@ export const GET =
// /:collection/count // /:collection/count
res = await (endpoints.collection.GET[slug2] as CollectionRouteHandler)({ res = await (endpoints.collection.GET[slug2] as CollectionRouteHandler)({
collection, collection,
req: payloadRequest, req,
}) })
} else { } else {
// /:collection/:id // /:collection/:id
res = await endpoints.collection.GET.findByID({ res = await endpoints.collection.GET.findByID({
id: slug2, id: slug2,
collection, collection,
req: payloadRequest, req,
}) })
} }
break break
@@ -302,21 +294,21 @@ export const GET =
res = await endpoints.collection.GET.getFile({ res = await endpoints.collection.GET.getFile({
collection, collection,
filename: slug3, filename: slug3,
req: payloadRequest, req,
}) })
} else if (slug3 in endpoints.collection.GET) { } else if (slug3 in endpoints.collection.GET) {
// /:collection/:id/preview // /:collection/:id/preview
res = await (endpoints.collection.GET[slug3] as CollectionRouteHandlerWithID)({ res = await (endpoints.collection.GET[slug3] as CollectionRouteHandlerWithID)({
id: slug2, id: slug2,
collection, collection,
req: payloadRequest, req,
}) })
} else if (`doc-${slug2}-by-id` in endpoints.collection.GET) { } else if (`doc-${slug2}-by-id` in endpoints.collection.GET) {
// /:collection/access/:id // /:collection/access/:id
// /:collection/versions/:id // /:collection/versions/:id
res = await ( res = await (
endpoints.collection.GET[`doc-${slug2}-by-id`] as CollectionRouteHandlerWithID endpoints.collection.GET[`doc-${slug2}-by-id`] as CollectionRouteHandlerWithID
)({ id: slug3, collection, req: payloadRequest }) )({ id: slug3, collection, req })
} }
break break
} }
@@ -334,26 +326,26 @@ export const GET =
const customEndpointResponse = await handleCustomEndpoints({ const customEndpointResponse = await handleCustomEndpoints({
endpoints: globalConfig.endpoints, endpoints: globalConfig.endpoints,
entitySlug: `${slug1}/${slug2}`, entitySlug: `${slug1}/${slug2}`,
payloadRequest: req, req,
}) })
if (customEndpointResponse) { if (customEndpointResponse) {
return customEndpointResponse return customEndpointResponse
} else { } else {
const reqWithData = await addDataAndFileToRequest({ request: req }) await addDataAndFileToRequest(req)
const payloadRequest = addLocalesToRequestFromData({ request: reqWithData }) addLocalesToRequestFromData(req)
switch (slug.length) { switch (slug.length) {
case 2: case 2:
// /globals/:slug // /globals/:slug
res = await endpoints.global.GET.findOne({ globalConfig, req: payloadRequest }) res = await endpoints.global.GET.findOne({ globalConfig, req })
break break
case 3: case 3:
if (slug3 in endpoints.global.GET) { if (slug3 in endpoints.global.GET) {
// /globals/:slug/preview // /globals/:slug/preview
res = await (endpoints.global.GET[slug3] as GlobalRouteHandler)({ res = await (endpoints.global.GET[slug3] as GlobalRouteHandler)({
globalConfig, globalConfig,
req: payloadRequest, req,
}) })
} else if (`doc-${slug3}` in endpoints.global.GET) { } else if (`doc-${slug3}` in endpoints.global.GET) {
// /globals/:slug/access // /globals/:slug/access
@@ -361,7 +353,7 @@ export const GET =
// /globals/:slug/preview // /globals/:slug/preview
res = await (endpoints.global.GET?.[`doc-${slug3}`] as GlobalRouteHandler)({ res = await (endpoints.global.GET?.[`doc-${slug3}`] as GlobalRouteHandler)({
globalConfig, globalConfig,
req: payloadRequest, req,
}) })
} }
break break
@@ -373,16 +365,16 @@ export const GET =
)({ )({
id: slug4, id: slug4,
globalConfig, globalConfig,
req: payloadRequest, req,
}) })
} }
break break
} }
} }
} else if (slug.length === 1 && slug1 in endpoints.root.GET) { } else if (slug.length === 1 && slug1 in endpoints.root.GET) {
const reqWithData = await addDataAndFileToRequest({ request: req }) await addDataAndFileToRequest(req)
const payloadRequest = addLocalesToRequestFromData({ request: reqWithData }) addLocalesToRequestFromData(req)
res = await endpoints.root.GET[slug1]({ req: payloadRequest }) res = await endpoints.root.GET[slug1]({ req })
} }
if (res instanceof Response) { if (res instanceof Response) {
@@ -396,7 +388,7 @@ export const GET =
// root routes // root routes
const customEndpointResponse = await handleCustomEndpoints({ const customEndpointResponse = await handleCustomEndpoints({
endpoints: req.payload.config.endpoints, endpoints: req.payload.config.endpoints,
payloadRequest: req, req,
}) })
if (customEndpointResponse) return customEndpointResponse if (customEndpointResponse) return customEndpointResponse
@@ -454,19 +446,19 @@ export const POST =
const customEndpointResponse = await handleCustomEndpoints({ const customEndpointResponse = await handleCustomEndpoints({
endpoints: collection.config.endpoints, endpoints: collection.config.endpoints,
entitySlug: slug1, entitySlug: slug1,
payloadRequest: req, req,
}) })
if (customEndpointResponse) { if (customEndpointResponse) {
return customEndpointResponse return customEndpointResponse
} else { } else {
const reqWithData = await addDataAndFileToRequest({ request: req }) await addDataAndFileToRequest(req)
const payloadRequest = addLocalesToRequestFromData({ request: reqWithData }) addLocalesToRequestFromData(req)
switch (slug.length) { switch (slug.length) {
case 1: case 1:
// /:collection // /:collection
res = await endpoints.collection.POST.create({ collection, req: payloadRequest }) res = await endpoints.collection.POST.create({ collection, req })
break break
case 2: case 2:
if (slug2 in endpoints.collection.POST) { if (slug2 in endpoints.collection.POST) {
@@ -481,7 +473,7 @@ export const POST =
res = await (endpoints.collection.POST?.[slug2] as CollectionRouteHandler)({ res = await (endpoints.collection.POST?.[slug2] as CollectionRouteHandler)({
collection, collection,
req: payloadRequest, req,
}) })
} }
break break
@@ -492,13 +484,13 @@ export const POST =
// /:collection/verify/:token ("doc-verify-by-id" uses id as token internally) // /:collection/verify/:token ("doc-verify-by-id" uses id as token internally)
res = await ( res = await (
endpoints.collection.POST[`doc-${slug2}-by-id`] as CollectionRouteHandlerWithID endpoints.collection.POST[`doc-${slug2}-by-id`] as CollectionRouteHandlerWithID
)({ id: slug3, collection, req: payloadRequest }) )({ id: slug3, collection, req })
} else if (slug3 === 'duplicate' && collection.config.disableDuplicate !== true) { } else if (slug3 === 'duplicate' && collection.config.disableDuplicate !== true) {
// /:collection/:id/duplicate // /:collection/:id/duplicate
res = await endpoints.collection.POST.duplicate({ res = await endpoints.collection.POST.duplicate({
id: slug2, id: slug2,
collection, collection,
req: payloadRequest, req,
}) })
} }
break break
@@ -517,25 +509,25 @@ export const POST =
const customEndpointResponse = await handleCustomEndpoints({ const customEndpointResponse = await handleCustomEndpoints({
endpoints: globalConfig.endpoints, endpoints: globalConfig.endpoints,
entitySlug: `${slug1}/${slug2}`, entitySlug: `${slug1}/${slug2}`,
payloadRequest: req, req,
}) })
if (customEndpointResponse) { if (customEndpointResponse) {
return customEndpointResponse return customEndpointResponse
} else { } else {
const reqWithData = await addDataAndFileToRequest({ request: req }) await addDataAndFileToRequest(req)
const payloadRequest = addLocalesToRequestFromData({ request: reqWithData }) addLocalesToRequestFromData(req)
switch (slug.length) { switch (slug.length) {
case 2: case 2:
// /globals/:slug // /globals/:slug
res = await endpoints.global.POST.update({ globalConfig, req: payloadRequest }) res = await endpoints.global.POST.update({ globalConfig, req })
break break
case 3: case 3:
if (`doc-${slug3}` in endpoints.global.POST) { if (`doc-${slug3}` in endpoints.global.POST) {
// /globals/:slug/access // /globals/:slug/access
res = await (endpoints.global.POST?.[`doc-${slug3}`] as GlobalRouteHandler)({ res = await (endpoints.global.POST?.[`doc-${slug3}`] as GlobalRouteHandler)({
globalConfig, globalConfig,
req: payloadRequest, req,
}) })
} }
break break
@@ -547,7 +539,7 @@ export const POST =
)({ )({
id: slug4, id: slug4,
globalConfig, globalConfig,
req: payloadRequest, req,
}) })
} }
break break
@@ -556,9 +548,9 @@ export const POST =
} }
} }
} else if (slug.length === 1 && slug1 in endpoints.root.POST) { } else if (slug.length === 1 && slug1 in endpoints.root.POST) {
const reqWithData = await addDataAndFileToRequest({ request: req }) await addDataAndFileToRequest(req)
const payloadRequest = addLocalesToRequestFromData({ request: reqWithData }) addLocalesToRequestFromData(req)
res = await endpoints.root.POST[slug1]({ req: payloadRequest }) res = await endpoints.root.POST[slug1]({ req })
} }
if (res instanceof Response) { if (res instanceof Response) {
@@ -572,7 +564,7 @@ export const POST =
// root routes // root routes
const customEndpointResponse = await handleCustomEndpoints({ const customEndpointResponse = await handleCustomEndpoints({
endpoints: req.payload.config.endpoints, endpoints: req.payload.config.endpoints,
payloadRequest: req, req,
}) })
if (customEndpointResponse) return customEndpointResponse if (customEndpointResponse) return customEndpointResponse
@@ -624,25 +616,25 @@ export const DELETE =
const customEndpointResponse = await handleCustomEndpoints({ const customEndpointResponse = await handleCustomEndpoints({
endpoints: collection.config.endpoints, endpoints: collection.config.endpoints,
entitySlug: slug1, entitySlug: slug1,
payloadRequest: req, req,
}) })
if (customEndpointResponse) { if (customEndpointResponse) {
return customEndpointResponse return customEndpointResponse
} else { } else {
const reqWithData = await addDataAndFileToRequest({ request: req }) await addDataAndFileToRequest(req)
const payloadRequest = addLocalesToRequestFromData({ request: reqWithData }) addLocalesToRequestFromData(req)
switch (slug.length) { switch (slug.length) {
case 1: case 1:
// /:collection // /:collection
res = await endpoints.collection.DELETE.delete({ collection, req: payloadRequest }) res = await endpoints.collection.DELETE.delete({ collection, req })
break break
case 2: case 2:
// /:collection/:id // /:collection/:id
res = await endpoints.collection.DELETE.deleteByID({ res = await endpoints.collection.DELETE.deleteByID({
id: slug2, id: slug2,
collection, collection,
req: payloadRequest, req,
}) })
break break
} }
@@ -660,7 +652,7 @@ export const DELETE =
// root routes // root routes
const customEndpointResponse = await handleCustomEndpoints({ const customEndpointResponse = await handleCustomEndpoints({
endpoints: req.payload.config.endpoints, endpoints: req.payload.config.endpoints,
payloadRequest: req, req,
}) })
if (customEndpointResponse) return customEndpointResponse if (customEndpointResponse) return customEndpointResponse
@@ -712,26 +704,26 @@ export const PATCH =
const customEndpointResponse = await handleCustomEndpoints({ const customEndpointResponse = await handleCustomEndpoints({
endpoints: collection.config.endpoints, endpoints: collection.config.endpoints,
entitySlug: slug1, entitySlug: slug1,
payloadRequest: req, req,
}) })
if (customEndpointResponse) { if (customEndpointResponse) {
return customEndpointResponse return customEndpointResponse
} else { } else {
const reqWithData = await addDataAndFileToRequest({ request: req }) await addDataAndFileToRequest(req)
const payloadRequest = addLocalesToRequestFromData({ request: reqWithData }) addLocalesToRequestFromData(req)
switch (slug.length) { switch (slug.length) {
case 1: case 1:
// /:collection // /:collection
res = await endpoints.collection.PATCH.update({ collection, req: payloadRequest }) res = await endpoints.collection.PATCH.update({ collection, req })
break break
case 2: case 2:
// /:collection/:id // /:collection/:id
res = await endpoints.collection.PATCH.updateByID({ res = await endpoints.collection.PATCH.updateByID({
id: slug2, id: slug2,
collection, collection,
req: payloadRequest, req,
}) })
break break
} }
@@ -749,7 +741,7 @@ export const PATCH =
// root routes // root routes
const customEndpointResponse = await handleCustomEndpoints({ const customEndpointResponse = await handleCustomEndpoints({
endpoints: req.payload.config.endpoints, endpoints: req.payload.config.endpoints,
payloadRequest: req, req,
}) })
if (customEndpointResponse) return customEndpointResponse if (customEndpointResponse) return customEndpointResponse

View File

@@ -1,4 +1,4 @@
import type { PayloadRequestWithData } from 'payload' import type { PayloadRequest } from 'payload'
import { PayloadIcon } from '@payloadcms/ui/shared' import { PayloadIcon } from '@payloadcms/ui/shared'
import fs from 'fs/promises' import fs from 'fs/promises'
@@ -17,7 +17,7 @@ export const runtime = 'nodejs'
export const contentType = 'image/png' export const contentType = 'image/png'
export const generateOGImage = async ({ req }: { req: PayloadRequestWithData }) => { export const generateOGImage = async ({ req }: { req: PayloadRequest }) => {
const config = req.payload.config const config = req.payload.config
if (config.admin.meta.defaultOGImageType === 'off') { if (config.admin.meta.defaultOGImageType === 'off') {

View File

@@ -1,4 +1,4 @@
import type { Collection, PayloadRequestWithData, SanitizedConfig } from 'payload' import type { Collection, PayloadRequest, SanitizedConfig } from 'payload'
import httpStatus from 'http-status' import httpStatus from 'http-status'
import { APIError } from 'payload' import { APIError } from 'payload'
@@ -78,7 +78,7 @@ export const routeError = async ({
collection?: Collection collection?: Collection
config: Promise<SanitizedConfig> | SanitizedConfig config: Promise<SanitizedConfig> | SanitizedConfig
err: APIError err: APIError
req: Partial<PayloadRequestWithData> req: Partial<PayloadRequest>
}) => { }) => {
let payload = req?.payload let payload = req?.payload

View File

@@ -1,17 +1,13 @@
import type { Collection, PayloadRequestWithData, SanitizedGlobalConfig } from 'payload' import type { Collection, PayloadRequest, SanitizedGlobalConfig } from 'payload'
export type BaseRouteHandler = ({ export type BaseRouteHandler = ({ req }: { req: PayloadRequest }) => Promise<Response> | Response
req,
}: {
req: PayloadRequestWithData
}) => Promise<Response> | Response
export type CollectionRouteHandler = ({ export type CollectionRouteHandler = ({
collection, collection,
req, req,
}: { }: {
collection: Collection collection: Collection
req: PayloadRequestWithData req: PayloadRequest
}) => Promise<Response> | Response }) => Promise<Response> | Response
export type CollectionRouteHandlerWithID = ({ export type CollectionRouteHandlerWithID = ({
@@ -21,7 +17,7 @@ export type CollectionRouteHandlerWithID = ({
}: { }: {
collection: Collection collection: Collection
id: string id: string
req: PayloadRequestWithData req: PayloadRequest
}) => Promise<Response> | Response }) => Promise<Response> | Response
export type GlobalRouteHandler = ({ export type GlobalRouteHandler = ({
@@ -29,7 +25,7 @@ export type GlobalRouteHandler = ({
req, req,
}: { }: {
globalConfig: SanitizedGlobalConfig globalConfig: SanitizedGlobalConfig
req: PayloadRequestWithData req: PayloadRequest
}) => Promise<Response> | Response }) => Promise<Response> | Response
export type GlobalRouteHandlerWithID = ({ export type GlobalRouteHandlerWithID = ({
@@ -39,5 +35,5 @@ export type GlobalRouteHandlerWithID = ({
}: { }: {
globalConfig: SanitizedGlobalConfig globalConfig: SanitizedGlobalConfig
id: string id: string
req: PayloadRequestWithData req: PayloadRequest
}) => Promise<Response> | Response }) => Promise<Response> | Response

View File

@@ -1,4 +1,4 @@
import type { PayloadRequest, PayloadRequestData } from 'payload' import type { PayloadRequest } from 'payload'
import { APIError } from 'payload' import { APIError } from 'payload'
@@ -6,40 +6,32 @@ import type { FetchAPIFileUploadOptions } from '../fetchAPI-multipart/index.js'
import { fetchAPIFileUpload } from '../fetchAPI-multipart/index.js' import { fetchAPIFileUpload } from '../fetchAPI-multipart/index.js'
type ReturnType = PayloadRequest & PayloadRequestData type AddDataAndFileToRequest = (req: PayloadRequest) => Promise<void>
type AddDataAndFileToRequest = (args: { request: PayloadRequest }) => Promise<ReturnType>
/** /**
* Mutates the Request to contain 'data' and 'file' if present * Mutates the Request, appending 'data' and 'file' if found
*/ */
export const addDataAndFileToRequest: AddDataAndFileToRequest = async ({ export const addDataAndFileToRequest: AddDataAndFileToRequest = async (req) => {
request: incomingRequest, const { body, headers, method, payload } = req
}) => {
const config = incomingRequest.payload.config
if ( if (method && ['PATCH', 'POST', 'PUT'].includes(method.toUpperCase()) && body) {
incomingRequest.method && const [contentType] = (headers.get('Content-Type') || '').split(';')
['PATCH', 'POST', 'PUT'].includes(incomingRequest.method.toUpperCase()) && const bodyByteSize = parseInt(req.headers.get('Content-Length') || '0', 10)
incomingRequest.body
) {
const [contentType] = (incomingRequest.headers.get('Content-Type') || '').split(';')
const mutableRequest = incomingRequest as ReturnType
const bodyByteSize = parseInt(incomingRequest.headers.get('Content-Length') || '0', 10)
if (contentType === 'application/json') { if (contentType === 'application/json') {
let data = {} let data = {}
try { try {
data = await mutableRequest.json() data = await req.json()
} catch (error) { } catch (error) {
mutableRequest.payload.logger.error(error) req.payload.logger.error(error)
} finally { } finally {
mutableRequest.data = data req.data = data
mutableRequest.json = () => Promise.resolve(data) req.json = () => Promise.resolve(data)
} }
} else if (bodyByteSize && contentType.includes('multipart/')) { } else if (bodyByteSize && contentType.includes('multipart/')) {
const { error, fields, files } = await fetchAPIFileUpload({ const { error, fields, files } = await fetchAPIFileUpload({
options: config.upload as FetchAPIFileUploadOptions, options: payload.config.upload as FetchAPIFileUploadOptions,
request: mutableRequest as Request, request: req as Request,
}) })
if (error) { if (error) {
@@ -47,16 +39,12 @@ export const addDataAndFileToRequest: AddDataAndFileToRequest = async ({
} }
if (files?.file) { if (files?.file) {
mutableRequest.file = files.file req.file = files.file
} }
if (fields?._payload && typeof fields._payload === 'string') { if (fields?._payload && typeof fields._payload === 'string') {
mutableRequest.data = JSON.parse(fields._payload) req.data = JSON.parse(fields._payload)
} }
} }
return mutableRequest
} }
return incomingRequest
} }

View File

@@ -1,25 +1,17 @@
import type { import type { PayloadRequest, SanitizedConfig } from 'payload'
PayloadRequest,
PayloadRequestData,
PayloadRequestWithData,
SanitizedConfig,
} from 'payload'
/** /**
* Mutates the Request to contain 'locale' and 'fallbackLocale' based on data or searchParams * Mutates the Request to contain 'locale' and 'fallbackLocale' based on data or searchParams
*/ */
type Args = { export function addLocalesToRequestFromData(req: PayloadRequest): void {
request: PayloadRequest & PayloadRequestData
}
export function addLocalesToRequestFromData({ request }: Args): PayloadRequestWithData {
const { const {
data, data,
payload: { config }, payload: { config },
} = request } = req
if (data) { if (data) {
let localeOnReq = request.locale let localeOnReq = req.locale
let fallbackLocaleOnReq = request.fallbackLocale let fallbackLocaleOnReq = req.fallbackLocale
if (!localeOnReq && data?.locale && typeof data.locale === 'string') { if (!localeOnReq && data?.locale && typeof data.locale === 'string') {
localeOnReq = data.locale localeOnReq = data.locale
@@ -39,13 +31,9 @@ export function addLocalesToRequestFromData({ request }: Args): PayloadRequestWi
localization: config.localization, localization: config.localization,
}) })
const mutableRequest = request if (locale) req.locale = locale
if (locale) mutableRequest.locale = locale if (fallbackLocale) req.fallbackLocale = fallbackLocale
if (fallbackLocale) mutableRequest.fallbackLocale = fallbackLocale
return mutableRequest
} }
return request
} }
type SanitizeLocalesArgs = { type SanitizeLocalesArgs = {

View File

@@ -1,8 +1,8 @@
import type { PayloadRequestWithData } from 'payload' import type { PayloadRequest } from 'payload'
type CorsArgs = { type CorsArgs = {
headers: Headers headers: Headers
req: Partial<PayloadRequestWithData> req: Partial<PayloadRequest>
} }
export const headersWithCors = ({ headers, req }: CorsArgs): Headers => { export const headersWithCors = ({ headers, req }: CorsArgs): Headers => {
const cors = req?.payload.config.cors const cors = req?.payload.config.cors

View File

@@ -1,5 +1,5 @@
import type { I18nClient } from '@payloadcms/translations' import type { I18nClient } from '@payloadcms/translations'
import type { InitPageResult, Locale, PayloadRequestWithData, VisibleEntities } from 'payload' import type { InitPageResult, Locale, PayloadRequest, VisibleEntities } from 'payload'
import { initI18n } from '@payloadcms/translations' import { initI18n } from '@payloadcms/translations'
import { findLocaleFromCode } from '@payloadcms/ui/shared' import { findLocaleFromCode } from '@payloadcms/ui/shared'
@@ -66,7 +66,7 @@ export const initPage = async ({
ignoreQueryPrefix: true, ignoreQueryPrefix: true,
}), }),
url: `${payload.config.serverURL}${route}${searchParams ? queryString : ''}`, url: `${payload.config.serverURL}${route}${searchParams ? queryString : ''}`,
} as PayloadRequestWithData, } as PayloadRequest,
}, },
payload, payload,
) )

View File

@@ -1,7 +1,7 @@
import type { import type {
Data, Data,
Locale, Locale,
PayloadRequestWithData, PayloadRequest,
SanitizedCollectionConfig, SanitizedCollectionConfig,
SanitizedGlobalConfig, SanitizedGlobalConfig,
} from 'payload' } from 'payload'
@@ -14,7 +14,7 @@ export const getDocumentData = async (args: {
globalConfig?: SanitizedGlobalConfig globalConfig?: SanitizedGlobalConfig
id?: number | string id?: number | string
locale: Locale locale: Locale
req: PayloadRequestWithData req: PayloadRequest
}): Promise<Data> => { }): Promise<Data> => {
const { id, collectionConfig, globalConfig, locale, req } = args const { id, collectionConfig, globalConfig, locale, req } = args

View File

@@ -1,5 +1,5 @@
'use client' 'use client'
import type { PayloadRequestWithData } from 'payload' import type { PayloadRequest } from 'payload'
import { import {
CopyToClipboard, CopyToClipboard,
@@ -42,7 +42,7 @@ export const APIKey: React.FC<{ enabled: boolean; readOnly?: boolean }> = ({
config, config,
}, },
t, t,
} as PayloadRequestWithData, } as PayloadRequest,
siblingData: {}, siblingData: {},
}) })

View File

@@ -1,7 +1,7 @@
'use client' 'use client'
import type { FormProps } from '@payloadcms/ui' import type { FormProps } from '@payloadcms/ui'
import type { FormState, PayloadRequestWithData } from 'payload' import type { FormState, PayloadRequest } from 'payload'
import { EmailField, Form, FormSubmit, useConfig, useTranslation } from '@payloadcms/ui' import { EmailField, Form, FormSubmit, useConfig, useTranslation } from '@payloadcms/ui'
import { email } from 'payload/shared' import { email } from 'payload/shared'
@@ -67,7 +67,7 @@ export const ForgotPasswordForm: React.FC = () => {
type: 'email', type: 'email',
data: {}, data: {},
preferences: { fields: {} }, preferences: { fields: {} },
req: { t } as PayloadRequestWithData, req: { t } as PayloadRequest,
required: true, required: true,
siblingData: {}, siblingData: {},
}) })

View File

@@ -6,7 +6,7 @@ import React from 'react'
const baseClass = 'login__form' const baseClass = 'login__form'
const Link = (LinkImport.default || LinkImport) as unknown as typeof LinkImport.default const Link = (LinkImport.default || LinkImport) as unknown as typeof LinkImport.default
import type { FormState, PayloadRequestWithData } from 'payload' import type { FormState, PayloadRequest } from 'payload'
import { import {
EmailField, EmailField,
@@ -73,7 +73,7 @@ export const LoginForm: React.FC<{
type: 'email', type: 'email',
data: {}, data: {},
preferences: { fields: {} }, preferences: { fields: {} },
req: { t } as PayloadRequestWithData, req: { t } as PayloadRequest,
required: true, required: true,
siblingData: {}, siblingData: {},
}) })
@@ -95,7 +95,7 @@ export const LoginForm: React.FC<{
config, config,
}, },
t, t,
} as PayloadRequestWithData, } as PayloadRequest,
required: true, required: true,
siblingData: {}, siblingData: {},
}) })

View File

@@ -6,7 +6,7 @@ import type { SanitizedCollectionConfig, TypeWithID } from '../collections/confi
import type { SanitizedConfig } from '../config/types.js' import type { SanitizedConfig } from '../config/types.js'
import type { Field, FieldAffectingData, RichTextField, Validate } from '../fields/config/types.js' import type { Field, FieldAffectingData, RichTextField, Validate } from '../fields/config/types.js'
import type { SanitizedGlobalConfig } from '../globals/config/types.js' import type { SanitizedGlobalConfig } from '../globals/config/types.js'
import type { PayloadRequestWithData, RequestContext } from '../types/index.js' import type { PayloadRequest, RequestContext } from '../types/index.js'
import type { WithServerSidePropsComponentProps } from './elements/WithServerSideProps.js' import type { WithServerSidePropsComponentProps } from './elements/WithServerSideProps.js'
export type RichTextFieldProps< export type RichTextFieldProps<
@@ -130,7 +130,7 @@ export type BaseRichTextHookArgs<
path: (number | string)[] path: (number | string)[]
/** The Express request object. It is mocked for Local API operations. */ /** The Express request object. It is mocked for Local API operations. */
req: PayloadRequestWithData req: PayloadRequest
/** /**
* The schemaPath of the field, e.g. ["group", "myArray", "textField"]. The schemaPath is the path but without indexes and would be used in the context of field schemas, not field data. * The schemaPath of the field, e.g. ["group", "myArray", "textField"]. The schemaPath is the path but without indexes and would be used in the context of field schemas, not field data.
*/ */
@@ -218,7 +218,7 @@ type RichTextAdapterBase<
flattenLocales: boolean flattenLocales: boolean
overrideAccess?: boolean overrideAccess?: boolean
populationPromises: Promise<void>[] populationPromises: Promise<void>[]
req: PayloadRequestWithData req: PayloadRequest
showHiddenFields: boolean showHiddenFields: boolean
siblingDoc: Record<string, unknown> siblingDoc: Record<string, unknown>
}) => void }) => void

View File

@@ -4,7 +4,7 @@ import type { Permissions } from '../../auth/index.js'
import type { SanitizedCollectionConfig } from '../../collections/config/types.js' import type { SanitizedCollectionConfig } from '../../collections/config/types.js'
import type { Locale } from '../../config/types.js' import type { Locale } from '../../config/types.js'
import type { SanitizedGlobalConfig } from '../../globals/config/types.js' import type { SanitizedGlobalConfig } from '../../globals/config/types.js'
import type { PayloadRequestWithData } from '../../types/index.js' import type { PayloadRequest } from '../../types/index.js'
import type { LanguageOptions } from '../LanguageOptions.js' import type { LanguageOptions } from '../LanguageOptions.js'
export type AdminViewConfig = { export type AdminViewConfig = {
@@ -44,7 +44,7 @@ export type InitPageResult = {
languageOptions: LanguageOptions languageOptions: LanguageOptions
locale?: Locale locale?: Locale
permissions: Permissions permissions: Permissions
req: PayloadRequestWithData req: PayloadRequest
translations: ClientTranslationsObject translations: ClientTranslationsObject
visibleEntities: VisibleEntities visibleEntities: VisibleEntities
} }

View File

@@ -1,3 +1,3 @@
import type { PayloadRequestWithData } from '../types/index.js' import type { PayloadRequest } from '../types/index.js'
export default ({ req: { user } }: { req: PayloadRequestWithData }): boolean => Boolean(user) export default ({ req: { user } }: { req: PayloadRequest }): boolean => Boolean(user)

View File

@@ -1,5 +1,5 @@
import type { Access, AccessResult } from '../config/types.js' import type { Access, AccessResult } from '../config/types.js'
import type { PayloadRequestWithData } from '../types/index.js' import type { PayloadRequest } from '../types/index.js'
import { Forbidden } from '../errors/index.js' import { Forbidden } from '../errors/index.js'
@@ -8,7 +8,7 @@ type OperationArgs = {
disableErrors?: boolean disableErrors?: boolean
id?: number | string id?: number | string
isReadingStaticFile?: boolean isReadingStaticFile?: boolean
req: PayloadRequestWithData req: PayloadRequest
} }
const executeAccess = async ( const executeAccess = async (
{ id, data, disableErrors, isReadingStaticFile = false, req }: OperationArgs, { id, data, disableErrors, isReadingStaticFile = false, req }: OperationArgs,

View File

@@ -1,11 +1,11 @@
import type { AllOperations, PayloadRequestWithData } from '../types/index.js' import type { AllOperations, PayloadRequest } from '../types/index.js'
import type { Permissions } from './types.js' import type { Permissions } from './types.js'
import { getEntityPolicies } from '../utilities/getEntityPolicies.js' import { getEntityPolicies } from '../utilities/getEntityPolicies.js'
import isolateObjectProperty from '../utilities/isolateObjectProperty.js' import isolateObjectProperty from '../utilities/isolateObjectProperty.js'
type GetAccessResultsArgs = { type GetAccessResultsArgs = {
req: PayloadRequestWithData req: PayloadRequest
} }
export async function getAccessResults({ req }: GetAccessResultsArgs): Promise<Permissions> { export async function getAccessResults({ req }: GetAccessResultsArgs): Promise<Permissions> {
const results = {} as Permissions const results = {} as Permissions

View File

@@ -1,7 +1,7 @@
/* eslint-disable no-param-reassign */ /* eslint-disable no-param-reassign */
import type { CollectionConfig } from '../collections/config/types.js' import type { CollectionConfig } from '../collections/config/types.js'
import type { Field, TabAsField } from '../fields/config/types.js' import type { Field, TabAsField } from '../fields/config/types.js'
import type { PayloadRequestWithData } from '../types/index.js' import type { PayloadRequest } from '../types/index.js'
import { fieldAffectsData, tabHasName } from '../fields/config/types.js' import { fieldAffectsData, tabHasName } from '../fields/config/types.js'
@@ -105,7 +105,7 @@ const traverseFields = ({
export const getFieldsToSign = (args: { export const getFieldsToSign = (args: {
collectionConfig: CollectionConfig collectionConfig: CollectionConfig
email: string email: string
user: PayloadRequestWithData['user'] user: PayloadRequest['user']
}): Record<string, unknown> => { }): Record<string, unknown> => {
const { collectionConfig, email, user } = args const { collectionConfig, email, user } = args

View File

@@ -1,4 +1,4 @@
import type { PayloadRequestWithData } from '../../types/index.js' import type { PayloadRequest } from '../../types/index.js'
import type { Permissions } from '../types.js' import type { Permissions } from '../types.js'
import { commitTransaction } from '../../utilities/commitTransaction.js' import { commitTransaction } from '../../utilities/commitTransaction.js'
@@ -8,7 +8,7 @@ import { adminInit as adminInitTelemetry } from '../../utilities/telemetry/event
import { getAccessResults } from '../getAccessResults.js' import { getAccessResults } from '../getAccessResults.js'
type Arguments = { type Arguments = {
req: PayloadRequestWithData req: PayloadRequest
} }
export const accessOperation = async (args: Arguments): Promise<Permissions> => { export const accessOperation = async (args: Arguments): Promise<Permissions> => {

View File

@@ -1,5 +1,5 @@
import type { TypedUser } from '../../index.js' import type { TypedUser } from '../../index.js'
import type { PayloadRequestWithData } from '../../types/index.js' import type { PayloadRequest } from '../../types/index.js'
import type { Permissions } from '../types.js' import type { Permissions } from '../types.js'
import { commitTransaction } from '../../utilities/commitTransaction.js' import { commitTransaction } from '../../utilities/commitTransaction.js'
@@ -10,7 +10,7 @@ import { getAccessResults } from '../getAccessResults.js'
export type AuthArgs = { export type AuthArgs = {
headers: Request['headers'] headers: Request['headers']
req?: Omit<PayloadRequestWithData, 'user'> req?: Omit<PayloadRequest, 'user'>
} }
export type AuthResult = { export type AuthResult = {
@@ -21,7 +21,7 @@ export type AuthResult = {
export const auth = async (args: Required<AuthArgs>): Promise<AuthResult> => { export const auth = async (args: Required<AuthArgs>): Promise<AuthResult> => {
const { headers } = args const { headers } = args
const req = args.req as PayloadRequestWithData const req = args.req as PayloadRequest
const { payload } = req const { payload } = req
try { try {

View File

@@ -3,7 +3,7 @@ import httpStatus from 'http-status'
import { URL } from 'url' import { URL } from 'url'
import type { Collection } from '../../collections/config/types.js' import type { Collection } from '../../collections/config/types.js'
import type { PayloadRequestWithData } from '../../types/index.js' import type { PayloadRequest } from '../../types/index.js'
import { buildAfterOperation } from '../../collections/operations/utils.js' import { buildAfterOperation } from '../../collections/operations/utils.js'
import { APIError } from '../../errors/index.js' import { APIError } from '../../errors/index.js'
@@ -19,7 +19,7 @@ export type Arguments = {
} }
disableEmail?: boolean disableEmail?: boolean
expiration?: number expiration?: number
req: PayloadRequestWithData req: PayloadRequest
} }
export type Result = string export type Result = string

View File

@@ -1,8 +1,8 @@
import type { PayloadRequestWithData } from '../../types/index.js' import type { PayloadRequest } from '../../types/index.js'
export const initOperation = async (args: { export const initOperation = async (args: {
collection: string collection: string
req: PayloadRequestWithData req: PayloadRequest
}): Promise<boolean> => { }): Promise<boolean> => {
const { collection: slug, req } = args const { collection: slug, req } = args

View File

@@ -1,5 +1,5 @@
import type { Payload } from '../../../index.js' import type { Payload } from '../../../index.js'
import type { PayloadRequestWithData } from '../../../types/index.js' import type { PayloadRequest } from '../../../types/index.js'
import type { AuthArgs, AuthResult } from '../auth.js' import type { AuthArgs, AuthResult } from '../auth.js'
import { createLocalReq } from '../../../utilities/createLocalReq.js' import { createLocalReq } from '../../../utilities/createLocalReq.js'
@@ -10,6 +10,6 @@ export const auth = async (payload: Payload, options: AuthArgs): Promise<AuthRes
return await authOperation({ return await authOperation({
headers, headers,
req: await createLocalReq({ req: options.req as PayloadRequestWithData }, payload), req: await createLocalReq({ req: options.req as PayloadRequest }, payload),
}) })
} }

View File

@@ -1,5 +1,5 @@
import type { CollectionSlug, Payload, RequestContext } from '../../../index.js' import type { CollectionSlug, Payload, RequestContext } from '../../../index.js'
import type { PayloadRequestWithData } from '../../../types/index.js' import type { PayloadRequest } from '../../../types/index.js'
import type { Result } from '../forgotPassword.js' import type { Result } from '../forgotPassword.js'
import { APIError } from '../../../errors/index.js' import { APIError } from '../../../errors/index.js'
@@ -14,7 +14,7 @@ export type Options<T extends CollectionSlug> = {
} }
disableEmail?: boolean disableEmail?: boolean
expiration?: number expiration?: number
req?: PayloadRequestWithData req?: PayloadRequest
} }
async function localForgotPassword<T extends CollectionSlug>( async function localForgotPassword<T extends CollectionSlug>(

View File

@@ -4,7 +4,7 @@ import type {
Payload, Payload,
RequestContext, RequestContext,
} from '../../../index.js' } from '../../../index.js'
import type { PayloadRequestWithData } from '../../../types/index.js' import type { PayloadRequest } from '../../../types/index.js'
import type { Result } from '../login.js' import type { Result } from '../login.js'
import { APIError } from '../../../errors/index.js' import { APIError } from '../../../errors/index.js'
@@ -22,7 +22,7 @@ export type Options<TSlug extends CollectionSlug> = {
fallbackLocale?: string fallbackLocale?: string
locale?: string locale?: string
overrideAccess?: boolean overrideAccess?: boolean
req?: PayloadRequestWithData req?: PayloadRequest
showHiddenFields?: boolean showHiddenFields?: boolean
} }

View File

@@ -1,5 +1,5 @@
import type { CollectionSlug, Payload, RequestContext } from '../../../index.js' import type { CollectionSlug, Payload, RequestContext } from '../../../index.js'
import type { PayloadRequestWithData } from '../../../types/index.js' import type { PayloadRequest } from '../../../types/index.js'
import type { Result } from '../resetPassword.js' import type { Result } from '../resetPassword.js'
import { APIError } from '../../../errors/index.js' import { APIError } from '../../../errors/index.js'
@@ -14,7 +14,7 @@ export type Options<T extends CollectionSlug> = {
token: string token: string
} }
overrideAccess: boolean overrideAccess: boolean
req?: PayloadRequestWithData req?: PayloadRequest
} }
async function localResetPassword<T extends CollectionSlug>( async function localResetPassword<T extends CollectionSlug>(

View File

@@ -1,5 +1,5 @@
import type { CollectionSlug, Payload, RequestContext } from '../../../index.js' import type { CollectionSlug, Payload, RequestContext } from '../../../index.js'
import type { PayloadRequestWithData } from '../../../types/index.js' import type { PayloadRequest } from '../../../types/index.js'
import { APIError } from '../../../errors/index.js' import { APIError } from '../../../errors/index.js'
import { createLocalReq } from '../../../utilities/createLocalReq.js' import { createLocalReq } from '../../../utilities/createLocalReq.js'
@@ -12,7 +12,7 @@ export type Options<T extends CollectionSlug> = {
email email
} }
overrideAccess: boolean overrideAccess: boolean
req?: PayloadRequestWithData req?: PayloadRequest
} }
async function localUnlock<T extends CollectionSlug>( async function localUnlock<T extends CollectionSlug>(

View File

@@ -1,5 +1,5 @@
import type { CollectionSlug, Payload, RequestContext } from '../../../index.js' import type { CollectionSlug, Payload, RequestContext } from '../../../index.js'
import type { PayloadRequestWithData } from '../../../types/index.js' import type { PayloadRequest } from '../../../types/index.js'
import { APIError } from '../../../errors/index.js' import { APIError } from '../../../errors/index.js'
import { createLocalReq } from '../../../utilities/createLocalReq.js' import { createLocalReq } from '../../../utilities/createLocalReq.js'
@@ -8,7 +8,7 @@ import { verifyEmailOperation } from '../verifyEmail.js'
export type Options<T extends CollectionSlug> = { export type Options<T extends CollectionSlug> = {
collection: T collection: T
context?: RequestContext context?: RequestContext
req?: PayloadRequestWithData req?: PayloadRequest
token: string token: string
} }

View File

@@ -2,7 +2,7 @@ import jwt from 'jsonwebtoken'
import type { Collection, DataFromCollectionSlug } from '../../collections/config/types.js' import type { Collection, DataFromCollectionSlug } from '../../collections/config/types.js'
import type { CollectionSlug } from '../../index.js' import type { CollectionSlug } from '../../index.js'
import type { PayloadRequestWithData } from '../../types/index.js' import type { PayloadRequest } from '../../types/index.js'
import type { User } from '../types.js' import type { User } from '../types.js'
import { buildAfterOperation } from '../../collections/operations/utils.js' import { buildAfterOperation } from '../../collections/operations/utils.js'
@@ -32,7 +32,7 @@ export type Arguments = {
} }
depth?: number depth?: number
overrideAccess?: boolean overrideAccess?: boolean
req: PayloadRequestWithData req: PayloadRequest
showHiddenFields?: boolean showHiddenFields?: boolean
} }

View File

@@ -1,13 +1,13 @@
import httpStatus from 'http-status' import httpStatus from 'http-status'
import type { Collection } from '../../collections/config/types.js' import type { Collection } from '../../collections/config/types.js'
import type { PayloadRequestWithData } from '../../types/index.js' import type { PayloadRequest } from '../../types/index.js'
import { APIError } from '../../errors/index.js' import { APIError } from '../../errors/index.js'
export type Arguments = { export type Arguments = {
collection: Collection collection: Collection
req: PayloadRequestWithData req: PayloadRequest
} }
export const logoutOperation = async (incomingArgs: Arguments): Promise<boolean> => { export const logoutOperation = async (incomingArgs: Arguments): Promise<boolean> => {

View File

@@ -1,7 +1,7 @@
import jwt from 'jsonwebtoken' import jwt from 'jsonwebtoken'
import type { Collection } from '../../collections/config/types.js' import type { Collection } from '../../collections/config/types.js'
import type { PayloadRequestWithData } from '../../types/index.js' import type { PayloadRequest } from '../../types/index.js'
import type { ClientUser, User } from '../types.js' import type { ClientUser, User } from '../types.js'
export type MeOperationResult = { export type MeOperationResult = {
@@ -15,7 +15,7 @@ export type MeOperationResult = {
export type Arguments = { export type Arguments = {
collection: Collection collection: Collection
currentToken?: string currentToken?: string
req: PayloadRequestWithData req: PayloadRequest
} }
export const meOperation = async (args: Arguments): Promise<MeOperationResult> => { export const meOperation = async (args: Arguments): Promise<MeOperationResult> => {

View File

@@ -2,7 +2,7 @@ import jwt from 'jsonwebtoken'
import url from 'url' import url from 'url'
import type { BeforeOperationHook, Collection } from '../../collections/config/types.js' import type { BeforeOperationHook, Collection } from '../../collections/config/types.js'
import type { Document, PayloadRequestWithData } from '../../types/index.js' import type { Document, PayloadRequest } from '../../types/index.js'
import { buildAfterOperation } from '../../collections/operations/utils.js' import { buildAfterOperation } from '../../collections/operations/utils.js'
import { Forbidden } from '../../errors/index.js' import { Forbidden } from '../../errors/index.js'
@@ -21,7 +21,7 @@ export type Result = {
export type Arguments = { export type Arguments = {
collection: Collection collection: Collection
req: PayloadRequestWithData req: PayloadRequest
} }
export const refreshOperation = async (incomingArgs: Arguments): Promise<Result> => { export const refreshOperation = async (incomingArgs: Arguments): Promise<Result> => {

Some files were not shown because too many files have changed in this diff Show More