ng-alain 12.2.3 → 12.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/application/files/i18n/el-GR.json +1 -1
  2. package/application/files/i18n/en-US.json +1 -1
  3. package/application/files/i18n/es-ES.json +1 -1
  4. package/application/files/i18n/fr-FR.json +1 -1
  5. package/application/files/i18n/hr-HR.json +1 -1
  6. package/application/files/i18n/it-IT.json +151 -0
  7. package/application/files/i18n/ko-KR.json +1 -1
  8. package/application/files/i18n/pl-PL.json +1 -1
  9. package/application/files/i18n/sl-SI.json +1 -1
  10. package/application/files/i18n/tr-TR.json +1 -1
  11. package/application/files/i18n/zh-CN.json +10 -6
  12. package/application/files/i18n/zh-TW.json +1 -1
  13. package/application/files/root/proxy.conf.js +17 -0
  14. package/application/files/src/app/app.component.ts +21 -5
  15. package/application/files/src/app/core/i18n/i18n.service.spec.ts +6 -0
  16. package/application/files/src/app/core/i18n/i18n.service.ts +3 -5
  17. package/application/files/src/app/core/net/default.interceptor.ts +4 -3
  18. package/application/files/src/app/core/startup/startup.service.ts +5 -3
  19. package/application/files/src/app/layout/basic/basic.component.ts +1 -1
  20. package/application/files/src/app/routes/exception/exception-routing.module.ts +4 -6
  21. package/application/files/src/app/routes/exception/exception.component.ts +16 -0
  22. package/application/files/src/app/routes/exception/exception.module.ts +2 -6
  23. package/application/files/src/assets/tmp/i18n/el-GR.json +1 -1
  24. package/application/files/src/assets/tmp/i18n/en-US.json +1 -1
  25. package/application/files/src/assets/tmp/i18n/es-ES.json +1 -1
  26. package/application/files/src/assets/tmp/i18n/fr-FR.json +1 -1
  27. package/application/files/src/assets/tmp/i18n/hr-HR.json +1 -1
  28. package/application/files/src/assets/tmp/i18n/it-IT.json +151 -0
  29. package/application/files/src/assets/tmp/i18n/ko-KR.json +1 -1
  30. package/application/files/src/assets/tmp/i18n/pl-PL.json +1 -1
  31. package/application/files/src/assets/tmp/i18n/sl-SI.json +1 -1
  32. package/application/files/src/assets/tmp/i18n/tr-TR.json +1 -1
  33. package/application/files/src/assets/tmp/i18n/zh-CN.json +10 -6
  34. package/application/files/src/assets/tmp/i18n/zh-TW.json +1 -1
  35. package/application/index.js +2 -2
  36. package/application/index.js.map +1 -1
  37. package/application/index.spec.ts +2 -1
  38. package/application/index.ts +2 -2
  39. package/application/schema.json +1 -1
  40. package/collection.json +5 -0
  41. package/core/lang.config.js +2 -1
  42. package/core/lang.config.js.map +1 -1
  43. package/core/lang.config.ts +2 -1
  44. package/curd/schema.json +39 -27
  45. package/curd/schema.ts +5 -1
  46. package/docs/generate.en-US.md +35 -0
  47. package/docs/generate.zh-CN.md +35 -0
  48. package/docs/plugin.en-US.md +1 -0
  49. package/docs/plugin.zh-CN.md +1 -0
  50. package/docs/sta.en-US.md +55 -0
  51. package/docs/sta.zh-CN.md +55 -0
  52. package/edit/schema.json +7 -7
  53. package/edit/schema.ts +5 -1
  54. package/empty/index.spec.ts +25 -14
  55. package/empty/schema.json +7 -7
  56. package/empty/schema.ts +5 -1
  57. package/list/schema.json +7 -7
  58. package/list/schema.ts +5 -1
  59. package/module/index.js +2 -4
  60. package/module/index.js.map +1 -1
  61. package/module/index.ts +4 -5
  62. package/module/schema.json +1 -1
  63. package/ng-add/schema.json +1 -1
  64. package/ng-update/upgrade-rules/checks/_src-to-nz-image-rule.js.map +1 -1
  65. package/ng-update/upgrade-rules/checks/_src-to-nz-image-rule.ts +1 -1
  66. package/ng-update/upgrade-rules/v12/index.spec.ts +2 -2
  67. package/ng-update/upgrade-rules/v12/schema.json +1 -1
  68. package/package.json +4 -1
  69. package/plugin/plugin.icon.js.map +1 -1
  70. package/plugin/plugin.icon.ts +1 -1
  71. package/plugin/plugin.network-env.js +8 -8
  72. package/plugin/plugin.network-env.js.map +1 -1
  73. package/plugin/plugin.network-env.spec.ts +2 -2
  74. package/plugin/plugin.network-env.ts +8 -8
  75. package/plugin/schema.json +1 -1
  76. package/schema.json +19 -0
  77. package/sta/index.js +208 -0
  78. package/sta/index.js.map +1 -0
  79. package/sta/index.spec.ts +57 -0
  80. package/sta/index.ts +242 -0
  81. package/sta/schema.js +3 -0
  82. package/sta/schema.js.map +1 -0
  83. package/sta/schema.json +52 -0
  84. package/sta/schema.ts +39 -0
  85. package/sta/templates/base.service.eta +46 -0
  86. package/sta/templates/dto-type.eta +12 -0
  87. package/sta/templates/dto.eta +17 -0
  88. package/sta/templates/procedure-call.eta +68 -0
  89. package/sta/templates/route-docs.eta +30 -0
  90. package/sta/templates/service.eta +44 -0
  91. package/sta/types.js +3 -0
  92. package/sta/types.js.map +1 -0
  93. package/sta/types.ts +28 -0
  94. package/tpl/schema.json +8 -8
  95. package/tpl/schema.ts +5 -1
  96. package/utils/alain.js +13 -8
  97. package/utils/alain.js.map +1 -1
  98. package/utils/alain.spec.ts +25 -3
  99. package/utils/alain.ts +22 -8
  100. package/utils/html.js.map +1 -1
  101. package/utils/html.ts +2 -2
  102. package/utils/json.js.map +1 -1
  103. package/utils/json.ts +1 -1
  104. package/utils/lib-versions.js +1 -1
  105. package/utils/lib-versions.ts +1 -1
  106. package/utils/testing.js +4 -1
  107. package/utils/testing.js.map +1 -1
  108. package/utils/testing.ts +8 -1
  109. package/utils/workspace.js +12 -2
  110. package/utils/workspace.js.map +1 -1
  111. package/utils/workspace.ts +20 -2
  112. package/view/schema.json +2 -7
  113. package/application/files/root/proxy.conf.json +0 -2
  114. package/application/files/src/app/routes/exception/403.component.ts +0 -7
  115. package/application/files/src/app/routes/exception/404.component.ts +0 -7
  116. package/application/files/src/app/routes/exception/500.component.ts +0 -7
package/schema.json CHANGED
@@ -12,6 +12,15 @@
12
12
  },
13
13
  "colorLess": {
14
14
  "$ref": "#/definitions/colorLess"
15
+ },
16
+ "projects": {
17
+ "type": "object",
18
+ "patternProperties": {
19
+ "^(?:@[a-zA-Z0-9_-]+/)?[a-zA-Z0-9_-]+$": {
20
+ "$ref": "#/definitions/project"
21
+ }
22
+ },
23
+ "additionalProperties": false
15
24
  }
16
25
  },
17
26
  "definitions": {
@@ -132,6 +141,16 @@
132
141
  "default": "./src/assets/color.less"
133
142
  }
134
143
  }
144
+ },
145
+ "project": {
146
+ "type": "object",
147
+ "properties": {
148
+ "routesRoot": {
149
+ "type": "string",
150
+ "description": "The root of the routes files structure. (default: app/routes)",
151
+ "default": "app/routes"
152
+ }
153
+ }
135
154
  }
136
155
  }
137
156
  }
package/sta/index.js ADDED
@@ -0,0 +1,208 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ /* eslint-disable @typescript-eslint/no-explicit-any */
13
+ const color_1 = require("@angular/cli/utilities/color");
14
+ const core_1 = require("@angular-devkit/core");
15
+ const schematics_1 = require("@angular-devkit/schematics");
16
+ const fs_1 = require("fs");
17
+ const jsonc_parser_1 = require("jsonc-parser");
18
+ const path_1 = require("path");
19
+ const swagger_typescript_api_1 = require("swagger-typescript-api");
20
+ const json_1 = require("../utils/json");
21
+ const workspace_1 = require("../utils/workspace");
22
+ let project;
23
+ const filePrefix = `/* eslint-disable */
24
+ /*
25
+ * Automatically generated by 'ng g ng-alain:sta'
26
+ * @see https://ng-alain.com/cli/sta
27
+ *
28
+ * Inspired by: https://github.com/acacode/swagger-typescript-api
29
+ */
30
+
31
+ `;
32
+ function addPathInTsConfig(name) {
33
+ return (tree) => {
34
+ const json = json_1.readJSON(tree, 'tsconfig.json', 'compilerOptions');
35
+ if (json == null)
36
+ return tree;
37
+ if (!json.compilerOptions)
38
+ json.compilerOptions = {};
39
+ if (!json.compilerOptions.paths)
40
+ json.compilerOptions.paths = {};
41
+ const paths = json.compilerOptions.paths;
42
+ paths[`@${name}`] = [`src/app/_${name}/index`];
43
+ paths[`@${name}/*`] = [`src/app/_${name}/*`];
44
+ json_1.writeJSON(tree, 'tsconfig.json', json);
45
+ return tree;
46
+ };
47
+ }
48
+ function cleanOutput(p) {
49
+ try {
50
+ fs_1.rmdirSync(p, { recursive: true });
51
+ fs_1.mkdirSync(p);
52
+ }
53
+ catch (e) { }
54
+ }
55
+ function fix(output, res, tree, context) {
56
+ const indexList = [`models`, `_base.service`];
57
+ const basePath = core_1.normalize(path_1.join(project.root, output.replace(process.cwd(), '')));
58
+ try {
59
+ // definitions
60
+ const dataTpl = res.getTemplate({ name: 'dataContracts', fileName: 'data-contracts.eta' });
61
+ const dataContent = res.renderTemplate(dataTpl, Object.assign({}, res.configuration));
62
+ tree.create(`${basePath}/models.ts`, filePrefix + res.formatTSContent(dataContent));
63
+ // Base Service
64
+ const baseServiceTpl = res.getTemplate({ name: 'baseService', fileName: 'base.service.eta' });
65
+ const baseServiceContent = res.renderTemplate(baseServiceTpl, Object.assign({}, res.configuration));
66
+ tree.create(`${basePath}/_base.service.ts`, filePrefix + res.formatTSContent(baseServiceContent));
67
+ // Tag Service
68
+ const dtoTypeTpl = res.getTemplate({ name: 'dto-type', fileName: 'dto-type.eta' });
69
+ const serviceTpl = res.getTemplate({ name: 'service', fileName: 'service.eta' });
70
+ res.configuration.routes.combined.forEach(route => {
71
+ const routeIndex = [];
72
+ // dto
73
+ const dtoContent = res.formatTSContent(res.renderTemplate(dtoTypeTpl, Object.assign(Object.assign({}, res.configuration), { route })));
74
+ if (dtoContent.trim().length > 10) {
75
+ tree.create(`${basePath}/${route.moduleName}/dtos.ts`, filePrefix + dtoContent);
76
+ routeIndex.push(`dtos`);
77
+ }
78
+ // service
79
+ const serviceContent = res.renderTemplate(serviceTpl, Object.assign(Object.assign({}, res.configuration), { route }));
80
+ tree.create(`${basePath}/${route.moduleName}/service.ts`, filePrefix + res.formatTSContent(serviceContent));
81
+ routeIndex.push(`service`);
82
+ // index.ts
83
+ tree.create(`${basePath}/${route.moduleName}/index.ts`, filePrefix + routeIndex.map(name => `export * from './${name}';`).join('\n'));
84
+ indexList.push(`${route.moduleName}/index`);
85
+ });
86
+ // Index
87
+ tree.create(`${basePath}/index.ts`, filePrefix + indexList.map(name => `export * from './${name}';`).join('\n'));
88
+ }
89
+ catch (ex) {
90
+ throw new schematics_1.SchematicsException(`Parse error: ${ex}`);
91
+ }
92
+ }
93
+ function genProxy(config) {
94
+ return (tree, context) => {
95
+ var _a;
96
+ context.logger.info(color_1.colors.blue(`- Name: ${config.name}`));
97
+ const output = (config.output = path_1.resolve(process.cwd(), (_a = config.output) !== null && _a !== void 0 ? _a : `./src/app/_${config.name}`));
98
+ const templates = path_1.resolve(__dirname, './templates');
99
+ if (config.url) {
100
+ context.logger.info(color_1.colors.blue(`- Using url data: ${config.url}`));
101
+ }
102
+ else if (config.filePath) {
103
+ context.logger.info(color_1.colors.blue(`- Using file data: ${config.filePath}`));
104
+ }
105
+ context.logger.info(color_1.colors.blue(`- Output: ${output}`));
106
+ return new Promise(resolve => {
107
+ context.logger.info(color_1.colors.blue(`Start generating...`));
108
+ const options = Object.assign({ name: `${config.name}.ts`, url: config.url, input: config.filePath, spec: config.spec, output,
109
+ templates, toJS: false, modular: true, cleanOutput: true, generateUnionEnums: true, generateClient: true, extractRequestParams: false, generateResponses: false, generateRouteTypes: true, generateApi: true, silent: true, disableStrictSSL: true, moduleNameFirstTag: true, defaultResponseType: 'any', typePrefix: config.modelTypePrefix, hooks: {
110
+ onInit: (c) => {
111
+ c.httpClientType = config.httpClientType;
112
+ return c;
113
+ },
114
+ onPrepareConfig: c => {
115
+ var _a;
116
+ if (!config.responseDataField)
117
+ return c;
118
+ const getDeepDataType = (ref) => {
119
+ var _a, _b;
120
+ let typeData = (_a = c.utils.getComponentByRef(ref)) === null || _a === void 0 ? void 0 : _a.typeData;
121
+ while (typeData != null && Array.isArray(typeData.allOf) && typeData.allOf.length > 0) {
122
+ typeData = (_b = c.utils.getComponentByRef(typeData.allOf[0].$ref)) === null || _b === void 0 ? void 0 : _b.typeData;
123
+ }
124
+ return typeData;
125
+ };
126
+ (_a = c.routes.combined) === null || _a === void 0 ? void 0 : _a.forEach(moduleInfo => {
127
+ moduleInfo.routes.forEach((routeInfo) => {
128
+ var _a, _b, _c;
129
+ if (!routeInfo.responseBodySchema)
130
+ return;
131
+ try {
132
+ const responseBodyContentFirstType = Object.keys((_a = routeInfo.responseBodySchema) === null || _a === void 0 ? void 0 : _a.content).pop();
133
+ if (!responseBodyContentFirstType)
134
+ return;
135
+ const ref = routeInfo.responseBodySchema.content[responseBodyContentFirstType].schema.$ref;
136
+ const resDataType = getDeepDataType(ref);
137
+ if (!resDataType)
138
+ return;
139
+ const fieldProperty = (_b = resDataType.properties) === null || _b === void 0 ? void 0 : _b[config.responseDataField];
140
+ if (!fieldProperty)
141
+ return;
142
+ routeInfo.response.type = (_c = fieldProperty.$parsed.content) !== null && _c !== void 0 ? _c : 'any';
143
+ }
144
+ catch (ex) {
145
+ throw new schematics_1.SchematicsException(`Parse data field error: ${ex}`);
146
+ }
147
+ });
148
+ });
149
+ return c;
150
+ },
151
+ onFormatTypeName: formattedModelName => {
152
+ if (!config.modelTypePrefix)
153
+ return formattedModelName;
154
+ if (formattedModelName.startsWith(config.modelTypePrefix + config.modelTypePrefix)) {
155
+ return formattedModelName.substring(config.modelTypePrefix.length);
156
+ }
157
+ return formattedModelName;
158
+ }
159
+ } }, config.generateApiOptions);
160
+ swagger_typescript_api_1.generateApi(options)
161
+ .then((res) => {
162
+ cleanOutput(output);
163
+ fix(output, res, tree, context);
164
+ resolve();
165
+ })
166
+ .catch(ex => {
167
+ throw new schematics_1.SchematicsException(`Generate error: ${ex}`);
168
+ });
169
+ });
170
+ };
171
+ }
172
+ function finished() {
173
+ return (_, context) => {
174
+ context.logger.info(color_1.colors.green(`✓ Finished, refer to: https://ng-alain.com/cli/sta`));
175
+ };
176
+ }
177
+ function tryLoadConfig(context, configPath) {
178
+ if (!configPath || configPath.length <= 0)
179
+ return null;
180
+ try {
181
+ const configFile = path_1.resolve(process.cwd(), configPath);
182
+ context.logger.info(color_1.colors.blue(`- Use config file: ${configFile}`));
183
+ if (fs_1.existsSync(configFile)) {
184
+ return jsonc_parser_1.parse(fs_1.readFileSync(configFile).toString('utf8'));
185
+ }
186
+ }
187
+ catch (err) {
188
+ throw new schematics_1.SchematicsException(`Invalid config file ${err}`);
189
+ }
190
+ }
191
+ function default_1(options) {
192
+ return (tree, context) => __awaiter(this, void 0, void 0, function* () {
193
+ context.logger.info(color_1.colors.yellow(`The ng g ng-alain:sta is currently in testing status and may change before the major version of '13'`));
194
+ project = (yield workspace_1.getProject(tree, options.project)).project;
195
+ const config = Object.assign(Object.assign({ name: 'sta' }, options), tryLoadConfig(context, options.config));
196
+ if (typeof config.generateApiOptions === 'string') {
197
+ try {
198
+ config.generateApiOptions = JSON.parse(config.generateApiOptions);
199
+ }
200
+ catch (ex) {
201
+ throw new schematics_1.SchematicsException(`Parse generateApiParams error: '${config.generateApiOptions}' => ${ex}`);
202
+ }
203
+ }
204
+ return schematics_1.chain([addPathInTsConfig(config.name), genProxy(config), finished()]);
205
+ });
206
+ }
207
+ exports.default = default_1;
208
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../schematics/sta/index.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,uDAAuD;AACvD,wDAAsD;AAEtD,+CAAiD;AAEjD,2DAAsG;AACtG,2BAAoE;AACpE,+CAAqC;AACrC,+BAAqC;AACrC,mEAA2F;AAE3F,wCAAoD;AACpD,kDAAgD;AAIhD,IAAI,OAA0B,CAAC;AAE/B,MAAM,UAAU,GAAG;;;;;;;;CAQlB,CAAC;AAE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G,CAAC,MAAM,sBAAU,CAAC,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC;QAC5D,MAAM,MAAM,iCACV,IAAI,EAAE,KAAK,IACR,OAAO,GACP,aAAa,CAAC,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,CAC1C,CAAC;QACF,IAAI,OAAO,MAAM,CAAC,kBAAkB,KAAK,QAAQ,EAAE;YACjD,IAAI;gBACF,MAAM,CAAC,kBAAkB,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,kBAAkB,CAAC,CAAC;aACnE;YAAC,OAAO,EAAE,EAAE;gBACX,MAAM,IAAI,gCAAmB,CAAC,mCAAmC,MAAM,CAAC,kBAAkB,QAAQ,EAAE,EAAE,CAAC,CAAC;aACzG;SACF;QAED,OAAO,kBAAK,CAAC,CAAC,iBAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC;IAC/E,CAAC,CAAA,CAAC;AACJ,CAAC;AAxBD,4BAwBC"}
@@ -0,0 +1,57 @@
1
+ import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing';
2
+
3
+ import { createAlainAndModuleApp } from '../utils/testing';
4
+
5
+ export const SPEC = {
6
+ openapi: '3.0.1',
7
+ info: {
8
+ title: 'Title',
9
+ version: '1.0.0'
10
+ },
11
+ tags: [
12
+ {
13
+ name: 'user'
14
+ }
15
+ ],
16
+ paths: {
17
+ '/user': {
18
+ get: {
19
+ summary: 'Info',
20
+ tags: ['user'],
21
+ responses: {
22
+ '200': {
23
+ description: 'Success',
24
+ content: {
25
+ 'application/json': {
26
+ schema: {
27
+ type: 'object',
28
+ properties: {}
29
+ }
30
+ }
31
+ }
32
+ }
33
+ }
34
+ }
35
+ }
36
+ }
37
+ };
38
+
39
+ describe('Schematic: sta', () => {
40
+ let runner: SchematicTestRunner;
41
+ let tree: UnitTestTree;
42
+
43
+ async function run(): Promise<void> {
44
+ tree = await runner.runSchematicAsync('sta', { spec: SPEC }, tree).toPromise();
45
+ }
46
+
47
+ beforeEach(async () => ({ runner, tree } = await createAlainAndModuleApp()));
48
+
49
+ it('should be working', async () => {
50
+ await run();
51
+ [`_base.service.ts`, `models.ts`, `index.ts`].forEach(name => {
52
+ expect(tree.exists(`/projects/foo/src/app/_sta/${name}`)).toBe(true);
53
+ });
54
+ const tsConfig = tree.readContent(`tsconfig.json`);
55
+ expect(tsConfig).toContain(`@sta`);
56
+ });
57
+ });
package/sta/index.ts ADDED
@@ -0,0 +1,242 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ import { colors } from '@angular/cli/utilities/color';
3
+
4
+ import { normalize } from '@angular-devkit/core';
5
+ import { ProjectDefinition } from '@angular-devkit/core/src/workspace';
6
+ import { Rule, SchematicsException, Tree, chain, SchematicContext } from '@angular-devkit/schematics';
7
+ import { rmdirSync, mkdirSync, existsSync, readFileSync } from 'fs';
8
+ import { parse } from 'jsonc-parser';
9
+ import { resolve, join } from 'path';
10
+ import { generateApi, GenerateApiOutput, GenerateApiParams } from 'swagger-typescript-api';
11
+
12
+ import { readJSON, writeJSON } from '../utils/json';
13
+ import { getProject } from '../utils/workspace';
14
+ import { Schema } from './schema';
15
+ import { STAConfig } from './types';
16
+
17
+ let project: ProjectDefinition;
18
+
19
+ const filePrefix = `/* eslint-disable */
20
+ /*
21
+ * Automatically generated by 'ng g ng-alain:sta'
22
+ * @see https://ng-alain.com/cli/sta
23
+ *
24
+ * Inspired by: https://github.com/acacode/swagger-typescript-api
25
+ */
26
+
27
+ `;
28
+
29
+ function addPathInTsConfig(name: string): Rule {
30
+ return (tree: Tree) => {
31
+ const json = readJSON(tree, 'tsconfig.json', 'compilerOptions');
32
+ if (json == null) return tree;
33
+ if (!json.compilerOptions) json.compilerOptions = {};
34
+ if (!json.compilerOptions.paths) json.compilerOptions.paths = {};
35
+ const paths = json.compilerOptions.paths;
36
+ paths[`@${name}`] = [`src/app/_${name}/index`];
37
+ paths[`@${name}/*`] = [`src/app/_${name}/*`];
38
+ writeJSON(tree, 'tsconfig.json', json);
39
+ return tree;
40
+ };
41
+ }
42
+
43
+ function cleanOutput(p: string): void {
44
+ try {
45
+ rmdirSync(p, { recursive: true });
46
+ mkdirSync(p);
47
+ } catch (e) {}
48
+ }
49
+
50
+ function fix(output: string, res: GenerateApiOutput, tree: Tree, context: SchematicContext): void {
51
+ const indexList = [`models`, `_base.service`];
52
+ const basePath = normalize(join(project.root, output.replace(process.cwd(), '')));
53
+ try {
54
+ // definitions
55
+ const dataTpl = res.getTemplate({ name: 'dataContracts', fileName: 'data-contracts.eta' });
56
+ const dataContent = res.renderTemplate(dataTpl, { ...res.configuration });
57
+ tree.create(`${basePath}/models.ts`, filePrefix + res.formatTSContent(dataContent));
58
+
59
+ // Base Service
60
+ const baseServiceTpl = res.getTemplate({ name: 'baseService', fileName: 'base.service.eta' });
61
+ const baseServiceContent = res.renderTemplate(baseServiceTpl, { ...res.configuration });
62
+ tree.create(`${basePath}/_base.service.ts`, filePrefix + res.formatTSContent(baseServiceContent));
63
+
64
+ // Tag Service
65
+ const dtoTypeTpl = res.getTemplate({ name: 'dto-type', fileName: 'dto-type.eta' });
66
+ const serviceTpl = res.getTemplate({ name: 'service', fileName: 'service.eta' });
67
+ res.configuration.routes.combined.forEach(route => {
68
+ const routeIndex: string[] = [];
69
+ // dto
70
+ const dtoContent = res.formatTSContent(
71
+ res.renderTemplate(dtoTypeTpl, {
72
+ ...res.configuration,
73
+ route
74
+ })
75
+ );
76
+ if (dtoContent.trim().length > 10) {
77
+ tree.create(`${basePath}/${route.moduleName}/dtos.ts`, filePrefix + dtoContent);
78
+ routeIndex.push(`dtos`);
79
+ }
80
+
81
+ // service
82
+ const serviceContent = res.renderTemplate(serviceTpl, {
83
+ ...res.configuration,
84
+ route
85
+ });
86
+ tree.create(`${basePath}/${route.moduleName}/service.ts`, filePrefix + res.formatTSContent(serviceContent));
87
+ routeIndex.push(`service`);
88
+
89
+ // index.ts
90
+ tree.create(
91
+ `${basePath}/${route.moduleName}/index.ts`,
92
+ filePrefix + routeIndex.map(name => `export * from './${name}';`).join('\n')
93
+ );
94
+ indexList.push(`${route.moduleName}/index`);
95
+ });
96
+ // Index
97
+ tree.create(`${basePath}/index.ts`, filePrefix + indexList.map(name => `export * from './${name}';`).join('\n'));
98
+ } catch (ex) {
99
+ throw new SchematicsException(`Parse error: ${ex}`);
100
+ }
101
+ }
102
+
103
+ function genProxy(config: STAConfig): Rule {
104
+ return (tree: Tree, context: SchematicContext) => {
105
+ context.logger.info(colors.blue(`- Name: ${config.name}`));
106
+ const output = (config.output = resolve(process.cwd(), config.output ?? `./src/app/_${config.name}`));
107
+ const templates = resolve(__dirname, './templates');
108
+ if (config.url) {
109
+ context.logger.info(colors.blue(`- Using url data: ${config.url}`));
110
+ } else if (config.filePath) {
111
+ context.logger.info(colors.blue(`- Using file data: ${config.filePath}`));
112
+ }
113
+ context.logger.info(colors.blue(`- Output: ${output}`));
114
+
115
+ return new Promise<void>(resolve => {
116
+ context.logger.info(colors.blue(`Start generating...`));
117
+ const options = {
118
+ name: `${config.name}.ts`,
119
+ url: config.url,
120
+ input: config.filePath,
121
+ spec: config.spec,
122
+ output,
123
+ templates,
124
+ toJS: false,
125
+ modular: true,
126
+ cleanOutput: true,
127
+ generateUnionEnums: true,
128
+ generateClient: true,
129
+ extractRequestParams: false,
130
+ generateResponses: false,
131
+ generateRouteTypes: true,
132
+ generateApi: true,
133
+ silent: true,
134
+ disableStrictSSL: true,
135
+ moduleNameFirstTag: true,
136
+ defaultResponseType: 'any',
137
+ typePrefix: config.modelTypePrefix,
138
+ hooks: {
139
+ onInit: (c: { httpClientType: string }) => {
140
+ c.httpClientType = config.httpClientType;
141
+ return c;
142
+ },
143
+ onPrepareConfig: c => {
144
+ if (!config.responseDataField) return c;
145
+
146
+ const getDeepDataType = (ref: string): any => {
147
+ let typeData = c.utils.getComponentByRef(ref)?.typeData as any;
148
+ while (typeData != null && Array.isArray(typeData.allOf) && typeData.allOf.length > 0) {
149
+ typeData = c.utils.getComponentByRef(typeData.allOf[0].$ref)?.typeData;
150
+ }
151
+ return typeData;
152
+ };
153
+
154
+ c.routes.combined?.forEach(moduleInfo => {
155
+ moduleInfo.routes.forEach((routeInfo: any) => {
156
+ if (!routeInfo.responseBodySchema) return;
157
+ try {
158
+ const responseBodyContentFirstType = Object.keys(routeInfo.responseBodySchema?.content).pop();
159
+ if (!responseBodyContentFirstType) return;
160
+
161
+ const ref = routeInfo.responseBodySchema.content[responseBodyContentFirstType].schema.$ref;
162
+ const resDataType = getDeepDataType(ref);
163
+ if (!resDataType) return;
164
+ const fieldProperty = resDataType.properties?.[config.responseDataField];
165
+ if (!fieldProperty) return;
166
+ routeInfo.response.type = fieldProperty.$parsed.content ?? 'any';
167
+ } catch (ex) {
168
+ throw new SchematicsException(`Parse data field error: ${ex}`);
169
+ }
170
+ });
171
+ });
172
+ return c;
173
+ },
174
+ onFormatTypeName: formattedModelName => {
175
+ if (!config.modelTypePrefix) return formattedModelName;
176
+
177
+ if (formattedModelName.startsWith(config.modelTypePrefix + config.modelTypePrefix)) {
178
+ return formattedModelName.substring(config.modelTypePrefix.length);
179
+ }
180
+ return formattedModelName;
181
+ }
182
+ },
183
+ ...(config.generateApiOptions as any)
184
+ } as GenerateApiParams;
185
+ generateApi(options)
186
+ .then((res: GenerateApiOutput) => {
187
+ cleanOutput(output);
188
+ fix(output, res, tree, context);
189
+ resolve();
190
+ })
191
+ .catch(ex => {
192
+ throw new SchematicsException(`Generate error: ${ex}`);
193
+ });
194
+ });
195
+ };
196
+ }
197
+
198
+ function finished(): Rule {
199
+ return (_: Tree, context: SchematicContext) => {
200
+ context.logger.info(colors.green(`✓ Finished, refer to: https://ng-alain.com/cli/sta`));
201
+ };
202
+ }
203
+
204
+ function tryLoadConfig(context: SchematicContext, configPath?: string): STAConfig | null {
205
+ if (!configPath || configPath.length <= 0) return null;
206
+
207
+ try {
208
+ const configFile = resolve(process.cwd(), configPath);
209
+ context.logger.info(colors.blue(`- Use config file: ${configFile}`));
210
+ if (existsSync(configFile)) {
211
+ return parse(readFileSync(configFile).toString('utf8'));
212
+ }
213
+ } catch (err) {
214
+ throw new SchematicsException(`Invalid config file ${err}`);
215
+ }
216
+ }
217
+
218
+ export default function (options: Schema): Rule {
219
+ return async (tree: Tree, context: SchematicContext) => {
220
+ context.logger.info(
221
+ colors.yellow(
222
+ `The ng g ng-alain:sta is currently in testing status and may change before the major version of '13'`
223
+ )
224
+ );
225
+
226
+ project = (await getProject(tree, options.project)).project;
227
+ const config: STAConfig = {
228
+ name: 'sta',
229
+ ...options,
230
+ ...tryLoadConfig(context, options.config)
231
+ };
232
+ if (typeof config.generateApiOptions === 'string') {
233
+ try {
234
+ config.generateApiOptions = JSON.parse(config.generateApiOptions);
235
+ } catch (ex) {
236
+ throw new SchematicsException(`Parse generateApiParams error: '${config.generateApiOptions}' => ${ex}`);
237
+ }
238
+ }
239
+
240
+ return chain([addPathInTsConfig(config.name), genProxy(config), finished()]);
241
+ };
242
+ }
package/sta/schema.js ADDED
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.js","sourceRoot":"","sources":["../../../schematics/sta/schema.ts"],"names":[],"mappings":""}
@@ -0,0 +1,52 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema",
3
+ "$id": "SchematicsNgAlainSTAComponent",
4
+ "title": "Ng Alain Swagger To API Options Schema",
5
+ "type": "object",
6
+ "additionalProperties": true,
7
+ "properties": {
8
+ "config": {
9
+ "type": "string",
10
+ "default": "sta.json",
11
+ "description": "指定配置文件路径 (Specify the configuration file path)"
12
+ },
13
+ "name": {
14
+ "type": "string",
15
+ "description": "Name for swagger project name, Default: sta",
16
+ "default": "sta"
17
+ },
18
+ "url": {
19
+ "type": "string",
20
+ "description": "URL to swagger schema, Choose one of filePath and url."
21
+ },
22
+ "filePath": {
23
+ "type": "string",
24
+ "description": "Path to swagger schema, Choose one of filePath and url."
25
+ },
26
+ "output": {
27
+ "type": "string",
28
+ "description": "Path to folder where will been located the created api module, Default: /src/app/${name}"
29
+ },
30
+ "responseDataField": {
31
+ "type": "string",
32
+ "description": "The real data field of Response"
33
+ },
34
+ "httpClientType": {
35
+ "type": "string",
36
+ "default": "delon",
37
+ "enum": [ "delon", "angular" ],
38
+ "description": "httpClient request type, Default: `delon`"
39
+ },
40
+ "modelTypePrefix": {
41
+ "type": "string",
42
+ "default": "",
43
+ "description": "Model name prefix"
44
+ },
45
+ "generateApiOptions": {
46
+ "anyOf": [
47
+ { "type": "string", "default": "{}" },
48
+ { "type": "object" }
49
+ ]
50
+ }
51
+ }
52
+ }
package/sta/schema.ts ADDED
@@ -0,0 +1,39 @@
1
+ export interface Schema {
2
+ /**
3
+ * 指定配置文件路径 (Specify the configuration file path)
4
+ */
5
+ config?: string;
6
+
7
+ /**
8
+ * Name for swagger project name, Default: `sta`
9
+ */
10
+ name?: string;
11
+
12
+ url?: string;
13
+
14
+ input?: string;
15
+
16
+ /**
17
+ * Path to folder where will been located the created api module, Default: `/src/app/${name}`
18
+ */
19
+ output?: string;
20
+
21
+ /**
22
+ * The real data field of Response
23
+ */
24
+ responseDataField?: string;
25
+
26
+ /**
27
+ * httpClient request type, Default: `delon`
28
+ */
29
+ httpClientType?: 'angular' | 'delon';
30
+
31
+ /**
32
+ * Model name prefix
33
+ */
34
+ modelTypePrefix?: string;
35
+
36
+ generateApiOptions?: string;
37
+
38
+ project?: string;
39
+ }