Last active
May 11, 2023 21:33
-
-
Save kepek/373a88ecee54970e77356bdb6825229e to your computer and use it in GitHub Desktop.
@strapi/plugin-documentation middleware which expose openapi.yaml & swagger.json. Tested with 4.x
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* `documentation` middleware | |
*/ | |
import { Strapi } from '@strapi/strapi'; | |
import * as fs from 'fs'; | |
import * as path from 'path'; | |
import yaml from 'js-yaml'; | |
function getDocumentationService(ctx, strapi: Strapi) { | |
return strapi?.plugins['documentation']?.services['documentation']; | |
} | |
function getDocumentationVersion(ctx, strapi: Strapi) { | |
const requestUrl: string = ctx?.request?.url; | |
const paramVersion = requestUrl?.split('/')?.find(segment => /v\d+\.\d+\.\d+/g.test(segment))?.replace(/^v/, ''); | |
const docVersion = getDocumentationService(ctx, strapi)?.getDocumentationVersion() | |
return paramVersion || docVersion; | |
} | |
function getDocumentationPath(ctx, strapi: Strapi) { | |
return path.join(getDocumentationService(ctx, strapi)?.getFullDocumentationPath(), getDocumentationVersion(ctx, strapi), 'full_documentation.json') | |
} | |
export default (config, { strapi }: { strapi: Strapi }) => { | |
return async (ctx, next)=> { | |
const requestUrl: string = ctx?.request?.url; | |
const requestRegExp = /^\/documentation\/(v\d+\.\d+\.\d+\/)?(openapi\.yaml|openapi\.yml|swagger\.json)$/; | |
if (requestRegExp.test(requestUrl) && ctx.request.method === 'GET') { | |
const documentationService = getDocumentationService(ctx, strapi) | |
if (!documentationService) { | |
ctx.throw(500, 'Documentation service not found'); | |
} | |
try { | |
const documentationVersion = getDocumentationVersion(ctx, strapi); | |
const documentationPath = getDocumentationPath(ctx, strapi); | |
if (!fs.existsSync(documentationPath)) { | |
ctx.throw(404, `Documentation not found for version ${documentationVersion}`); | |
} | |
const jsonContent = fs.readFileSync(documentationPath, 'utf8'); | |
const jsonData = JSON.parse(jsonContent); | |
const isJson = requestUrl?.endsWith('.json'); | |
const isYaml = requestUrl?.endsWith('.yaml') || requestUrl?.endsWith('.yml'); | |
let body = jsonData; | |
if (isYaml) { | |
body = yaml.dump(jsonData); | |
} | |
if (isJson || isYaml) { | |
ctx.body = body; | |
} | |
} catch (e) { | |
ctx.throw(500, e); | |
} | |
} | |
await next(); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment