JKHeadley / rest-hapi

🚀 A RESTful API generator for Node.js

Home Page:https://resthapi.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Extended SchemaType syntax produces incorrect Joi validation

davad opened this issue · comments

Describe the bug

Setting a schema field to Mixed type using a SchemaType object creates invalid Joi configuration

To Reproduce

Example schema:

module.exports = mongoose => {
    const modelName = "test";
    const Types = mongoose.Schema.Types;

    const Schema = new mongoose.Schema({
        name: Types.String,
        mixed: Types.Mixed,
        altMixed: {
            type: Types.Mixed,
        },
    });

    Schema.statics = {
        collectionName: modelName,
        routeOptions: {},
    };
    return Schema;
};

Creating a document fails unless altMixed is an object

Document with altMixed set to a string

% curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '[{"name":"Foo", "mixed":"a string", "altMixed": "another string" }]' http://localhost:8080/test | jq

{
  "statusCode": 400,
  "error": "Bad Request",
  "message": "\"value\" at position 0 fails because [child \"altMixed\" fails because [\"altMixed\" must be an object]], \"testCreateModel\" must be an object",
  "validation": {
    "source": "payload",
    "keys": [
      "0.altMixed",
      ""
    ]
  }
}

Document with altMixed set to an empty object

% curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '[{"name":"Bar", "mixed":"a string", "altMixed": {} }]' http://localhost:8080/test | jq

[
  {
    "_id": "5c780c64dd0ded492f5069f0",
    "isDeleted": false,
    "name": "Bar",
    "mixed": "a string",
    "createdAt": "2019-02-28T16:29:24.346Z"
  }
]

Expected behavior

Joi validation should be the same regardless of how a type is defined.

Desktop (please complete the following information):

  • OS: macOS
  • Browser cURL

Additional context

I tested this with an altString: { type: Types.String } property and didn't have any issues. I also used the mixed/altMixed schema in the REPL to create a document and didn't have any issues.