• Stars
    star
    164
  • Rank 230,032 (Top 5 %)
  • Language
    JavaScript
  • License
    Other
  • Created almost 8 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A library to convert Joi schema objects into Swagger schema definitions

joi-to-swagger

npm Node.js Testing Download Status

Conversion library for transforming Joi schema objects into Swagger OAS 3.0 schema definitions.

// input
joi.object().keys({
  id:      joi.number().integer().positive().required(),
  name:    joi.string(),
  email:   joi.string().email().required(),
  created: joi.date().allow(null),
  active:  joi.boolean().default(true),
})
// output
{
  "type": "object",
  "required": ["id", "email"],
  "properties": {
    "id": {
      "type": "integer",
      "minimum": 1
    },
    "name": {
      "type": "string"
    },
    "email": {
      "type": "string",
      "format": "email"
    },
    "created": {
      "type": "string",
      "nullable": true,
      "format": "date-time"
    },
    "active": {
      "type": "boolean"
    }
  },
  "additionalProperties": false
}

Usage

const j2s = require('joi-to-swagger');

const { swagger, components } = j2s(mySchema, existingComponents);

- in case of ES6 module syntax:

import j2s from 'joi-to-swagger';

const { swagger, components } = j2s(mySchema, existingComponents);

J2S takes two arguments, the first being the Joi object you wish to convert. The second optional argument is a collection of existing components to reference against for the meta className identifiers (see below).

J2S returns a result object containing swagger and components properties. swagger contains your new schema, components contains any components that were generated while parsing your schema.

Supported Conventions:

  • joi.object()

    • .unknown(false) -> additionalProperties: false
    • .required() on object members produces a "required": [] array
    • .pattern(pattern, JoiSchema) -> additionalProperties: [Schema]
  • joi.array().items() - in case of multiple provided schemas using items() method, the "oneOf" (OAS3) keyword is used

    • .min(4) -> "minItems": 4
    • .max(10) -> "maxItems": 10
    • .unique(truthy) -> "uniqueItems": true
  • joi.number() produces "type": "number" with a format of "float"

    • .precision() -> "format": "double"
    • .integer() -> "type": "integer"
    • .strict().only(1, 2, '3') -> "enum": [1, 2] (note that non-numbers are omitted due to swagger type constraints)
    • .allow(null) -> "nullable": true
    • .min(5) -> "minimum": 5 (joi.ref is supported and will fallback to 0 if not provided via refValues metadata)
    • .max(10) -> "maximum": 10 (joi.ref is supported and will fallback to 0 if not provided via refValues metadata)
    • .positive() -> "minimum": 1
    • .negative() -> "maximum": -1
    • .valid(1, 2) -> "enum": [1, 2]
    • .invalid(1, 2) -> "not": { "enum": [1, 2] }
  • joi.string() produces "type": "string" with no formatting

    • .strict().only('A', 'B', 1) -> "enum": ["A", "B"] (note that non-strings are omitted due to swagger type constraints)
    • .alphanum() -> "pattern": "/^[a-zA-Z0-9]*$/"
    • .alphanum().lowercase()
    • .alphanum().uppercase()
    • .token() -> "pattern": "/^[a-zA-Z0-9_]*$/"
    • .token().lowercase()
    • .token().uppercase()
    • .email() -> "format": "email"
    • .isoDate() -> "format": "date-time"
    • .regex(/foo/) -> "pattern": "/foo/"
    • .allow(null) -> "nullable": true
    • .min(5) -> "minLength": 5
    • .max(10) -> "maxLength": 10
    • .uuid() -> "format": "uuid"
    • .valid('A', 'B') -> "enum": ['A', 'B']
    • .invalid('A', 'B') -> "not": { "enum": ['A', 'B'] }
  • joi.binary() produces "type": "string" with a format of "binary".

    • .encoding('base64') -> "format": "byte"
    • .min(5) -> "minLength": 5
    • .max(10) -> "maxLength": 10
    • .allow(null) -> "nullable": true
  • joi.date() produces "type": "string" with a format of "date-time".

    • .allow(null) -> "nullable": true
  • joi.alternatives() - structure of alternative schemas is defined by "anyOf", "oneOf" or "allOf (OAS3) keywords

    • .mode('one') -> produces "oneOf": [ { ... } ]
    • in case of joi.required() alternative schema, the custom property option "x-required" is added to subschema -> "x-required": true
  • joi.when() conditions are transformed to "oneOf": [ { ... }, { ... } ] keyword

    • if multiple joi.when().when() conditions are provided, they are transformed to "anyOf": [ { ... }, { ... } ] keyword
    • in case of joi.required() condition, the custom property option "x-required" is added to subschema -> "x-required": true
  • any.default() sets the "default" detail.

  • any.example() sets the "example" or "examples".

    • .example('hi') -> "example": "hi"
    • .example('hi', 'hey') -> "examples": ["hi", "hey"]
  • joi.any()

  • .meta({ swaggerType: 'file' }).description('simpleFile') add a file to the swagger structure

  • .valid(1, 'A') -> "enum": [1, 'A']

  • .invalid(1, 'A') -> "not": { "enum": [1, 'A'] }

Meta Overrides

The following may be provided on a joi .meta() object to explicitly override default joi-to-schema behavior.

className: By default J2S will be full verbose in its components. If an object has a className string, J2S will look for an existing schema component with that name, and if a component does not exist then it will create one. Either way, it will produce a $ref element for that schema component. If a new component is created it will be returned with the swagger schema.

classTarget: Named components are assumed to be schemas, and are referenced as components/schemas/ComponentName. If a classTarget meta value is provided (such as parameters), this will replace schemas in the reference.

swagger: To explicitly define your own swagger component for a joi schema object, place that swagger object in the swagger meta tag. It will be mixed in to the schema that J2S produces.

swaggerOverride: If this meta tag is truthy, the swagger component will replace the result for that schema instead of mixing in to it.

swaggerType: Can be used with the .any() type to add files.

schemaOverride: A replacement Joi schema which is used to generate swagger. For example, AWS API Gateway supports a subset of the swagger spec. In order to utilize this library with AWS API Gateway's swagger, this option is useful when working with Joi.alternatives().

The example below uses joi.when, which would normally use oneOf, anyOf, or allOf keywords. In order to get around that, the meta tag overrides the schema to be similar, but less strict.

joi.object({
  type: joi.string().valid('a', 'b'),
  body: when('type', {
    is: 'a',
    then: joi.object({ a: joi.string() }),
    otherwise: when('type', {
      is: 'b',
      then: joi.object({ b: joi.string() }),
      otherwise: joi.forbidden()
    })
  })
}).meta({ schemaOverride: joi.object({ a: joi.string(), b: joi.string() })})

refValues: The possibility to give exact values when using joi.ref()

joi.object({
  durationFrom: joi.number().integer().min(5).max(10),
  durationTo: joi.number().integer().min(joi.ref('durationFrom')).max(20)
    .meta({ refValues: { durationFrom: 5 } }),
})

Custom Types (joi.extend)

For supporting custom joi types you can add the needed type information using a the meta property baseType.

const customJoi = joi.extend({
    type: 'customStringType',
    base: joi.string().meta({ baseType: 'string' }),
    // ...
});

More Repositories

1

InterviewThis

An open source list of developer questions to ask prospective employers
6,539
star
2

Kalendae

A javascript date picker that just works.
JavaScript
2,000
star
3

QueryizeJS

A no-frills chainable interface for constructing MySQL queries for node.js
JavaScript
56
star
4

quell

A no-frills active record implementation for node-mysql.
JavaScript
12
star
5

morgan-debug

An extension of the morgan express logger to output through the debug library.
JavaScript
11
star
6

ircdkit

A low-level framework for constructing IRC servers with NodeJS
JavaScript
8
star
7

Spiral

A bio-cycles tracker for all humans
JavaScript
8
star
8

HandlebarsHelperHoard

A portable collection of handlebars helper functions for use in node and the browser.
JavaScript
6
star
9

CurvyAndTrans.com

Site source for my fashion and transgender topics blog.
JavaScript
5
star
10

mysequel

A best-practices abstraction of node-mysql2
JavaScript
4
star
11

wellrested

A superagent wrapper library for creating preconfigured HTTP service clients
JavaScript
4
star
12

hooks

A collection of my frequently used react hooks
JavaScript
3
star
13

intro-to-backbone

An introduction to Backbone.js via annotated source code.
HTML
3
star
14

stubnet

A node.js library for creating fake TCP servers for automated tests.
JavaScript
3
star
15

nodeunit-dataprovider

Helper function for nodeunit to generate sets of tests using arrays of test data.
JavaScript
3
star
16

pitstopjs

DEPRECATED An express middleware for creating conditional groups of other middleware.
JavaScript
3
star
17

taut

Main repo for Taut IRC
JavaScript
2
star
18

react-utils

A collection of react hooks and components that I use in many of my rollup/react projects. No, it's not documented.
JavaScript
2
star
19

stepperbox

JavaScript testing library for creating stub functions with sequential behavior
JavaScript
2
star
20

ZeroTo255-Picker

Mac OS X color picker based on the shading algorithm used by 0to255.com. THIS IS A LEARNING PROJECT, THE CODE PROBABLY SUCKS
Objective-C
2
star
21

shellmirrorjs

A quick and dirty servlet to let other people see the results of a shell command.
JavaScript
1
star
22

PinVault

A key-value store with partial-object key matching
JavaScript
1
star
23

PinVaultObserver

An observer/mediator library that supports objects and arrays as event names for partial matching on dispatches.
JavaScript
1
star
24

node-long-emitter

A buffered EventEmitter with built in express middleware for long-polling.
JavaScript
1
star
25

WoW-AH-Vendorables

WoW Addon for scanning the auction house for items posted below vendor price
Lua
1
star
26

ircsock.js

Modular IRC client socket
JavaScript
1
star
27

js-utils

A collection of assorted JS utility functions in ES Module format for use in compiled library code
JavaScript
1
star