Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions .zed/settings.json
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd prefer not to include editor specific config files in the repo, I don't use Zed personally and there's not config for VSCode, either 🙂

Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"lsp": {
"biome": {
"binary": {
"path": "./node_modules/@biomejs/biome/bin/biome",
"arguments": ["lsp-proxy"]
}
}
},
"languages": {
"JSON": { "formatter": { "language_server": { "name": "biome" } } },
"JSONC": { "formatter": { "language_server": { "name": "biome" } } },
"JavaScript": {
"formatter": { "language_server": { "name": "biome" } },
"code_actions_on_format": {
"source.fixAll.biome": true,
"source.organizeImports.biome": true
}
},
"TSX": {
"formatter": { "language_server": { "name": "biome" } },
"code_actions_on_format": {
"source.fixAll.biome": true,
"source.organizeImports.biome": true
}
},
"TypeScript": {
"formatter": { "language_server": { "name": "biome" } },
"code_actions_on_format": {
"source.fixAll.biome": true,
"source.organizeImports.biome": true
}
}
}
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "payload-oapi",
"description": "An OpenAPI plugin for Payload CMS",
"version": "0.2.5",
"version": "0.2.6",
"homepage:": "https://github.com/janbuchar/payload-oapi",
"repository:": "https://github.com/janbuchar/payload-oapi",
"main": "dist/index.js",
Expand Down
31 changes: 24 additions & 7 deletions src/openapi/generators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,7 @@ const isOpenToPublic = async (checker: Access): Promise<boolean> => {

const generateCollectionOperations = async (
collection: Collection,
apiBasePath: string,
): Promise<Record<string, OpenAPIV3.PathItemObject & OpenAPIV3_1.PathItemObject>> => {
const { slug } = collection.config
const { singular, plural } = collectionName(collection)
Expand All @@ -400,7 +401,7 @@ const generateCollectionOperations = async (
} satisfies OpenAPIV3_1.ResponsesObject & OpenAPIV3.ResponsesObject

return {
[`/api/${slug}`]: {
[`${apiBasePath}/${slug}`]: {
get: {
operationId: componentName('schemas', plural, { prefix: 'list' }),
summary: `Retrieve a list of ${plural}`,
Expand Down Expand Up @@ -462,7 +463,7 @@ const generateCollectionOperations = async (
security: (await isOpenToPublic(collection.config.access.create)) ? [] : [apiKeySecurity],
},
},
[`/api/${slug}/{id}`]: {
[`${apiBasePath}/${slug}/{id}`]: {
parameters: [
...baseQueryParams,
{
Expand Down Expand Up @@ -563,13 +564,14 @@ const generateGlobalSchemas = (

const generateGlobalOperations = async (
global: SanitizedGlobalConfig,
apiBasePath: string,
): Promise<Record<string, OpenAPIV3.PathItemObject & OpenAPIV3_1.PathItemObject>> => {
const slug = global.slug
const singular = globalName(global)
const tags = [singular]

return {
[`/api/globals/${slug}`]: {
[`${apiBasePath}/globals/${slug}`]: {
get: {
summary: `Get the ${singular}`,
tags,
Expand Down Expand Up @@ -652,6 +654,15 @@ const generateComponents = (
return { schemas, requestBodies, responses }
}

/**
* Prefer the `apiBasePath` from plugin options (not null),
* otherwise use the currently configured api route from payload.
*/
const getApiBasePath = (
options: SanitizedPluginOptions,
req: Pick<PayloadRequest, 'payload'>,
): string => (options.apiBasePath !== null ? options.apiBasePath : req.payload.config.routes.api)

export const generateV30Spec = async (
req: Pick<PayloadRequest, 'payload' | 'protocol' | 'headers'>,
options: SanitizedPluginOptions,
Expand All @@ -663,15 +674,18 @@ export const generateV30Spec = async (
shouldIncludeCollection(collection, filters),
)
const globals = req.payload.globals.config.filter(global => shouldIncludeGlobal(global, filters))
const apiBasePath = getApiBasePath(options, req)

const spec = {
openapi: '3.0.3',
info: options.metadata,
servers: [{ url: `${req.protocol}//${req.headers.get('host')}` }],
paths: Object.assign(
{},
...(await Promise.all(collections.map(generateCollectionOperations))),
...(await Promise.all(globals.map(generateGlobalOperations))),
...(await Promise.all(
collections.map(collection => generateCollectionOperations(collection, apiBasePath)),
)),
...(await Promise.all(globals.map(global => generateGlobalOperations(global, apiBasePath)))),
),
components: {
securitySchemes: generateSecuritySchemes(options.authEndpoint),
Expand Down Expand Up @@ -727,15 +741,18 @@ export const generateV31Spec = async (
shouldIncludeCollection(collection, filters),
)
const globals = req.payload.globals.config.filter(global => shouldIncludeGlobal(global, filters))
const apiBasePath = getApiBasePath(options, req)

const spec = {
openapi: '3.1.0',
info: options.metadata,
servers: [{ url: `${req.protocol}//${req.headers.get('host')}` }],
paths: Object.assign(
{},
...(await Promise.all(collections.map(generateCollectionOperations))),
...(await Promise.all(globals.map(generateGlobalOperations))),
...(await Promise.all(
collections.map(collection => generateCollectionOperations(collection, apiBasePath)),
)),
...(await Promise.all(globals.map(global => generateGlobalOperations(global, apiBasePath)))),
),
components: {
securitySchemes: generateSecuritySchemes(options.authEndpoint),
Expand Down
2 changes: 2 additions & 0 deletions src/openapiPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const openapi =
metadata,
enabled = true,
filters = {},
apiBasePath = null,
}: PluginOptions): Plugin =>
({ endpoints = [], ...config }) => {
if (!enabled) {
Expand All @@ -28,6 +29,7 @@ const openapi =
metadata,
authEndpoint,
filters,
apiBasePath,
}),
},
{
Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export interface PluginOptions {
authEndpoint?: string
metadata: OpenAPIMetadata
filters?: FilterOptions
apiBasePath?: string | null
}

export type SanitizedPluginOptions = Required<Omit<PluginOptions, 'enabled' | 'specEndpoint'>>
58 changes: 58 additions & 0 deletions test/openapi-generators.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ describe('openapi generators', () => {
authEndpoint: '/api/auth',
metadata: { title: 'Test API', version: '1.0' },
filters: {},
apiBasePath: null,
},
)

Expand Down Expand Up @@ -95,6 +96,7 @@ describe('openapi generators', () => {
authEndpoint: '/api/auth',
metadata: { title: 'Test API', version: '1.0' },
filters: {},
apiBasePath: null,
},
)

Expand Down Expand Up @@ -145,6 +147,7 @@ describe('openapi generators', () => {
authEndpoint: '/api/auth',
metadata: { title: 'Test API', version: '1.0' },
filters: {},
apiBasePath: null,
},
)

Expand Down Expand Up @@ -179,6 +182,7 @@ describe('openapi generators', () => {
authEndpoint: '/api/auth',
metadata: { title: 'Test API', version: '1.0' },
filters: {},
apiBasePath: null,
},
)

Expand Down Expand Up @@ -207,6 +211,7 @@ describe('openapi generators', () => {
authEndpoint: '/api/auth',
metadata: { title: 'Test API', version: '1.0' },
filters: {},
apiBasePath: null,
},
)

Expand All @@ -230,6 +235,7 @@ describe('openapi generators', () => {
authEndpoint: '/api/auth',
metadata: { title: 'Test API', version: '1.0' },
filters: { includeCollections: ['posts'] },
apiBasePath: null,
},
)

Expand All @@ -249,6 +255,7 @@ describe('openapi generators', () => {
authEndpoint: '/api/auth',
metadata: { title: 'Test API', version: '1.0' },
filters: { excludeCollections: ['users'] },
apiBasePath: null,
},
)

Expand All @@ -268,6 +275,7 @@ describe('openapi generators', () => {
authEndpoint: '/api/auth',
metadata: { title: 'Test API', version: '1.0' },
filters: { hideInternalCollections: true },
apiBasePath: null,
},
)

Expand All @@ -289,6 +297,7 @@ describe('openapi generators', () => {
authEndpoint: '/api/auth',
metadata: { title: 'Test API', version: '1.0' },
filters: { includeCollections: [] },
apiBasePath: null,
},
)

Expand Down Expand Up @@ -317,6 +326,7 @@ describe('openapi generators', () => {
authEndpoint: '/api/auth',
metadata: { title: 'Test API', version: '1.0' },
filters: { includeGlobals: ['settings'] },
apiBasePath: null,
},
)

Expand Down Expand Up @@ -344,11 +354,59 @@ describe('openapi generators', () => {
authEndpoint: '/api/auth',
metadata: { title: 'Test API', version: '1.0' },
filters: { excludeGlobals: ['footer'] },
apiBasePath: null,
},
)

expect(spec.paths['/api/globals/settings']).toBeDefined()
expect(spec.paths['/api/globals/footer']).toBeUndefined()
})
})

test('apiBasePath option changes operation paths', async () => {
const payload = await buildPayload({
collections: [Posts],
})

const spec = await generateV30Spec(
{ protocol: 'https', headers: new Headers({ host: 'localhost' }), payload },
{
openapiVersion: '3.0',
authEndpoint: '/api/auth',
metadata: { title: 'Test API', version: '1.0' },
filters: { hideInternalCollections: true },
apiBasePath: '/api/custom',
},
)

expect(spec.paths['/api/custom/posts']).toBeDefined()
expect(spec.paths['/api/custom/payload-preferences']).toBeUndefined()
expect(spec.paths['/api/custom/payload-migrations']).toBeUndefined()
expect(spec.paths['/api/custom/payload-locked-documents']).toBeUndefined()
})

test('payload routes api config changes operation paths', async () => {
const payload = await buildPayload({
collections: [Posts],
routes: {
api: '/api/custom',
},
})

const spec = await generateV30Spec(
{ protocol: 'https', headers: new Headers({ host: 'localhost' }), payload },
{
openapiVersion: '3.0',
authEndpoint: '/api/auth',
metadata: { title: 'Test API', version: '1.0' },
filters: { hideInternalCollections: true },
apiBasePath: null,
},
)

expect(spec.paths['/api/custom/posts']).toBeDefined()
expect(spec.paths['/api/custom/payload-preferences']).toBeUndefined()
expect(spec.paths['/api/custom/payload-migrations']).toBeUndefined()
expect(spec.paths['/api/custom/payload-locked-documents']).toBeUndefined()
})
})