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. */
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. */
import { REST_DELETE, REST_GET, REST_PATCH, REST_POST } from '@payloadcms/next/routes'
import config from 'payload-config'
export const GET = REST_GET(config)

View File

@@ -1,6 +1,6 @@
/* 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. */
import { GET_STATIC_FILE } from '@payloadcms/next/routes'
import config from 'payload-config'
export const GET = GET_STATIC_FILE(config)

View File

@@ -1,6 +1,6 @@
/* 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. */
import { GRAPHQL_POST } from '@payloadcms/next/routes'
import config from 'payload-config'
export const POST = GRAPHQL_POST(config)

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,10 +1,12 @@
import httpStatus from 'http-status'
import type { PayloadHandler } from '../../exports/config'
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({
key: routeParams.key,
key: req.routeParams?.key as string,
req,
user: req.user,
})

View File

@@ -4,9 +4,9 @@ import type { PayloadHandler } from '../../exports/config'
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({
key: routeParams.key,
key: req.routeParams?.key as string,
req,
user: req.user,
})

View File

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

View File

@@ -54,6 +54,12 @@ export type CustomPayloadRequest<U = any> = {
payloadDataLoader?: DataLoader<string, TypeWithID>
/** Resized versions of the image that was uploaded during this request */
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 */
t: TFunction
/**

View File

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

View File

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

View File

@@ -7,18 +7,11 @@ import { getAfterDeleteHook } from './hooks/afterDelete'
import { getBeforeChangeHook } from './hooks/beforeChange'
import { getCacheUploadsAfterChangeHook, getCacheUploadsAfterDeleteHook } from './hooks/uploadCache'
import { getStaticHandler } from './staticHandler'
import { extendWebpackConfig } from './webpack'
export const payloadCloud =
(pluginOptions?: PluginOptions) =>
(incomingConfig: Config): Config => {
let config = { ...incomingConfig }
const webpack = extendWebpackConfig(incomingConfig)
config.admin = {
...(config.admin || {}),
webpack,
}
if (process.env.PAYLOAD_CLOUD !== 'true') {
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',
method: 'get',
handler: ({ req }) => {
handler: (req) => {
const sp = new URL(req.url).searchParams
return Response.json({ message: `Hi ${sp.get('name')}!` })
},
@@ -60,7 +60,7 @@ export default buildConfigWithDefaults({
path: '/config',
method: 'get',
root: true,
handler: ({ req }) => {
handler: (req) => {
return Response.json(req.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',
method: 'get',
handler: ({ routeParams }) => {
return Response.json({ message: `Hello ${routeParams.name} @ ${routeParams.group}` })
handler: (req) => {
return Response.json({
message: `Hello ${req.routeParams.name as string} @ ${req.routeParams.group as string}`,
})
},
},
{
path: '/say-hello/:name',
method: 'get',
handler: ({ routeParams }) => {
return Response.json({ message: `Hello ${routeParams.name}!` })
handler: (req) => {
return Response.json({ message: `Hello ${req.routeParams.name as string}!` })
},
},
{
path: '/whoami',
method: 'post',
handler: ({ req }) => {
handler: (req) => {
return Response.json({
name: req.data.name,
age: req.data.age,

View File

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

View File

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