ts-template.js 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. const _ = require('lodash');
  2. const getModelType = (type, interf = false) => {
  3. let modelType = 'string';
  4. if (type === 'Money' || type === 'money') {
  5. if (!interf) modelType = 'Decimal128';
  6. else modelType = 'number';
  7. } else if (type === 'ObjectId') modelType = 'ObjectId';
  8. else if (type === 'Array') modelType = 'Array<any>';
  9. else modelType = _.lowerFirst(type);
  10. return modelType;
  11. };
  12. const ModelContext = (data) => {
  13. const { name: table_name, columns } = data;
  14. const prefix = _.upperFirst(table_name);
  15. let fc = [];
  16. fc.push(`import { modelOptions, prop } from '@typegoose/typegoose';`);
  17. fc.push(`import { BaseModel } from 'free-midway-component';`);
  18. const has_money = columns.find((f) => f.type === 'Money' || f.type === 'money');
  19. if (has_money) fc.push(`import { Decimal128 } from 'mongoose';`);
  20. // 添加secret需要isString函数
  21. const has_secret = columns.find((f) => f.type === 'Secret' || f.type === 'secret');
  22. if (has_secret) fc.push(`import { isString } from 'lodash';`);
  23. fc.push(`@modelOptions({`);
  24. fc.push(` schemaOptions: { collection: '${table_name}' },`);
  25. fc.push(`})`);
  26. fc.push(`export class ${prefix} extends BaseModel {`);
  27. // 处理字段
  28. for (const col of columns) {
  29. const { type, title, def } = col;
  30. const prop = _.pick(col, ['required', 'index', 'zh', 'ref', 'remark']);
  31. if (def) prop.default = def;
  32. const modelType = getModelType(type);
  33. switch (modelType) {
  34. case 'secret':
  35. prop.select = false;
  36. fc.push(` // 手动删除set前的大括号,处理太麻烦了.就手动删除吧`);
  37. fc.push(` @prop(${JSON.stringify(prop)}, set: (val) => { if (isString(val)) { return { secret: val }; } return val; } })`);
  38. fc.push(` ${title}: object`);
  39. break;
  40. default:
  41. fc.push(` @prop(${JSON.stringify(prop)})`);
  42. fc.push(` ${title}: ${modelType}`);
  43. break;
  44. }
  45. }
  46. fc.push(`}`);
  47. // 最后换行转为字符串
  48. const fileContext = fc.join('\n');
  49. return fileContext;
  50. };
  51. const ServiceContext = (data) => {
  52. const fc = [];
  53. const { name: table_name, getPath } = data;
  54. const prefix = _.upperFirst(table_name);
  55. const entityPath = getPath('entity');
  56. fc.push(`import { Provide } from '@midwayjs/decorator';`);
  57. fc.push(`import { InjectEntityModel } from '@midwayjs/typegoose';`);
  58. fc.push(`import { ReturnModelType } from '@typegoose/typegoose';`);
  59. fc.push(`import { BaseService } from 'free-midway-component';`);
  60. fc.push(`import { ${prefix} } from '${entityPath}';`);
  61. fc.push(`type modelType = ReturnModelType<typeof ${prefix}>;`);
  62. fc.push(`@Provide()`);
  63. fc.push(`export class ${prefix}Service extends BaseService<modelType> {`);
  64. fc.push(` @InjectEntityModel(${prefix})`);
  65. fc.push(` model: modelType;`);
  66. fc.push(`}`);
  67. return fc.join('\n');
  68. };
  69. const ControllerContext = (data) => {
  70. const fc = [];
  71. const { name, name_zh, getPath } = data;
  72. const prefix = _.upperFirst(name);
  73. const servicePath = getPath('service');
  74. const interfacePath = getPath('interface');
  75. fc.push(`import { Body, Controller, Del, Get, Inject, Param, Post, Query } from '@midwayjs/decorator';`);
  76. fc.push(`import { BaseController } from 'free-midway-component';`);
  77. fc.push(`import { ${prefix}Service } from '${servicePath}';`);
  78. fc.push(`import { CDTO_${name}, CVO_${name}, FVO_${name},QDTO_${name}, QVO_${name}, UDTO_${name}, UVAO_${name} } from '${interfacePath}';`);
  79. fc.push(`import { ApiResponse, ApiTags, ApiQuery } from '@midwayjs/swagger';`);
  80. fc.push(`import { Validate } from '@midwayjs/validate';`);
  81. fc.push(`@ApiTags(['${name_zh}'])`);
  82. fc.push(`@Controller('/${name}')`);
  83. fc.push(`export class ${prefix}Controller extends BaseController {`);
  84. fc.push(` @Inject()`);
  85. fc.push(` service: ${prefix}Service;`);
  86. fc.push('\n');
  87. // create
  88. fc.push(`@Post('/') @Validate() @ApiResponse({ type: CVO_${name} })`);
  89. fc.push(` async create(@Body() data: CDTO_${name}) {`);
  90. fc.push(` const dbData = await this.service.create(data);`);
  91. fc.push(` const result = new CVO_${name}(dbData);`);
  92. fc.push(` return result;`);
  93. fc.push(` }`);
  94. // query
  95. fc.push(`@Get('/')@ApiQuery({name:'query'})@ApiResponse({ type: QVO_${name} })`);
  96. fc.push(` async query(@Query() filter:QDTO_${name}, @Query('skip') skip: number,@Query('limit') limit: number){`);
  97. fc.push(` const list = await this.service.query(filter, { skip, limit });`);
  98. fc.push(` const data = [];`);
  99. fc.push(` for (const i of list) {`);
  100. fc.push(` const newData = new QVO_${name}(i);`);
  101. fc.push(` data.push(newData);`);
  102. fc.push(` }`);
  103. fc.push(` const total = await this.service.count(filter);`);
  104. fc.push(` return { data, total };`);
  105. fc.push(` }`);
  106. fc.push(`\n`);
  107. // fetch
  108. fc.push(`@Get('/:id')@ApiResponse({ type: FVO_${name} })`);
  109. fc.push(` async fetch(@Param('id') id: string) {`);
  110. fc.push(` const data = await this.service.fetch(id);`);
  111. fc.push(` const result = new FVO_${name}(data);`);
  112. fc.push(` return result;`);
  113. fc.push(` }`);
  114. fc.push(`\n`);
  115. // update
  116. fc.push(`@Post('/:id')@Validate()@ApiResponse({ type: UVAO_${name} })`);
  117. fc.push(` async update(@Param('id') id: string, @Body() body: UDTO_${name}) {`);
  118. fc.push(` const result = await this.service.updateOne(id, body);`);
  119. fc.push(` return result;`);
  120. fc.push(` }`);
  121. fc.push(`\n`);
  122. // delete
  123. fc.push(`@Del('/:id')@Validate()`);
  124. fc.push(` async delete(@Param('id') id: string) {`);
  125. fc.push(` await this.service.delete(id);`);
  126. fc.push(` return 'ok';`);
  127. fc.push(` }`);
  128. // other bat deal
  129. fc.push(` async createMany(...args: any[]) {`);
  130. fc.push(` throw new Error('Method not implemented.');`);
  131. fc.push(` }`);
  132. fc.push(`\n`);
  133. fc.push(` async updateMany(...args: any[]) {`);
  134. fc.push(` throw new Error('Method not implemented.');`);
  135. fc.push(` }`);
  136. fc.push(`\n`);
  137. fc.push(` async deleteMany(...args: any[]) {`);
  138. fc.push(` throw new Error('Method not implemented.');`);
  139. fc.push(` }`);
  140. fc.push(`}`);
  141. fc.push(`\n`);
  142. return fc.join(`\n`);
  143. };
  144. /**
  145. *
  146. * @param {Object} col 字段
  147. * @param {boolean} needReq 是否启用必须,针对post设置
  148. * @returns
  149. */
  150. const getInterfaceColumn = (col, needReq = false) => {
  151. const fc = [];
  152. const { type, zh, title, required } = col;
  153. const modelType = getModelType(type, true);
  154. fc.push(` @ApiProperty({ description: '${zh}' })`);
  155. if (needReq) {
  156. let ruleStr = '';
  157. let rt = '';
  158. if (type === 'Money' || type === 'money') rt = 'number';
  159. else rt = _.lowerFirst(type);
  160. if (required) ruleStr = `@Rule(RuleType['${rt}']().required().error(new ServiceError('缺少${zh}',FrameworkErrorEnum.${needReq ? 'NEED_BODY' : 'NEED_QUERY'})))`;
  161. else ruleStr = `@Rule(RuleType['${rt}']().empty(''))`;
  162. fc.push(ruleStr);
  163. }
  164. fc.push(` '${title}': ${modelType} = undefined;`);
  165. return fc;
  166. };
  167. const InterfaceContext = (data) => {
  168. const fc = [];
  169. const { columns = [], name } = data;
  170. const have_required = columns.find((f) => f.required);
  171. fc.push(`import { Rule, RuleType } from '@midwayjs/validate';`);
  172. fc.push(`import { ApiProperty } from '@midwayjs/swagger';`);
  173. if (have_required) fc.push(`import { FrameworkErrorEnum, SearchBase, ServiceError } from 'free-midway-component';`);
  174. else fc.push(`import { SearchBase } from 'free-midway-component';`);
  175. fc.push(`import get = require('lodash/get');`);
  176. fc.push(`const dealVO = (cla, data) => {`);
  177. fc.push(` for (const key in cla) {`);
  178. fc.push(` const val = get(data, key);`);
  179. fc.push(` if (val || val === 0) cla[key] = val;`);
  180. fc.push(` }`);
  181. fc.push(`};`);
  182. fc.push(`export class FVO_${name} {`);
  183. fc.push(` constructor(data: object) {`);
  184. fc.push(` dealVO(this, data);`);
  185. fc.push(` }`);
  186. fc.push(` @ApiProperty({ description: '数据id' })`);
  187. fc.push(` _id: string = undefined;`);
  188. for (const col of columns) {
  189. const cfc = getInterfaceColumn(col);
  190. fc.push(...cfc);
  191. }
  192. fc.push(`}`);
  193. fc.push(`\n`);
  194. const indexs = columns.filter((f) => f.index);
  195. const props = indexs.map((i) => `'${i.title}'`).join(', ');
  196. fc.push(`export class QDTO_${name} extends SearchBase {`);
  197. fc.push(` constructor() {`);
  198. fc.push(` const like_prop = [];`);
  199. fc.push(` const props = [${props}];`);
  200. fc.push(` const mapping = [];`);
  201. fc.push(` super({ like_prop, props, mapping });`);
  202. fc.push(` }`);
  203. for (const col of indexs) {
  204. const cfc = getInterfaceColumn(col);
  205. fc.push(...cfc);
  206. }
  207. fc.push(`}`);
  208. fc.push(`\n`);
  209. fc.push(`export class QVO_${name} extends FVO_${name} {`);
  210. fc.push(` constructor(data: object) {`);
  211. fc.push(` super(data);`);
  212. fc.push(` dealVO(this, data);`);
  213. fc.push(` }`);
  214. fc.push(`}`);
  215. fc.push(`\n`);
  216. fc.push(`export class CDTO_${name} {`);
  217. for (const col of columns) {
  218. const cfc = getInterfaceColumn(col, true);
  219. fc.push(...cfc);
  220. }
  221. fc.push(`}`);
  222. fc.push(`\n`);
  223. fc.push(`export class CVO_${name} extends FVO_${name} {`);
  224. fc.push(` constructor(data: object) {`);
  225. fc.push(` super(data);`);
  226. fc.push(` dealVO(this, data);`);
  227. fc.push(` }`);
  228. fc.push(`}`);
  229. fc.push(`\n`);
  230. fc.push(`export class UDTO_${name} extends CDTO_${name} {
  231. @ApiProperty({ description: '数据id' })
  232. @Rule(RuleType['string']().empty(''))
  233. _id: string = undefined;
  234. }`);
  235. fc.push(`\n`);
  236. fc.push(`export class UVAO_${name} extends FVO_${name} {`);
  237. fc.push(` constructor(data: object) {`);
  238. fc.push(` super(data);`);
  239. fc.push(` dealVO(this, data);`);
  240. fc.push(` }`);
  241. fc.push(`}`);
  242. return fc.join('\n');
  243. };
  244. module.exports = (data) => {
  245. // let result = `\n========== Model ==========\n`;
  246. // result += ModelContext(data);
  247. // result += `\n========== Service ==========\n`;
  248. // result += ServiceContext(data);
  249. // result += `\n========== Controller ==========\n`;
  250. // result += ControllerContext(data);
  251. // result += `\n========== interface ==========\n`;
  252. // result += InterfaceContext(data);
  253. const result = {};
  254. result.m = ModelContext(data);
  255. result.s = ServiceContext(data);
  256. result.c = ControllerContext(data);
  257. result.i = InterfaceContext(data);
  258. result.n = data.name;
  259. return result;
  260. };