Search code examples
node.jssails.js

Allow object of objects within inputs in action


I'm wondering how I have objects of objects as inputs in an action - for example,

module.exports = {

  friendlyName: 'Signup',

  description: 'Signup a user for an account.',

  inputs: {
    bride: {
        firstName: {
            description: 'The first name of the bride',
            type: 'string',
            required: true
        }
    },
    groom: {
        lastName: {
            description: 'The first name of the groom',
            type: 'string',
            required: true
        }
    }
  }

  exits: {},

  fn: async function (inputs, exits) {
      sails.log.debug(inputs.bride.firstName); // I would like to be able to reference input like this
      return exits.success();
  }
};

How can I do this and access inputs.bride.firstName (instead of having to do inputs.brideFirstName)?

I receive the following error trying to do this:

'Invalid input definition ("bride").  Must have `type`, or at least some more information.  (If you aren\'t sure what to use, just go with `type: \'ref\'.)' ] } }

Solution

  • Another way is to implement a custom validation with objects of objects

    module.exports = {
    
      friendlyName: 'Signup',
    
      description: 'Signup a user for an account.',
    
      inputs: {
        bride: {
          description: 'The first name of the bride',
          type: 'json', // {'firstName': 'luis'}
          custom: function(value) {
            return _.isObject(value) && _.isString(value.firstName)
          }
        },
        groom: {
          description: 'The first name of the groom',
          type: 'json', // {'lastname': 'lazy'}
          custom: function(value) {
            return _.isObject(value) && _.isString(value.lastName)
          }
        }
      }
    
      exits: {},
    
      fn: async function (inputs, exits) {
          sails.log.debug(inputs.bride.firstName); // luis
          return exits.success();
      }
    };
    

    More information on: https://sailsjs.com/documentation/concepts/models-and-orm/validations#?custom-validation-rules