feat: supports root endpoints

This commit is contained in:
Jacob Fletcher
2022-09-22 10:43:20 -04:00
parent 686085496a
commit 52cd3b4a7e
12 changed files with 150 additions and 17 deletions

View File

@@ -226,7 +226,7 @@ export type CollectionConfig = {
/**
* Custom rest api endpoints
*/
endpoints?: Endpoint[]
endpoints?: Omit<Endpoint, 'root'>[]
/**
* Access control
*/

View File

@@ -113,7 +113,7 @@ export default function registerCollections(ctx: Payload): void {
}
const endpoints = buildEndpoints(collection);
mountEndpoints(router, endpoints);
mountEndpoints(ctx.express, router, endpoints);
ctx.router.use(`/${slug}`, router);
}

View File

@@ -8,6 +8,7 @@ const component = joi.alternatives().try(
export const endpointsSchema = joi.array().items(joi.object({
path: joi.string(),
method: joi.string().valid('get', 'head', 'post', 'put', 'patch', 'delete', 'connect', 'options'),
root: joi.bool(),
handler: joi.alternatives().try(
joi.array().items(joi.func()),
joi.func(),

View File

@@ -79,16 +79,19 @@ export type AccessResult = boolean | Where;
*/
export type Access = (args?: any) => AccessResult | Promise<AccessResult>;
export interface PayloadHandler {(
export interface PayloadHandler {
(
req: PayloadRequest,
res: Response,
next: NextFunction,
): void }
): void
}
export type Endpoint = {
path: string
method: 'get' | 'head' | 'post' | 'put' | 'patch' | 'delete' | 'connect' | 'options' | string
handler: PayloadHandler | PayloadHandler[]
root?: boolean
}
export type AdminView = React.ComponentType<{ user: User, canAccessAdmin: boolean }>

View File

@@ -1,9 +1,13 @@
import { Router } from 'express';
import { Express, Router } from 'express';
import { Endpoint } from '../config/types';
function mountEndpoints(router: Router, endpoints: Endpoint[]): void {
function mountEndpoints(express: Express, router: Router, endpoints: Endpoint[]): void {
endpoints.forEach((endpoint) => {
router[endpoint.method](endpoint.path, endpoint.handler);
if (!endpoint.root) {
router[endpoint.method](endpoint.path, endpoint.handler);
} else {
express[endpoint.method](endpoint.path, endpoint.handler);
}
});
}

View File

@@ -56,7 +56,7 @@ export type GlobalConfig = {
beforeRead?: BeforeReadHook[]
afterRead?: AfterReadHook[]
}
endpoints?: Endpoint[],
endpoints?: Omit<Endpoint, 'root'>[],
access?: {
read?: Access;
readDrafts?: Access;

View File

@@ -48,7 +48,7 @@ export default function initGlobals(ctx: Payload): void {
const { slug } = global;
const endpoints = buildEndpoints(global);
mountEndpoints(router, endpoints);
mountEndpoints(ctx.express, router, endpoints);
ctx.router.use(`/globals/${slug}`, router);
});

View File

@@ -106,7 +106,7 @@ export const init = (payload: Payload, options: InitOptions): void => {
initGraphQLPlayground(payload);
}
mountEndpoints(payload.router, payload.config.endpoints);
mountEndpoints(options.express, payload.router, payload.config.endpoints);
// Bind router to API
payload.express.use(payload.config.routes.api, payload.router);