GithubHelp home page GithubHelp logo

joi-to-swagger's Introduction

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' }),
    // ...
});

joi-to-swagger's People

Contributors

blugavere avatar cjnqt avatar david-unergie avatar dependabot[bot] avatar greenkeeper[bot] avatar h2non avatar jimcatts avatar jkenv avatar lucasconstantino avatar mairu avatar melchii avatar mmed avatar pato1 avatar qwang1113 avatar siilwyn avatar snyk-bot avatar twipped avatar vikaskanani avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

joi-to-swagger's Issues

regeneratorRuntime - error

Hi I'm receiving this error. Is a bug, can you help me?

C:\Users\54116\Desktop\Proyectos\node_swagger\express_joi_swagger\node_modules\j2s\dist\index.js:6
var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee(ctx, instances, funcs) {
^

ReferenceError: regeneratorRuntime is not defined
at C:\Users\54116\Desktop\Proyectos\node_swagger\express_joi_swagger\node_modules\j2s\dist\inde
x.js:6:34
at Object. (C:\Users\54116\Desktop\Proyectos\node_swagger\express_joi_swagger\node_m
odules\j2s\dist\index.js:48:2)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object. (C:\Users\54116\Desktop\Proyectos\node_swagger\express_joi_swagger\node_m
odules\j2s\index.js:1:18)


Running this code:
const joi = require('@hapi/joi');
const j2s = require('j2s');

const mySchema = 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),
});

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

console.log(swagger,components);


NODEJS VERSION: v10.16.3

Package.json:
{
"name": "express_joi_swagger",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"@hapi/joi": "^17.1.1",
"j2s": "^2.0.6"
}
}

[Feature request] Support Joi.link()

Please add functionality of Joi.link()
This would allow schemas to be recursive

Usage example: i have schema like this

const nestedThingValidator = Joi.object({
    type: Joi.string().required().valid(FIELD_TYPE.NESTED),
    format: Joi.string()
      .valid(FIELD_TYPE.BOOL, FIELD_TYPE.RADIOBUTTON, FIELD_TYPE.DROPDOWN)
      .required(),
    options: Joi.array()
      .items(
        Joi.object({
          value: Joi.string().required(),
          code: propertyCodeValidator,
          fieldset: Joi.array()
            .items(Joi.ref("#nestedOne"))
            .min(1),
        })
      )
      .required()
      .min(1),
  })
  .id("nestedOne");

Which allows object to be recursively nested

P.S. Here are a message i have with my schema when i try to convert it with this library
image

[FEATURE] Support for schema.tailor and schema.alter

In Joi, you can create subtle variants of a schema using alter and tailor. This is not reflected in the joi-to-swagger conversion.

For example,

const MySchema = Joi.object({
  property1: Joi.string(),
  property2: Joi.string().alter({
    special: schema => schema.strip()
  })
})

const SpecialSchema = MySchema.tailor('special')

still produces

"SpecialSchema": {
  "type": "object",
  "properties": {
    "property1": {
      "type": "string"
    },
    "property2": {
      "type": "string"
    }
  }
}

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! ๐ŸŽŠ

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml
  • The new Node.js version is in-range for the engines in 1 of your package.json files, so that was left alone

If youโ€™re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didnโ€™t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didnโ€™t touch job or matrix configurations because these tend to be quite specific and complex, and itโ€™s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what youโ€™re doing it may require additional work or may not be applicable at all. Weโ€™re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, Iโ€™m a humble robot and wonโ€™t feel rejected ๐Ÿค–


FAQ and help

There is a collection of frequently asked questions. If those donโ€™t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot ๐ŸŒด

TypeError: any is not a recognized Joi type

Hey there, neat project!

I wanted to try this out but I ran into a snag trying to run it against a simple Joi schema. Am I doing something wrong?

var j2s = require('joi-to-swagger'); // latest, 1.2.0
const Joi = require('joi'); // latest, v13.0.2
const schema = Joi.object().keys({
  id: Joi.any().forbidden(), 
  key: Joi.string()
});

j2s(schema); // boom!
TypeError: any is not a recognized Joi type.
    at parse (/Users/Mark/test/node_modules/joi-to-swagger/index.js:37:9)
    at children.forEach (/Users/Mark/test/node_modules/joi-to-swagger/index.js:292:15)
    at Array.forEach (<anonymous>)
    at Object.object (/Users/Mark/test/node_modules/joi-to-swagger/index.js:290:12)
    at parse (/Users/Mark/test/node_modules/joi-to-swagger/index.js:35:38)
    at repl:1:1
    at ContextifyScript.Script.runInThisContext (vm.js:50:33)
    at REPLServer.defaultEval (repl.js:240:29)
    at bound (domain.js:301:14)
    at REPLServer.runBound [as eval] (domain.js:314:12)

thank you for this

Just swung by to say thanks.

I'm using this in a project and have found it very useful. So thanks, again.

Invalid definition references with OAS3

References for definitions returned by joi-to-swagger are incompatible with v3 OpenAPI Spec.

In OAS3 all reusable Components are under common namespace components. Also, definitions were renamed to schemas.

So the correct Reference generated by joi-to-swagger should be #/components/schemas/* instead of #/definitions/*.

Affected function: refDef

Generation of components using .pattern()

Hi,

I'm using as a value of a key a pattern with a schema object.

I would expect that a component is created for the schema referenced in the additional parameters.

const innerSchema = Joi.object().keys({
    key: Joi.any(),
  }).meta({ className: 'innerSchema' });
  id: Joi.object().pattern(
    /^/,
    innerSchema,
  ),
}).meta({ className: 'patternSchema' });

const componentsPatternSchema = j2s(patternSchema as Schema).components;
componentsPatternSchema is

{
  "schemas": {
    "patternSchema": {
      "type": "object",
      "properties": {
        "id": {
          "type": "object",
          "properties": {},
          "additionalProperties": {
            "$ref": "#/components/schemas/innerSchema"
          }
        }
      },
      "additionalProperties": false
    }
  }
}

but no component was created for what is referenced in the additonalProperties.

Using a schema as a value for a key of a schema will create the component as expected

const noPatternSchema = Joi.object().keys({ id: innerSchema }).meta({ className: 'noPatternSchema' });
  const componentsNoPatternSchema = j2s(noPatternSchema as Schema).components;

componentsNoPatternSchema is

  "schemas": {
    "innerSchema": {
      "type": "object",
      "properties": {
        "key": {}
      },
      "additionalProperties": false
    },
    "noPatternSchema": {
      "type": "object",
      "properties": {
        "id": {
          "$ref": "#/components/schemas/innerSchema"
        }
      },
      "additionalProperties": false
    }
  }
}

Is this an issue or another approach is required in order to get the expected output?

Thank you for any insight provided!

joi-to-swagger version 6.1.0

How to manage Joi.extend?

Hi,

we defined some joi extensions in our application, and we don't know if it's possible to manage that with j2s or not? Via meta or something else.
Currently, we get the error TypeError: ourExtension is not a recognized Joi type

const joi = require('joi')
const joi2swagger = require('joi-to-swagger')
const ourJoi = joi.extend([
    {
        base: joi.string(),
        name: 'ourExtension',
        coerce(value, state, options) {
            return value + 'ourExtension'
        },
    },
])

joi2swagger({
    test: ourJoi.ourExtension()
})
// => TypeError: ourExtension is not a recognized Joi type

We would like to say to j2s "ourExtension" is like "string", but we don't know how to do.
Is there a way?
Thanks

False default values for boolean not passing

@Mairu please copy this code, this is fix to allow to pass false boolean in defaultValue.

Code changes:
const defaultValue = get(schema, '_flags.default');
if ((defaultValue || typeof defaultValue === 'boolean') && typeof defaultValue !== 'function') {
swagger.default = defaultValue;
}

test code:
simpleTest(
'boolean',
joi.boolean().default(false),
{
default: false,
type: 'boolean',
},
);

tried to open a PR, but was not possible.

Error when a property has a forbidden flag

Hi. I have a Joi schema which has forbidden flag for one of its property. I get this error:
"Cannot create property 'description' on boolean 'false'"
when trying to convert it to a swagger object.

line 44 of index.js (3.0.0):
swagger = parseAsType[schema._type](schema, existingComponents, components);
sets the swagger object to false instead of returning.
Code afterwards treats it like an object and it fails because it is boolean type.

add meta option to override alternatives feature (for AWS APIG)

I recently upgraded from joi-to-swagger@3 to joi-to-swagger@5. I love having the new features, but unfortunately the old alternatives behavior breaks the swagger integration with AWS API Gateway. I was thinking about adding a meta override flag to use the old behavior if present.

Happy to implement this myself.

Description feature

Hello!
I've come across your lib and it has been great so far.
I was wondering if it is possible to add one feature though.
Joi has a description feature which would come in handy to specify some fields on Swagger.

Could this be implemented or are you accepting pull requests?

Convert Joi label to Swagger title

Hello! I am currently setting the Swagger title value from my Joi using the .meta function like:

.meta({swagger: {title: 'Name'}})

I would rather be able to use the Joi label function like:

.label('Name')

and have it automatically mapped to the title in Swagger. If the new feature is acceptable, I have a PR ready to submit.

Love the project! Thank you!!
Jim

joi.object().keys() vs joi.object({})

Hello this is example from doc:

// 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),
})

But Im trying to transform this format generated from https://github.com/TehShrike/joi-sql

// input
joi.object({
  id:      joi.number().integer().positive().required(),
  name:    joi.string(),
  email:   joi.string().email().required(),
  created: joi.date().allow(null),
  active:  joi.boolean().default(true),
})

it throws an error that it doesnt recognize schema format.

Swagger OpenAPI 3.0 now supports alternatives

Currently joi.alternatives() only selects the first item for the swagger doc.
However OpenAPI now supports multiple inputs, so joi-to-swagger could get rid of that limitation. What do you think? Start supporting OpenAPI 3.0?

Support for .allow('a','b') by setting enums for this

From JOI:- Note that this list of allowed values is in addition to any other permitted values. To create an exclusive list of values, see any.valid(value).
This code is being used to check if flags only is set to true and then only it sets the enums but in case of allow being used for a set of allowed values _flags.only is not set so enums are not displayed.
if ( get(schema, '_flags.only') && valids.length) { swagger.enum = valids; }

Generate parameters array

Hi, I have this joi object:
Joi.object({ userGuid: Joi.string().uuid().required(), version: Joi.string() .regex(/^\d+(.\d+){3}$/) .required(), os: Joi.string() .valid('IOS', 'ANDROID', 'CHROMEOS', 'WINDOWS', 'MACOS') .required(), endUserId: Joi.string().required(), machineId: Joi.string().required(), }).meta({ className: 'postVersionInfo' })

and I generates this schema:
"postVersionInfo": { "type": "object", "properties": { "userGuid": { "type": "string", "format": "uuid" }, "version": { "type": "string", "pattern": "^\\d+(.\\d+){3}$" }, "os": { "type": "string", "enum": [ "IOS", "ANDROID", "CHROMEOS", "WINDOWS", "MACOS" ] }, "endUserId": { "type": "string" }, "machineId": { "type": "string" } }, "required": [ "userGuid", "version", "os", "endUserId", "machineId" ], "additionalProperties": false }

But in order to use in properly in swagger and to get info about each parameter, I need a joi-to-swagger to generate an array of parameters, like in this example: https://petstore.swagger.io/#/pet/uploadFile, where the parameters schema looks like:
[ { "name": "petId", "in": "path", "description": "ID of pet to update", "required": true, "type": "integer", "format": "int64" }, { "name": "additionalMetadata", "in": "formData", "description": "Additional data to pass to server", "required": false, "type": "string" }, { "name": "file", "in": "formData", "description": "file to upload", "required": false, "type": "file" } ]

How can I achieve this?
Thanks!

More examples

Hi, I'm looking for more examples to use this module. Could you add some complete example of how to integrate this module with a swagger file or with some apirest with expressjs?

Generated swagger is improperly including conditionally required properties

I'm using the .when function to make certain fields required only when other fields have a specific value. In my use case, I use the same swagger for CREATEing an object as I do for UPDATEing it, but the 'id' property is only required on UPDATE... so I use the sys_version (which is a DB timestamp field) to be able to tell. Thus I have a Joi property that looks like:

id: Joi.string().description('The unique, string identifier of this invoice').when('sys_version', {is: Joi.number().greater(0).required(), then: Joi.required())

The problem is, the Swagger that is generated is including the 'id' as a required property as if I had written the schema with a Joi.required().

This is undesirably behavior - I'd like the Joi schema to not include conditionally required properties as required in the Swagger output.

Thanks!
Andrew

How to create joi schema of allOf: swagger syntax

How to create JOI schema of following swagger example
Can anybody provide a proper example to solve the below example

"/a/demo/list": {
   "post": {
     "summary": "demo List",
     "operationId": "demo",
     "description": "demo List",
     "produces": [
       "application/json"
     ],
     "consumes": [
       "application/json"
     ],
     "parameters": [
       {
         "name": "body",
         "description": "Fetch demo list",
         "in": "body",
         "schema": {
           "allOf": [
             {
               "$ref": "#/components/schemas/pagination"
             },
             {
               "$ref": "#/components/schemas/sort"
             }
           ]
         }
       }
     ],
     "responses": {
       "200": {
         "description": "successful operation"
       }
     }
   }
 }
"components": {
   "schemas": {
     "pagination": {
       "type": "object",
       "properties": {
         "perPageRecords": {
           "type": "integer"
         },
         "pageNo": {
           "type": "integer"
         }
       },
       "additionalProperties": false
     },
     "sort": {
       "title": "sort",
       "properties": {
         "sorts": {
           "type": "array",
           "items": {
             "type": "object",
             "properties": {
               "fieldName": {
                 "type": "string"
               },
               "direction": {
                 "type": "string"
               }
             }
           }
         }
       }
     }
   }
 }

Does this library work with Joi date extensions?

I'm trying to use Joi date extensions and am getting a weird validation error:

Error: {
  "format" [1]: -- missing --
}

[1] "format" is required

ValidationError: {\n  \u001b[41m\"format\"\u001b[0m\u001b[31m [1]: -- missing --\u001b[0m\n}\n\u001b[31m\n[1] \"format\" is required\u001b[0m\n    at Object.exports.process (D:\\rhythm\\rolodex-contacts\\node_modules\\joi\\lib\\errors.js:196:19)\n

How do I make this work?

Thanks!
Andrew

Usage of joi.ref() in min()/max() generated invalid schemas

Originally reported through PR #98


Commonly this library ignores Joi.ref() what is fine, but in this case it generates invalid .json which can't be compiled

Joi implementation example

Joi.object({
  durationFrom: Joi.number().integer().min(0).max(999).optional().allow(null).example(10),
  durationTo: Joi.number().integer().min(Joi.ref('/body.durationFrom')).max(999).optional().allow(null).example(10)
})

will generate

{
  "durationFrom": {
    "type": "integer",
    "minimum": 0,
    "maximum": 999,
    "nullable": true,
    "example": 10
  },
  "durationTo": {
    "type": "integer",
    "minimum": {
      "adjust": null,
      "in": false,
      "iterables": null,
      "map": null,
      "separator": ".",
      "type": "value",
      "ancestor": "root",
      "path": [
        "body",
        "durationFrom"
      ],
      "depth": 2,
      "key": "body.durationFrom",
      "root": "body",
      "display": "ref:root:body.durationFrom"
    },
    "maximum": 999,
    "nullable": true,
    "example": 10
  }
}

String allow null conversion

Is conversion joi.string().allow(null) to"type": ["string", "null"] a valid value for swagger type? Because swagger UI (at least swagger-ui-express) does not seem to understand it. Instead, it writes "Unknown Type: string,null".

Although didn't find any mention of multiple types in swagger 2.0 spec, all used examples show just a single type value.

And in swagger 3.0 spec it's explicitely said that:

type takes a single value. type as a list is not valid in OpenAPI (even though it is valid in JSON Schema):

Meta options (className, swagger and swaggerOverride)

Hello!
I have few questions/issues with meta options:

  1. Meta option swagger can't be used with className, since it returns before override:
    return { swagger: refDef(metaDefType, metaDefName), components };

    Object.assign(swagger, override);

    E.g.:
const schema = Joi.string().meta({
  className: 'Email',
  swagger: {
    format: 'email'
  }
});
const { components } = j2s(schema)

Expecting:

components // => { Email: { type: 'string', format: 'email' } }

Got:

components // => { Email: { type: 'string' } }
  1. swaggerOverride can't be used with className, since it returns no components in this case:
    if (override && flattenMeta.swaggerOverride) {

Perhaps it was made intentionally, but maybe this info should be added to Readme?

Versions:

  • joi-to-swagger: 4.0.0

Feature: Include examples with any.example()

This is a feature request. =)

Joi offers to define some examples for any value.
Swagger allows kind of the same thing.

It would be nice to be able to define examples directly in Joi and have them show up in the generated swagger defintion.

Joi.when with schema test is not implemented

Hello, I try to convert this Joi Schema to swagger but I have an error.

This is my schema :

Joi.when(Joi.object({ isCustom : true }).unknown(), {
    then        : Joi.object().keys(advancedAlert),
    otherwise   : Joi.object().keys(simpleAlert),
});

This is the error returned :

Error: No schema was passed.
    at parse (project/node_modules/joi-to-swagger/index.js:19:21)
    at Object.alternatives (project/node_modules/joi-to-swagger/index.js:242:15)
    at parse (project/node_modules/joi-to-swagger/index.js:49:38)
    at children.forEach (project/node_modules/joi-to-swagger/index.js:296:15)
    at Array.forEach (<anonymous>)
    at Object.object (project/node_modules/joi-to-swagger/index.js:294:12)
    at parse (project/node_modules/joi-to-swagger/index.js:49:38)

Regular expression pattern should not include open/close slashes

In JSON Schema version 4+, regular expression patterns should not include open/close slashes.

Apparently, the behavior was consistent in legacy versions, but it's now failing with widely used implementations, such as jsonschema v1.2+, which claims to be JSONSchema v4 compliant.

According to the JSON Schema specification, pattern string values should be ECMAScript regular expression compliant:
http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.3.3

But considering that open/close slashes are only required for regular expression literals within ECMAScript syntax, not as part of the regular expression value, we can safely remove them:
http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5

I will provide a PR for the fix.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.