table-template.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. 'use strict';
  2. const _ = require('lodash');
  3. module.exports = data => {
  4. const { name, name_zh, columns } = data;
  5. let columnStr = `const ${name} = { \n`;
  6. let indexStr = '';
  7. let has_ObjectId = false;
  8. let has_Secret = false;
  9. for (let i = 0; i < columns.length; i++) {
  10. const { title, type, required = false, remark, index } = columns[i];
  11. const str = ` ${title}: { type: ${type || 'String'}, required: ${required} ${type === 'Secret' ? ', select: false' : ''} }, // ${remark || ''} \n`;
  12. columnStr += str;
  13. if (index) indexStr += `schema.index({ '${title}': 1 });\n`;
  14. if (!has_ObjectId && type === 'ObjectId') has_ObjectId = true;
  15. else if (!has_Secret && type === 'Secret') has_Secret = true;
  16. }
  17. columnStr += '}';
  18. const nameList = name.split('_');
  19. const modelName = nameList.map(i => _.capitalize(i)).join('_');
  20. return `'use strict';
  21. const Schema = require('mongoose').Schema;
  22. const metaPlugin = require('naf-framework-mongoose-free/lib/model/meta-plugin');
  23. ${has_ObjectId ? "const { ObjectId } = require('mongoose').Types;" : ''}
  24. ${has_Secret ? "const { Secret } = require('naf-framework-mongoose-free/lib/model/schema');" : ''}
  25. // ${name_zh || ''}
  26. ${columnStr}
  27. const schema = new Schema(${name}, { toJSON: { virtuals: true } });
  28. schema.index({ id: 1 });
  29. schema.index({ 'meta.createdAt': 1 });
  30. ${indexStr}
  31. schema.plugin(metaPlugin);
  32. module.exports = app => {
  33. const { mongoose } = app;
  34. return mongoose.model('${modelName}', schema, ${name});
  35. };
  36. `;
  37. };