Validations for associative models sailsJs

纵然是瞬间 提交于 2019-12-12 04:54:53

问题


I am trying to build a REST API on sailsjs v0.11.0, I am looking for a way to validate all POST requests. Validation works for simple models.

Simple model example: category.js

module.exports = {
    attributes: {
        name: {
            type: 'string',
            required: true,    // this works, the POST data is validated, if this field is missing, sails responds with an error json
            unique: true
        }
    }
}

Associative one to many model example where validation doesnt work:

Chapter.js

module.exports = {

    attributes: {
        name: 'string',
        categoryId: 'integer',
        pages: {
            type: 'string',
            required: true     // Sails saves the record to DB even if this field is missing.
        },
        owner: {
            model: 'Upload'
        }
    }

};

Upload.js

module.exports = {

    attributes: {
        draftId: 'integer',
        chapters: {
            collection: 'Chapter',
            via: 'owner'
        }
    }
};

EDIT:

I got it to work with the following updated Chapter.js model, but if the associated model fails validation, the sails server responds with a 500 status and a error json as shown below, While this is not an error, It should have sent a 400 status.

Updated Chapter.js:

module.exports = {
    attributes: {
        name: {
            type: 'string',
            required: true
        },
        categoryId: {
            type: 'integer',
            required: true
        },
        pages: {
            type: 'string',
            required: true
        },
        owner: {
            model: 'Upload'
        }
    }
};

The Error with 500 status:

{
  "error": "E_UNKNOWN",
  "status": 500,
  "summary": "Encountered an unexpected error",
  "raw": [
    {
      "type": "insert",
      "collection": "chapter",
      "values": {
        "name": "chapeterOne",
        "pages": "2,3,4,5",
        "owner": 12
      },
      "err": {
        "error": "E_VALIDATION",
        "status": 400,
        "summary": "1 attribute is invalid",
        "model": "Chapter",
        "invalidAttributes": {
          "categoryId": [
            {
              "rule": "integer",
              "message": "`undefined` should be a integer (instead of \"null\", which is a object)"
            },
            {
              "rule": "required",
              "message": "\"required\" validation rule failed for input: null"
            }
          ]
        }
      }
    }
  ]
}

Is there a way to make the error message more sensible?

来源:https://stackoverflow.com/questions/29202056/validations-for-associative-models-sailsjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!