table-template.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. const configArr = [];
  10. let configSearchStr = '';
  11. for (let i = 0; i < columns.length; i++) {
  12. const { title, type, required = false, remark, index } = columns[i];
  13. const str = ` ${title}: { type: ${type || 'String'}, required: ${required} ${type === 'Secret' ? ', select: false' : ''} }, // ${remark || ''} \n`;
  14. columnStr += str;
  15. configArr.push(`'${required ? '!' : ''}${title}'`);
  16. if (index) {
  17. indexStr += `schema.index({ '${title}': 1 });\n`;
  18. configSearchStr += `'${title}': '${title}' ,\n`;
  19. }
  20. if (!has_ObjectId && type === 'ObjectId') has_ObjectId = true;
  21. else if (!has_Secret && type === 'Secret') has_Secret = true;
  22. }
  23. columnStr += '}';
  24. const nameList = name.split('_');
  25. const modelName = nameList.map(i => _.capitalize(i)).join('_');
  26. return `'use strict';
  27. const Schema = require('mongoose').Schema;
  28. const metaPlugin = require('naf-framework-mongoose-free/lib/model/meta-plugin');
  29. ${has_ObjectId ? "const { ObjectId } = require('mongoose').Types;" : ''}
  30. ${has_Secret ? "const { Secret } = require('naf-framework-mongoose-free/lib/model/schema');" : ''}
  31. // ${name_zh || ''}
  32. ${columnStr}
  33. const schema = new Schema(${name}, { toJSON: { virtuals: true } });
  34. schema.index({ id: 1 });
  35. schema.index({ 'meta.createdAt': 1 });
  36. ${indexStr}
  37. schema.plugin(metaPlugin);
  38. module.exports = app => {
  39. const { mongoose } = app;
  40. return mongoose.model('${modelName}', schema, ${name});
  41. };
  42. module.exports = {
  43. create: {
  44. requestBody: [${configArr.join(',')}],
  45. },
  46. destroy: {
  47. params: ["!id"],
  48. service: "delete",
  49. },
  50. update: {
  51. params: ["!id"],
  52. requestBody: [${configArr.join(',')}],
  53. },
  54. show: {
  55. parameters: {
  56. params: ["!id"],
  57. },
  58. service: "fetch",
  59. },
  60. index: {
  61. parameters: {
  62. query: {
  63. "meta.createdAt@start": "meta.createdAt@start",
  64. "meta.createdAt@end": "meta.createdAt@end",
  65. ${configSearchStr}
  66. },
  67. // options: {
  68. // "meta.state": 0 // 默认条件
  69. // },
  70. },
  71. service: "query",
  72. options: {
  73. query: ["skip", "limit"],
  74. sort: ["meta.createdAt"],
  75. desc: true,
  76. count: true,
  77. },
  78. },
  79. };
  80. `;
  81. };