javascriptnode.jsapisails.js

When using Actions2 in sails.js how do i validate the body object?


very new to sails.js

I get that the inputs object allows actions2 to validate the request parameters. However how do you access/validate the request body. e.g. req.body. i know i can access this from this.req.body, but with actions2 i wondered if there was a way of accessing/validating it through inputs or something else built in just like the query parameters.

Really simple action below to illustrate the point.

module.exports = {
  friendlyName: 'Create',

  description: 'Create summaries.',

  inputs: {},

  exits: {},

  fn: async function (inputs, exits) {
    // All done.
    return this.res.created(this.req.body)
  },
}

the body would contain:

{
    "Summary": [
        {
            "DUPLICATE_MANIFESTED": 0,
            "DUPLICATE_SEEN": 4,
        },
        {
            "DUPLICATE_MANIFESTED": 0,
            "DUPLICATE_SEEN": 1,

        }
    ]
}

Thanks!


Solution

  • OK. So i've realised as serious newbie that it does work. But i also found out that the standard validations in the Inputs does't work in the same way for nested objects and arrays.

    So essentially you use the keys in the object you are sending and so can use 'Summary' right off the bat.

    The part I mentioned about the validations. I may be wrong but as you can see i found that sails under the hood uses rttc for type checking, so every element underneath the first cannot have any properties like 'description' or 'type', but instead just has to have the type as the value straigh away. I have investigated any further nesting though.

    I've also found there isn't an easy way of having missing elements when type checking the nesting properties, so essentially they are then all required or you can set them i think as '*' which essentially bypasses the type check. I do need to do more homework on this as i'm not 100% sure but thought it might help anyone that comes accross this.

    Below is how i have the below as an answer.

    module.exports = {
      friendlyName: 'Create',
    
      description: 'Create summaries.',
    
      inputs: {
        Summary: {
          description: 'The current incoming request (req).',
          type: [
            {
              DUPLICATE_MANIFESTED: 'number',
              DUPLICATE_SEEN: 'number',
            }
          ]
        }
      },
    
      exits: {},
    
      fn: async function (inputs, exits) {
        // All done.
        return this.res.created(inputs.Summary)
      },
    }
    

    Hope this helps anyone who's a newb like me!