简体   繁体   中英

Export SailsJS model schema as JSON

The goal is to take model schema and export it somewhere as JSON, take that json and make a dynamic form in Angular.

Basically main problem which I see here is to get model, and generate output which will be important for generating reactive form in Angular.

For example:

module.exports = {
  attributes: {
    nameOnMenu: { type: 'string', required: true },
    price: { type: 'string', required: true },
    percentRealMeat: { type: 'number' },
    numCalories: { type: 'number' },
  },
};

So final output would look like:

[
  { nameOnMenu: { type: 'string', required: true }},
  { price: { type: 'string', required: true }},
  { percentRealMeat: { type: 'number',  required: false }},
  { numCalories: { type: 'number', required: false }},
]

Based on this output, i will go through all and generate form.

I'm not sure that I really understand the question that you are asking here but let me take a bash at trying to provide an answer.

I can think of two ways that you could achieve it:

1.) Use server rendered local data to include the desired result for use on the front end.

2.) Make an API request from the front end for the desired result.

In your resulting controller/action you can get the model attributes in various ways. I can think of one:

const { resolve } = require('path');
// Portable relative path based on code being in
// config/bootstrap.js file so adjust as required
const modelDefinition = require(resolve(__dirname, '..', 'api', 'models', 'NameOfModel.js')).attributes;
console.log(modelDefinition);
{ name:
  { type: 'string',
    required: true,
    validations: { isNotEmptyString: true },
    autoMigrations:
     { columnType: 'varchar(255)',
       unique: false,
       autoIncrement: false } },
  ...etc,
}

For completeness, you would need to factor in a few things regarding the model settings and model attributes in order to get an accurate output, for instance, whether or not the table includes an updatedAt field.

Ultimately, you can marshal this data as you see fit with vanilla Javascript/Node in order to obtain your desired result but I will leave that to you.

As another user has pointed out, I'm also not sure that you will find an officially supported solution for completely reactive data using Angular and Sails, I assume that this will require a bit of engineering in order for your to create something that is suitable for your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM