krakenjs / swaggerize-routes

Swagger document driven route builder.
Other
58 stars 57 forks source link

Allow null values on parameters #66

Open pmeinhardt opened 8 years ago

pmeinhardt commented 8 years ago

Hi there,

How would you go about allowing parameters to be set to null?

For instance, for an API that I am working on at the moment, I would like to be able to update (PATCH) resources and reset certain attributes by sending null. E.g. to reset the user image a client would send:

PATCH /users/129482194

{
  "image_id": null
}

The swagger.json currently contains something like the following:

{
  "/users/{id}": {
    "patch": {
      "parameters": {
        "name": "body",
        "in": "body",
        "type": "object",
        "properties": {
          "image_id": {
            "type": "string",
            "format": "uuid"
          }
        }
      }
    }
  }
}

Proposal

I looked into the Swagger specification but could not find a way of allowing both string/uuid values and null for a parameter. I have seen people propose an "x-isnullable" extension and it looks like a valid option.

The route definition would then look like this:

{
  "/users/{id}": {
    "patch": {
      "parameters": {
        "name": "body",
        "in": "body",
        "type": "object",
        "properties": {
          "image_id": {
            "type": "string",
            "format": "uuid",
            "x-isnullable": true  // <<= added extension allows parameter to be a uuid or null
          }
        }
      }
    }
  }
}

Findings & Obstacles

However I am not sure how you'd implement this in swaggerize-routes.

Reading the source, I found that the parameter objects from the Swagger document are passed to enjoi, which then uses joi to create a schema for validation.

I found out that joi allows whitelisting specific values. Here's an example schema that allows string values and null:

var assert = require('assert');
var joi = require('joi');

var schema = joi.string().allow(null);

schema.validate('abc', function (err, value) {
  assert(err === null);
});

schema.validate(null, function (err, value) {
  assert(err === null);
});

However enjoi – focussed on JSON Schema (doesn't seem to cover this case?) – only supports a subset of the joi schema definitions, so I do not see an easy way to add an "x-isnullable" Swagger extension which can be implemented on top of enjoi (especially for nested attributes in a request body).

Any ideas on how you would tackle this?

Thanks. Cheers, Paul

rlataguerra commented 7 years ago

+1 @pmeinhardt did you find a workaround ?

pmeinhardt commented 7 years ago

@stickyhands: In this case, the property in question was a UUID and we decided to introduce a special one - "00000000-0000-0000-0000-000000000000" - to indicate that the reference should be nulled. Our code then treated this particular UUID like null.