@trojs/openapi-server
v2.1.1
Published
OpenAPI Server
Downloads
2,195
Readme
OpenAPI server
Create easy a webserver API first with a OpenAPI spec.
Installation
npm install @trojs/openapi-server
or
yarn add @trojs/openapi-server
Test the package
npm run test
or
yarn test
How to use
const controllers = {
// connect to a openationId in the OpenAPI spec with the same name
getTest: ({
context,
request,
response,
parameters,
specification,
url
}) => ({ //response an object
test: 'ok'
})
}
const { openAPISpecification, Api } = await openAPI({ file: './openapi-spec.json', base })
const api = new Api({
version: 'v1',
specification: openAPISpecification,
controllers,
logger: console,
ajvOptions: { allErrors: true }
})
const { app } = await setupServer({
env: process.env,
apis: [api]
})
If you create a controller, you can easy connect it to the operationId in the OpenAPI spec. Check also the examples in the test files. In your controller you can use e.g. context, request and response, from express. It isn neccesary to define it in your controller, if you don't use it, you can remove it. e.g.
getTest: ({ parameters }) =>
{
return {
test: 'ok'
}
}
parameters are query param's from the url of a get request, parsed by the type defined in the OpenAPI spec.
Specifications is the OpenAPI spec.
Url is the current url.
Add custom security handlers like JWT
import jwt from 'jsonwebtoken'
function jwtHandler(context, request, response) {
const authHeader = context.request.headers.authorization;
if (!authHeader) {
throw new Error('Missing authorization header');
}
const token = authHeader.replace('Bearer ', '');
return jwt.verify(token, 'secret');
}
const securityHandlers = [
{
name: 'jwt',
handler: jwtHandler
}
]
const api = new Api({
version: 'v1',
specification: openAPISpecification,
controllers,
securityHandlers
})
See also: https://openapistack.co/docs/openapi-backend/security-handlers/#security-handlers