Gathering detailed insights and metrics for koa-joi-swagger
Gathering detailed insights and metrics for koa-joi-swagger
Gathering detailed insights and metrics for koa-joi-swagger
Gathering detailed insights and metrics for koa-joi-swagger
npm install koa-joi-swagger
Typescript
Module System
Node Version
NPM Version
67.3
Supply Chain
95.1
Quality
71.8
Maintenance
25
Vulnerability
98.6
License
JavaScript (100%)
Total Downloads
29,048
Last Day
5
Last Week
36
Last Month
163
Last Year
2,949
75 Stars
18 Commits
11 Forks
7 Watching
1 Branches
1 Contributors
Minified
Minified + Gzipped
Latest Version
1.1.1
Package Id
koa-joi-swagger@1.1.1
Size
16.65 kB
NPM Version
5.0.0
Node Version
8.0.0
Cumulative downloads
Total Downloads
Last day
-28.6%
5
Compared to previous day
Last week
-47.1%
36
Compared to previous week
Last month
-3%
163
Compared to previous month
Last year
-33.3%
2,949
Compared to previous year
16
1
1npm i koa-joi-swagger 2
or
1yarn add koa-joi-swagger
for v3, install optional dependencies
1npm i swagger-ui-dist # or yarn add swagger-ui-dist
1git clone https://github.com/zaaack/koa-joi-swagger.git 2cd koa-joi-swagger 3yarn # or npm i 4SERVE=1 babel-node ./test/fixtures/server.js
Now open http://127.0.0.1:3456/swagger!
app.js
1import { toSwaggerDoc, ui, mixedValidate } from '../../src' 2import mixedDoc from './mixed-doc' 3import Koa from 'koa' 4import DecRouter from 'koa-dec-router' 5import bodyparser from 'koa-bodyparser' 6 7const app = new Koa() 8 9const decRouter = DecRouter({ 10 controllersDir: `${__dirname}/controllers`, 11}) 12 13app.use(bodyparser()) 14 15const swaggerDoc = toSwaggerDoc(mixedDoc) 16// mount swagger ui in `/swagger` 17app.use(ui(swaggerDoc, {pathRoot: '/swagger'})) 18 19// handle validation errors 20app.use(async (ctx, next) => { 21 try { 22 await next() 23 } catch (e) { 24 if (e.name === 'RequestValidationError') { 25 ctx.status = 400 26 ctx.body = { 27 code: 1, 28 message: e.message, 29 data: e.data, 30 } 31 } else if (e.name === 'ResponseValidationError') { 32 ctx.status = 500 33 ctx.body = { 34 code: 1, 35 message: e.message, 36 data: e.data, 37 } 38 } 39 } 40}) 41 42// validate request and response by mixedDoc 43app.use(mixedValidate(mixedDoc, { 44 onError: e => console.log(e.details, e._object), 45})) 46 47// koa-dec-router 48app.use(decRouter.router.routes()) 49app.use(decRouter.router.allowedMethods()) 50 51app.listen(3456)
"I see the api is simple, but how to write the joi schema and the swagger document?"
That's the point, you don't need to write a joi schema to validation and a swagger document to create API documents.
"Oh, no, Should I learn a new schema?"
Of cause not, I hate new schemas, too, especially those made by someone or some company without long support, it's just a waste of time and my brain cell.
Therefore, to make this library simple and reliable, I just mixed joi and swagger document, and using joi-to-json-schema to transform joi schema to swagger schema. You don't have to learn a new schema, just replace the JSON schema in your swagger document to joi schema, then let this library to do the rest.
I call it mixed document, here is an example.
1export default { 2 swagger: '2.0', 3 info: { 4 title: 'Test API', 5 description: 'Test API', 6 version: '1.0.0', 7 }, 8 // the domain of the service 9 // host: 127.0.0.1:3457 10 // array of all schemes that your API supports 11 schemes: ['https', 'http'], 12 // will be prefixed to all paths 13 basePath: '/api/v1', 14 consumes: ['application/x-www-form-urlencoded'], 15 produces: ['application/json'], 16 paths: { 17 '/posts': { 18 get: { 19 summary: 'Some posts', 20 tags: ['Post'], 21 parameters: { 22 query: Joi.object().keys({ 23 type: Joi.string().valid(['news', 'article']), 24 }), 25 }, 26 responses: { 27 '200': { 28 x: 'Post list', 29 schema: Joi.object().keys({ 30 lists: Joi.array().items(Joi.object().keys({ 31 title: Joi.string().description('Post title'), 32 content: Joi.string().required().description('Post content'), 33 })) 34 }), 35 }, 36 'default': { 37 description: 'Error happened', 38 schema: Joi.object().json().keys({ 39 code: Joi.number().integer(), 40 message: Joi.string(), 41 data: Joi.object(), 42 }), 43 }, 44 } 45 } 46 }, 47 }, 48}
You can see the differences between this and the real swagger document, just replace parameters
and responses
to joi schema instead of JSON schema,
Here is the swagger document that generate from mixed document above.
1import JoiSwagger, {
2 toSwaggerDoc, mixedValidate, joiValidate, ui
3} from 'koa-joi-swagger'
4import Koa from 'koa'
5
6const app = new Koa()
7/*
8
9JoiSwagger = {
10 toSwaggerDoc,
11 mixedValidate,
12 joiValidate,
13 ui,
14 Joi,
15}
16 */
17
18const mixedDoc = require('./mixed-doc')
19
20const swaggerDoc = toSwaggerDoc(mixedDoc) // parse mixed document to swagger document for swagger-ui
21
22
23//
24// const defaultResJoiOpts = {
25// stripUnknown: true,
26// convert: true,
27// }
28app.use(mixedValidate(mixedDoc, {
29 reqOpts: {
30 stripUnknown: false,
31 convert: true,
32 }, // optional, ctx.request joi validation options, here is default
33 resOpts: { // optional, ctx.response joi validation options, here is default
34 stripUnknown: true, // this would remove additional properties
35 convert: true, // this would convert field types
36 },
37 onError: err => console.error(err), // Do something with the error, the error would throw anyway.
38}))
39
40app.use(ui(swaggerDoc, {
41 pathRoot: '/swagger', // optional, swagger path
42 skipPaths: [], // optional, skip paths
43 UIHtml: defaultUIHtml, // optional, get ui html
44 swaggerConfig: '', // optional, a json5 string, e.g. `{ <field>: <value>, .... }` to display in html for overriding swagger ui options.
45 sendConfig: { maxage: 3600 * 1000 * 24 * 30 }, // optional, config for koa-send, default maxage is 1 month.
46 v3: false, // optional, default is v2, you need to install optional dependencies `swagger-ui-dist` first.
47
48}))
49
50// joiValidate // the internal joi validation function used by mixedValidate, in case you need one.
51// JoiSwagger.Joi // The joi used to validate, with some opinionated extension, you can override it or using it.
52
I have think it before, but hit some problems like validating javascript date object, remove additionalProperties, etc. And writing JSON schema is too verbose. Joi is the best validation library in NodeJS, we should take the advantage.
YAML is not easy to reuse, although JSON schema can reuse model, and how to reuse shared properties between models? I can't find a way. Pure javascrip can easily reuse or wrap model schema, and you can wrap each final schema with a function, don't feel pain when adding properties for each request schema in the future.
Sorry, joi's philosophy is too strict for me, I really don't need to explicit declare the string could be empty, so I override the original Joi.string()
to make Joi.string().empty('')
is a default behavior.
Also, add a .force()
method for string/number type, to coerce the field to string/number regardless of the original type, it's really useful when validating some bson type like Long, Deciaml or Custom object.
Added a Joi.object().json()
to coerce object with toJSON
method to a plain JSON object. This would useful when validation some ORM/ODM's model object (like mongorito).
And I highly recommend using this extended joi to write your schemas, and adding your extension if you need.
You can also using other version of Joi to validate.
1import JoiSwagger from 'koa-joi-swagger' 2import myJoi from './myJoi' 3 4// using 5export const Joi = JoiSwagger.Joi 6 7// override 8JoiSwagger.Joi = myJoi 9
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
Found 1/15 approved changesets -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2025-01-27
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More