chore: custom handler type signature adjustment

This commit is contained in:
Jarrod Flesch
2024-02-26 09:41:19 -05:00
parent bf11eacf5a
commit a6cf73b6d1
19 changed files with 41 additions and 67 deletions

View File

@@ -1,6 +1,6 @@
/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */ /* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */
import { REST_DELETE, REST_GET, REST_PATCH, REST_POST } from '@payloadcms/next/routes'
/* DO NOT MODIFY it because it could be re-written at any time. */ /* DO NOT MODIFY it because it could be re-written at any time. */
import { REST_DELETE, REST_GET, REST_PATCH, REST_POST } from '@payloadcms/next/routes'
import config from 'payload-config' import config from 'payload-config'
export const GET = REST_GET(config) export const GET = REST_GET(config)

View File

@@ -1,6 +1,6 @@
/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */ /* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */
import { GET_STATIC_FILE } from '@payloadcms/next/routes'
/* DO NOT MODIFY it because it could be re-written at any time. */ /* DO NOT MODIFY it because it could be re-written at any time. */
import { GET_STATIC_FILE } from '@payloadcms/next/routes'
import config from 'payload-config' import config from 'payload-config'
export const GET = GET_STATIC_FILE(config) export const GET = GET_STATIC_FILE(config)

View File

@@ -1,6 +1,6 @@
/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */ /* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */
import { GRAPHQL_POST } from '@payloadcms/next/routes'
/* DO NOT MODIFY it because it could be re-written at any time. */ /* DO NOT MODIFY it because it could be re-written at any time. */
import { GRAPHQL_POST } from '@payloadcms/next/routes'
import config from 'payload-config' import config from 'payload-config'
export const POST = GRAPHQL_POST(config) export const POST = GRAPHQL_POST(config)

View File

@@ -130,10 +130,8 @@ const handleCustomEndpoints = ({
}) })
if (customEndpoint) { if (customEndpoint) {
return customEndpoint.handler({ payloadRequest.routeParams = handlerParams
req: payloadRequest, return customEndpoint.handler(payloadRequest)
routeParams: handlerParams,
})
} }
} }

View File

@@ -94,6 +94,7 @@ export const createPayloadRequest = async ({
payloadUploadSizes: {}, payloadUploadSizes: {},
port: urlProperties.port, port: urlProperties.port,
protocol: urlProperties.protocol, protocol: urlProperties.protocol,
routeParams: params || {},
search: urlProperties.search, search: urlProperties.search,
searchParams: urlProperties.searchParams, searchParams: urlProperties.searchParams,
t: i18n.t, t: i18n.t,

View File

@@ -7,7 +7,10 @@
"outDir": "./dist" /* Specify an output folder for all emitted files. */, "outDir": "./dist" /* Specify an output folder for all emitted files. */,
"rootDir": "./src" /* Specify the root folder within your source files. */, "rootDir": "./src" /* Specify the root folder within your source files. */,
"allowImportingTsExtensions": true, "allowImportingTsExtensions": true,
"sourceMap": true "sourceMap": true,
"paths": {
"payload-config": ["./src/config.ts"]
}
}, },
"exclude": [ "exclude": [
"src/**/*.spec.js", "src/**/*.spec.js",

View File

@@ -224,15 +224,7 @@ export type Access<T = any, U = any> = (
) => AccessResult | Promise<AccessResult> ) => AccessResult | Promise<AccessResult>
/** Equivalent to express middleware, but with an enhanced request object */ /** Equivalent to express middleware, but with an enhanced request object */
export type PayloadHandler = ({ export type PayloadHandler = (req: PayloadRequest) => Promise<Response> | Response
req,
routeParams,
}: {
req: PayloadRequest
routeParams: {
[key: string]: string
}
}) => Promise<Response> | Response
/** /**
* Docs: https://payloadcms.com/docs/rest-api/overview#custom-endpoints * Docs: https://payloadcms.com/docs/rest-api/overview#custom-endpoints

View File

@@ -1,10 +1,12 @@
import httpStatus from 'http-status' import httpStatus from 'http-status'
import type { PayloadHandler } from '../../exports/config'
import deleteOperation from '../operations/delete' import deleteOperation from '../operations/delete'
export const deleteHandler = async ({ req, routeParams }): Promise<Response> => { export const deleteHandler: PayloadHandler = async (req): Promise<Response> => {
const result = await deleteOperation({ const result = await deleteOperation({
key: routeParams.key, key: req.routeParams?.key as string,
req, req,
user: req.user, user: req.user,
}) })

View File

@@ -4,9 +4,9 @@ import type { PayloadHandler } from '../../exports/config'
import findOne from '../operations/findOne' import findOne from '../operations/findOne'
export const findByIDHandler: PayloadHandler = async ({ req, routeParams }): Promise<Response> => { export const findByIDHandler: PayloadHandler = async (req): Promise<Response> => {
const result = await findOne({ const result = await findOne({
key: routeParams.key, key: req.routeParams?.key as string,
req, req,
user: req.user, user: req.user,
}) })

View File

@@ -4,11 +4,11 @@ import type { PayloadHandler } from '../../exports/config'
import update from '../operations/update' import update from '../operations/update'
export const updateHandler: PayloadHandler = async ({ req, routeParams }) => { export const updateHandler: PayloadHandler = async (req) => {
const payloadRequest = req const payloadRequest = req
const doc = await update({ const doc = await update({
key: routeParams?.key, key: req.routeParams?.key as string,
req: payloadRequest, req: payloadRequest,
user: payloadRequest?.user, user: payloadRequest?.user,
value: payloadRequest.data.value || payloadRequest.data, value: payloadRequest.data.value || payloadRequest.data,

View File

@@ -54,6 +54,12 @@ export type CustomPayloadRequest<U = any> = {
payloadDataLoader?: DataLoader<string, TypeWithID> payloadDataLoader?: DataLoader<string, TypeWithID>
/** Resized versions of the image that was uploaded during this request */ /** Resized versions of the image that was uploaded during this request */
payloadUploadSizes?: Record<string, Buffer> payloadUploadSizes?: Record<string, Buffer>
/** The route parameters
* @example
* /:collection/:id -> /posts/123
* { collection: 'posts', id: '123' }
*/
routeParams?: Record<string, unknown>
/** Translate function - duplicate of i18n.t */ /** Translate function - duplicate of i18n.t */
t: TFunction t: TFunction
/** /**

View File

@@ -92,6 +92,7 @@ export const createLocalReq: CreateLocalReq = async (
req.t = i18n.t req.t = i18n.t
req.user = user || req?.user || null req.user = user || req?.user || null
req.payloadDataLoader = req?.payloadDataLoader || getDataLoader(req) req.payloadDataLoader = req?.payloadDataLoader || getDataLoader(req)
req.routeParams = req?.routeParams || {}
if (!req?.url) attachFakeURLProperties(req) if (!req?.url) attachFakeURLProperties(req)

View File

@@ -17,7 +17,7 @@ export const getCacheUploadsAfterChangeHook =
if (res) { if (res) {
if (operation === 'update') { if (operation === 'update') {
// Unawaited promise // Unawaited promise
purge({ doc, endpoint, operation, req }) void purge({ doc, endpoint, operation, req })
} }
} }
return doc return doc
@@ -31,7 +31,7 @@ export const getCacheUploadsAfterDeleteHook =
const { res } = req const { res } = req
if (res) { if (res) {
// Unawaited promise // Unawaited promise
purge({ doc, endpoint, operation: 'delete', req }) void purge({ doc, endpoint, operation: 'delete', req })
} }
return doc return doc
} }

View File

@@ -7,18 +7,11 @@ import { getAfterDeleteHook } from './hooks/afterDelete'
import { getBeforeChangeHook } from './hooks/beforeChange' import { getBeforeChangeHook } from './hooks/beforeChange'
import { getCacheUploadsAfterChangeHook, getCacheUploadsAfterDeleteHook } from './hooks/uploadCache' import { getCacheUploadsAfterChangeHook, getCacheUploadsAfterDeleteHook } from './hooks/uploadCache'
import { getStaticHandler } from './staticHandler' import { getStaticHandler } from './staticHandler'
import { extendWebpackConfig } from './webpack'
export const payloadCloud = export const payloadCloud =
(pluginOptions?: PluginOptions) => (pluginOptions?: PluginOptions) =>
(incomingConfig: Config): Config => { (incomingConfig: Config): Config => {
let config = { ...incomingConfig } let config = { ...incomingConfig }
const webpack = extendWebpackConfig(incomingConfig)
config.admin = {
...(config.admin || {}),
webpack,
}
if (process.env.PAYLOAD_CLOUD !== 'true') { if (process.env.PAYLOAD_CLOUD !== 'true') {
return config // only modified webpack return config // only modified webpack

View File

@@ -1,24 +0,0 @@
import type { Config } from 'payload/config'
import type { Configuration as WebpackConfig } from 'webpack'
import path from 'path'
export const extendWebpackConfig =
(config: Config): ((webpackConfig: WebpackConfig) => WebpackConfig) =>
(webpackConfig) => {
const existingWebpackConfig =
typeof config.admin?.webpack === 'function'
? config.admin.webpack(webpackConfig)
: webpackConfig
return {
...existingWebpackConfig,
resolve: {
...(existingWebpackConfig.resolve || {}),
alias: {
...(existingWebpackConfig.resolve?.alias || {}),
'@payloadcms/plugin-cloud': path.resolve(__dirname, './admin.js'),
},
},
}
}

View File

@@ -38,7 +38,7 @@ export default buildConfigWithDefaults({
{ {
path: '/greet', path: '/greet',
method: 'get', method: 'get',
handler: ({ req }) => { handler: (req) => {
const sp = new URL(req.url).searchParams const sp = new URL(req.url).searchParams
return Response.json({ message: `Hi ${sp.get('name')}!` }) return Response.json({ message: `Hi ${sp.get('name')}!` })
}, },
@@ -60,7 +60,7 @@ export default buildConfigWithDefaults({
path: '/config', path: '/config',
method: 'get', method: 'get',
root: true, root: true,
handler: ({ req }) => { handler: (req) => {
return Response.json(req.payload.config) return Response.json(req.payload.config)
}, },
custom: { description: 'Get the sanitized payload config' }, custom: { description: 'Get the sanitized payload config' },

View File

@@ -11,21 +11,23 @@ export const collectionEndpoints: CollectionConfig['endpoints'] = [
{ {
path: '/say-hello/:group/:name', path: '/say-hello/:group/:name',
method: 'get', method: 'get',
handler: ({ routeParams }) => { handler: (req) => {
return Response.json({ message: `Hello ${routeParams.name} @ ${routeParams.group}` }) return Response.json({
message: `Hello ${req.routeParams.name as string} @ ${req.routeParams.group as string}`,
})
}, },
}, },
{ {
path: '/say-hello/:name', path: '/say-hello/:name',
method: 'get', method: 'get',
handler: ({ routeParams }) => { handler: (req) => {
return Response.json({ message: `Hello ${routeParams.name}!` }) return Response.json({ message: `Hello ${req.routeParams.name as string}!` })
}, },
}, },
{ {
path: '/whoami', path: '/whoami',
method: 'post', method: 'post',
handler: ({ req }) => { handler: (req) => {
return Response.json({ return Response.json({
name: req.data.name, name: req.data.name,
age: req.data.age, age: req.data.age,

View File

@@ -6,7 +6,7 @@ export const globalEndpoints: GlobalConfig['endpoints'] = [
{ {
path: `/${globalEndpoint}`, path: `/${globalEndpoint}`,
method: 'post', method: 'post',
handler: ({ req }) => { handler: (req) => {
return Response.json(req.body) return Response.json(req.body)
}, },
}, },

View File

@@ -6,7 +6,7 @@ export const endpoints: Config['endpoints'] = [
{ {
path: `/${applicationEndpoint}`, path: `/${applicationEndpoint}`,
method: 'post', method: 'post',
handler: ({ req }) => { handler: (req) => {
return Response.json(req.body) return Response.json(req.body)
}, },
}, },
@@ -20,7 +20,7 @@ export const endpoints: Config['endpoints'] = [
{ {
path: `/${applicationEndpoint}/i18n`, path: `/${applicationEndpoint}/i18n`,
method: 'get', method: 'get',
handler: ({ req }) => { handler: (req) => {
return Response.json({ message: req.t('general:updatedSuccessfully') }) return Response.json({ message: req.t('general:updatedSuccessfully') })
}, },
}, },
@@ -34,7 +34,7 @@ export const endpoints: Config['endpoints'] = [
{ {
path: `/${rootEndpoint}`, path: `/${rootEndpoint}`,
method: 'post', method: 'post',
handler: ({ req }) => { handler: (req) => {
return Response.json(req.body) return Response.json(req.body)
}, },
}, },