table-template.js 2.4 KB

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