@domain.js/main 0.1.0

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 (76) hide show
  1. package/.eslintrc.js +67 -0
  2. package/.husky/pre-commit +7 -0
  3. package/.test/test.ts +13 -0
  4. package/.test/test2.js +45 -0
  5. package/.travis.yml +8 -0
  6. package/.vscode/settings.json +3 -0
  7. package/README.md +6 -0
  8. package/dist/cli/index.d.ts +2 -0
  9. package/dist/cli/index.js +221 -0
  10. package/dist/deps/aes/index.d.ts +4 -0
  11. package/dist/deps/aes/index.js +16 -0
  12. package/dist/deps/axios/index.d.ts +22 -0
  13. package/dist/deps/axios/index.js +56 -0
  14. package/dist/deps/cache/After.d.ts +3 -0
  15. package/dist/deps/cache/After.js +28 -0
  16. package/dist/deps/cache/Before.d.ts +4 -0
  17. package/dist/deps/cache/Before.js +16 -0
  18. package/dist/deps/cache/Define.d.ts +28 -0
  19. package/dist/deps/cache/Define.js +2 -0
  20. package/dist/deps/cache/index.d.ts +5 -0
  21. package/dist/deps/cache/index.js +50 -0
  22. package/dist/deps/checker/index.d.ts +11 -0
  23. package/dist/deps/checker/index.js +25 -0
  24. package/dist/deps/cia/errors.d.ts +6 -0
  25. package/dist/deps/cia/errors.js +36 -0
  26. package/dist/deps/cia/index.d.ts +53 -0
  27. package/dist/deps/cia/index.js +291 -0
  28. package/dist/deps/counter/index.d.ts +16 -0
  29. package/dist/deps/counter/index.js +16 -0
  30. package/dist/deps/cron/index.d.ts +33 -0
  31. package/dist/deps/cron/index.js +98 -0
  32. package/dist/deps/defines.d.ts +35 -0
  33. package/dist/deps/defines.js +36 -0
  34. package/dist/deps/graceful/index.d.ts +14 -0
  35. package/dist/deps/graceful/index.js +115 -0
  36. package/dist/deps/hash/index.d.ts +17 -0
  37. package/dist/deps/hash/index.js +17 -0
  38. package/dist/deps/logger/index.d.ts +14 -0
  39. package/dist/deps/logger/index.js +100 -0
  40. package/dist/deps/parallel/index.d.ts +34 -0
  41. package/dist/deps/parallel/index.js +93 -0
  42. package/dist/deps/redis/index.d.ts +6 -0
  43. package/dist/deps/redis/index.js +9 -0
  44. package/dist/deps/rest/Before.d.ts +5 -0
  45. package/dist/deps/rest/Before.js +9 -0
  46. package/dist/deps/rest/defines.d.ts +50 -0
  47. package/dist/deps/rest/defines.js +2 -0
  48. package/dist/deps/rest/index.d.ts +34 -0
  49. package/dist/deps/rest/index.js +79 -0
  50. package/dist/deps/rest/stats.d.ts +6 -0
  51. package/dist/deps/rest/stats.js +155 -0
  52. package/dist/deps/rest/utils.d.ts +23 -0
  53. package/dist/deps/rest/utils.js +419 -0
  54. package/dist/deps/schema/index.d.ts +11 -0
  55. package/dist/deps/schema/index.js +39 -0
  56. package/dist/deps/sequelize/index.d.ts +11 -0
  57. package/dist/deps/sequelize/index.js +17 -0
  58. package/dist/deps/signer/index.d.ts +20 -0
  59. package/dist/deps/signer/index.js +36 -0
  60. package/dist/dm/dm.d.ts +21 -0
  61. package/dist/dm/dm.js +57 -0
  62. package/dist/dm/index.d.ts +12 -0
  63. package/dist/dm/index.js +56 -0
  64. package/dist/http/index.d.ts +12 -0
  65. package/dist/http/index.js +34 -0
  66. package/dist/http/router.d.ts +23 -0
  67. package/dist/http/router.js +215 -0
  68. package/dist/http/utils.d.ts +29 -0
  69. package/dist/http/utils.js +185 -0
  70. package/dist/index.d.ts +65 -0
  71. package/dist/index.js +18 -0
  72. package/dist/utils/index.d.ts +36 -0
  73. package/dist/utils/index.js +84 -0
  74. package/jest.config.js +6 -0
  75. package/package.json +79 -0
  76. package/tsconfig.json +13 -0
@@ -0,0 +1,20 @@
1
+ export interface Opt {
2
+ uri: string;
3
+ key: string;
4
+ timestamp: number;
5
+ signMethod: "HmacSHA256";
6
+ signVersion: "1";
7
+ method: string;
8
+ }
9
+ export declare function Main(): {
10
+ generator: (opt: Opt, secret: string) => string;
11
+ request: (uri: string, method: string, key: string, secret: string) => {
12
+ "x-auth-signature": string;
13
+ "x-auth-key": string;
14
+ "x-auth-method": string;
15
+ "x-auth-timestamp": number;
16
+ "x-auth-sign-method": "HmacSHA256";
17
+ "x-auth-sign-version": "1";
18
+ };
19
+ };
20
+ export declare const Deps: never[];
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Deps = exports.Main = void 0;
4
+ const crypto = require("crypto");
5
+ function Main() {
6
+ const generator = (opt, secret) => {
7
+ const string = Object.keys(opt)
8
+ .map((k) => `${k}=${encodeURIComponent(opt[k])}`)
9
+ .sort()
10
+ .join("&");
11
+ const h = crypto.createHmac("sha256", secret);
12
+ return h.update(string).digest("base64");
13
+ };
14
+ const request = (uri, method, key, secret) => {
15
+ const opt = {
16
+ uri,
17
+ key,
18
+ timestamp: (Date.now() / 1000) | 0,
19
+ signMethod: "HmacSHA256",
20
+ signVersion: "1",
21
+ method,
22
+ };
23
+ const signature = generator(opt, secret);
24
+ return {
25
+ "x-auth-signature": signature,
26
+ "x-auth-key": key,
27
+ "x-auth-method": method,
28
+ "x-auth-timestamp": opt.timestamp,
29
+ "x-auth-sign-method": opt.signMethod,
30
+ "x-auth-sign-version": opt.signVersion,
31
+ };
32
+ };
33
+ return { generator, request };
34
+ }
35
+ exports.Main = Main;
36
+ exports.Deps = [];
@@ -0,0 +1,21 @@
1
+ import * as lodash from "lodash";
2
+ interface ModuleInterface {
3
+ Main?: (...args: any[]) => any;
4
+ main?: (...args: any[]) => any;
5
+ Deps?: string[];
6
+ Before?: (...args: any[]) => any;
7
+ After?: (...args: any[]) => void;
8
+ }
9
+ declare type ModuleFn = (((...args: any[]) => any) | {}) & ModuleInterface;
10
+ export declare type Merge<T extends {}, D extends {
11
+ [k in string]: ModuleFn;
12
+ }> = T & {
13
+ [K in keyof D]: ReturnType<D[K]["Main"] extends (...args: any) => any ? D[K]["Main"] : D[K]["main"] extends (...args: any) => any ? D[K]["main"] : D[K] extends (...args: any) => any ? D[K] : (...args: any) => any>;
14
+ };
15
+ export declare function DM(_: typeof lodash): {
16
+ exec: <Args extends any[], BeforeFn extends (...args: Args) => any[], MainFn extends (...args: ReturnType<BeforeFn>) => any, AfterFn extends (main: ReturnType<MainFn>, ...args: ReturnType<BeforeFn>) => void>(Main: MainFn, Before: BeforeFn | undefined, After: AfterFn | undefined, _args?: Args) => ReturnType<MainFn>;
17
+ auto: <Modules extends {
18
+ [x: string]: ModuleFn;
19
+ }, Deps extends object, Args_1 extends any[]>(modules: Modules, deps: Deps, args: Args_1) => Merge<Deps, Modules>;
20
+ };
21
+ export {};
package/dist/dm/dm.js ADDED
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DM = void 0;
4
+ function DM(_) {
5
+ function exec(Main, Before = ((...args) => args), After, _args = []) {
6
+ const args = Before(..._args);
7
+ const main = Main(...args);
8
+ if (typeof After === "function")
9
+ After(main, ...args);
10
+ return main;
11
+ }
12
+ function auto(modules, deps, args) {
13
+ // 获取全部即将初始化的模块名称,此时的 modules 是扁平的一级结构
14
+ const names = new Set(Object.keys(modules));
15
+ while (names.size) {
16
+ // 记录此次迭代有多少个模块被排序了,如果某次迭代被排序的模块数量为0,
17
+ // 那就要抛出异常了,说明依赖指定有问题,永远都不可能排序完毕
18
+ let count = 0;
19
+ /** 默认挂载函数 */
20
+ const plugin = (name) => {
21
+ const Module = modules[name];
22
+ const Main = Module.Main || Module.main || Module;
23
+ if (typeof Main !== "function")
24
+ throw Error("Main is not a function");
25
+ const Before = Module.Before || ((...args) => args);
26
+ const After = Module.After;
27
+ if (After && typeof After !== "function")
28
+ throw Error("After is not a function");
29
+ const main = exec(Main, Before, After, args);
30
+ if (_.has(deps, name))
31
+ throw Error(`Name ${name} duplicate`);
32
+ _.set(deps, name, main);
33
+ names.delete(name);
34
+ count += 1;
35
+ };
36
+ for (const x of names) {
37
+ const { Deps } = modules[x];
38
+ if (!Array.isArray(Deps) || !Deps.length) {
39
+ plugin(x);
40
+ continue;
41
+ }
42
+ if (Deps.every((d) => _.has(deps, d)))
43
+ plugin(x);
44
+ }
45
+ if (count === 0) {
46
+ const lacks = [];
47
+ for (const x of names) {
48
+ lacks.push(`${x}: ${_.filter(modules[x].Deps, (d) => !_.has(deps, d)).join(",")}`);
49
+ }
50
+ throw Error(`Deps defined conflict, ${lacks.join(";")}`);
51
+ }
52
+ }
53
+ return deps;
54
+ }
55
+ return { exec, auto };
56
+ }
57
+ exports.DM = DM;
@@ -0,0 +1,12 @@
1
+ interface ModuleInterface {
2
+ Main: (...args: any[]) => any;
3
+ Deps?: string[];
4
+ Before?: (...args: any[]) => any;
5
+ After?: (...args: any[]) => void;
6
+ }
7
+ declare type ModuleFn = (((...args: any[]) => any) | {}) & ModuleInterface;
8
+ export declare function exec<Args extends any[], BeforeFn extends (...args: Args) => any[], MainFn extends (...args: ReturnType<BeforeFn>) => any, AfterFn extends (main: ReturnType<MainFn>, ...args: ReturnType<BeforeFn>) => void>(Main: MainFn, Before?: BeforeFn, After?: AfterFn | undefined, _args?: Args): ReturnType<MainFn>;
9
+ export declare function auto<Modules extends {
10
+ [k in string]: ModuleFn;
11
+ }, Deps extends object, Args extends any[]>(modules: Modules, deps: Deps, args: Args): { [k in keyof Modules]: ReturnType<Modules[k]["Main"]>; };
12
+ export {};
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.auto = exports.exec = void 0;
4
+ const _ = require("lodash");
5
+ function exec(Main, Before = ((...args) => args), After = undefined, _args = []) {
6
+ const args = Before(..._args);
7
+ const main = Main(...args);
8
+ if (typeof After === "function")
9
+ After(main, ...args);
10
+ return main;
11
+ }
12
+ exports.exec = exec;
13
+ function auto(modules, deps, args) {
14
+ // 获取全部即将初始化的模块名称,此时的 modules 是扁平的一级结构
15
+ const names = new Set(Object.keys(modules));
16
+ while (names.size) {
17
+ // 记录此次迭代有多少个模块被排序了,如果某次迭代被排序的模块数量为0,
18
+ // 那就要抛出异常了,说明依赖指定有问题,永远都不可能排序完毕
19
+ let count = 0;
20
+ /** 默认挂载函数 */
21
+ const plugin = (name) => {
22
+ const Module = modules[name];
23
+ const Main = Module.Main;
24
+ if (typeof Main !== "function")
25
+ throw Error("Main is not a function");
26
+ const Before = Module.Before || ((...args) => args);
27
+ const After = Module.After;
28
+ if (After && typeof After !== "function")
29
+ throw Error("After is not a function");
30
+ const main = exec(Main, Before, After, args);
31
+ if (_.has(deps, name))
32
+ throw Error(`Name ${name} duplicate`);
33
+ _.set(deps, name, main);
34
+ names.delete(name);
35
+ count += 1;
36
+ };
37
+ for (const x of names) {
38
+ const { Deps } = modules[x];
39
+ if (!Array.isArray(Deps) || !Deps.length) {
40
+ plugin(x);
41
+ continue;
42
+ }
43
+ if (Deps.every((d) => _.has(deps, d)))
44
+ plugin(x);
45
+ }
46
+ if (count === 0) {
47
+ const lacks = [];
48
+ for (const x of names) {
49
+ lacks.push(`${x}: ${_.filter(modules[x].Deps, (d) => !_.has(deps, d)).join(",")}`);
50
+ }
51
+ throw Error(`Deps defined conflict, ${lacks.join(";")}`);
52
+ }
53
+ }
54
+ return deps;
55
+ }
56
+ exports.auto = auto;
@@ -0,0 +1,12 @@
1
+ import * as restify from "restify";
2
+ import { Router } from "./router";
3
+ import { Cnf, Domain, Profile, HttpCodes } from "./defines";
4
+ interface Deps {
5
+ routers(r: ReturnType<typeof Router>): void;
6
+ domain: Domain;
7
+ httpCodes: HttpCodes;
8
+ swaggerDocJson?: any;
9
+ makeProfileHook?: (obj: Profile, req: restify.Request) => any;
10
+ }
11
+ export declare function Main(cnf: Cnf, deps: Deps): () => restify.Server;
12
+ export {};
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Main = void 0;
4
+ const restify = require("restify");
5
+ const router_1 = require("./router");
6
+ const utils_1 = require("./utils");
7
+ function Main(cnf, deps) {
8
+ const utils = (0, utils_1.Utils)(cnf);
9
+ const { routers, domain, httpCodes, swaggerDocJson, makeProfileHook } = deps;
10
+ const server = restify.createServer();
11
+ server.use(restify.plugins.queryParser());
12
+ server.use(restify.plugins.bodyParser({
13
+ keepExtensions: true,
14
+ maxFieldsSize: cnf.bodyMaxBytes || 2 * 1024 * 1024, // 参数最大容量 2MB
15
+ }));
16
+ const router = (0, router_1.Router)({
17
+ utils,
18
+ server,
19
+ httpCodes,
20
+ makeProfileHook,
21
+ domain,
22
+ apisRoute: cnf.apisRoute,
23
+ swagger: [cnf.swaggerApiPath, swaggerDocJson],
24
+ });
25
+ routers(router);
26
+ // Http server start
27
+ return () => {
28
+ server.listen(cnf.port || 8088, cnf.host || "127.0.0.1", () => {
29
+ console.log("%s listening at %s", server.name, server.url);
30
+ });
31
+ return server;
32
+ };
33
+ }
34
+ exports.Main = Main;
@@ -0,0 +1,23 @@
1
+ import * as restify from "restify";
2
+ import { Utils } from "./utils";
3
+ import { HttpCodes, Domain, Profile } from "./defines";
4
+ interface Deps {
5
+ domain: Domain;
6
+ utils: ReturnType<typeof Utils>;
7
+ server: restify.Server;
8
+ httpCodes: HttpCodes;
9
+ makeProfileHook?(obj: Profile, req: restify.Request): any;
10
+ apisRoute?: string;
11
+ swagger?: [any, any];
12
+ }
13
+ export declare function Router(deps: Deps): {
14
+ get: (routePath: string, ctlAct: string, code?: number, isList?: boolean, handler?: Function | undefined, resHandler?: Function | undefined) => void;
15
+ post: (routePath: string, ctlAct: string, code?: number, isList?: boolean, handler?: Function | undefined, resHandler?: Function | undefined) => void;
16
+ put: (routePath: string, ctlAct: string, code?: number, isList?: boolean, handler?: Function | undefined, resHandler?: Function | undefined) => void;
17
+ del: (routePath: string, ctlAct: string, code?: number, isList?: boolean, handler?: Function | undefined, resHandler?: Function | undefined) => void;
18
+ } & {
19
+ collection: (res: string, _routePath?: string | undefined, controller?: string | undefined) => void;
20
+ model: (res: string, routePath?: string) => void;
21
+ resource: (res: string, routePath?: string) => void;
22
+ };
23
+ export {};
@@ -0,0 +1,215 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Router = void 0;
4
+ const _ = require("lodash");
5
+ const errors = require("restify-errors");
6
+ const swaggerUi = require("swagger-ui-restify");
7
+ function Router(deps) {
8
+ const { domain, apisRoute, utils, server, httpCodes = {}, makeProfileHook, swagger = ["", {}], } = deps;
9
+ const { ucwords, makeParams, makeProfile, outputCSV, jsonSchema2Swagger } = utils;
10
+ // 改写 HttpErrorToJSON 处理 data
11
+ const HttpErrorToJSON = errors.HttpError.prototype.toJSON;
12
+ errors.HttpError.prototype.toJSON = function toJSON() {
13
+ const json = HttpErrorToJSON.call(this);
14
+ if (this.body.data)
15
+ json.data = this.body.data;
16
+ return json;
17
+ };
18
+ const error2httpError = (error) => {
19
+ const { code, message, data } = error;
20
+ const e = errors.makeErrFromCode((code && httpCodes[code]) || 500, message);
21
+ if (code)
22
+ e.body.code = code;
23
+ if (data)
24
+ e.body.data = data;
25
+ return e;
26
+ };
27
+ const [apiSwagger, swaggerDocJson] = swagger;
28
+ const apis = [];
29
+ let apisHTML = "<h3>API 目录,点击可以查看参数格式定义</h3>";
30
+ let swaggerHtml = "";
31
+ if (apiSwagger) {
32
+ server.get(`/${apiSwagger}/*.*`, ...swaggerUi.serve);
33
+ server.get(`/${apiSwagger}`, (req, res) => {
34
+ res.writeHead(200, {
35
+ "Content-Length": Buffer.byteLength(swaggerHtml),
36
+ "Content-Type": "text/html",
37
+ });
38
+ res.write(swaggerHtml);
39
+ res.end();
40
+ });
41
+ }
42
+ /** 判断是否需要提供apis的查询接口 */
43
+ if (apisRoute) {
44
+ server.get(`/${apisRoute}`, (req, res, next) => {
45
+ if (req.query._format === "html") {
46
+ res.sendRaw(200, apisHTML, {
47
+ "Content-Type": "text/html; charset=utf-8",
48
+ });
49
+ }
50
+ else {
51
+ res.send(apis);
52
+ }
53
+ next();
54
+ });
55
+ server.get(`/${apisRoute}/_schema`, (req, res, next) => {
56
+ const { path } = req.query;
57
+ try {
58
+ const { all } = req.query;
59
+ const schema = domain._getSchemaByPath(path);
60
+ res.send(all === undefined ? schema[1] : schema);
61
+ }
62
+ catch (e) {
63
+ next(error2httpError(e));
64
+ return;
65
+ }
66
+ next();
67
+ });
68
+ }
69
+ const getAPISchemaDoc = (verb, route, methodPath) => {
70
+ if (!apiSwagger)
71
+ return;
72
+ let apiSchema = [];
73
+ let desc = "";
74
+ try {
75
+ apiSchema = domain._getSchemaByPath(methodPath);
76
+ desc = apiSchema[1] ? apiSchema[1].description : "unknow";
77
+ apiSchema = jsonSchema2Swagger(apiSchema[1] ? apiSchema[1] : {}, verb, methodPath, swaggerDocJson);
78
+ }
79
+ catch (e) {
80
+ console.log(methodPath, "schema to swagger error.");
81
+ }
82
+ swaggerHtml = swaggerUi.generateHTML(swaggerDocJson, {
83
+ baseURL: `${swaggerDocJson.basePath}${apiSwagger}`,
84
+ explorer: true,
85
+ });
86
+ const apiTag = methodPath.split(".")[0];
87
+ swaggerDocJson.paths[route] = {
88
+ [verb]: {
89
+ "x-swagger-router-controller": methodPath,
90
+ operationId: methodPath,
91
+ tags: [apiTag],
92
+ externalDocs: {
93
+ description: "查看接口参数 json schema 定义",
94
+ url: `./${apisRoute}/_schema?path=${methodPath}`,
95
+ },
96
+ description: desc,
97
+ parameters: apiSchema || [],
98
+ responses: {},
99
+ },
100
+ };
101
+ };
102
+ function register(verb, route, methodPath, code = 200, isList = false, handler, resHandler) {
103
+ /**
104
+ * 暂存起来,提供给apis接口来用
105
+ * apis接口用来返回当前 services 提供的可用的 api
106
+ */
107
+ apis.push(`[${verb.toUpperCase()}] ${route} Domain: ${methodPath}`);
108
+ apisHTML += `\n<li><a href="./${apisRoute}/_schema?path=${methodPath}">[${verb.toUpperCase()}] ${route} Domain: ${methodPath}</a></li>`;
109
+ const method = _.get(domain, methodPath);
110
+ /** 如果都没有则抛出异常 */
111
+ if (!method || !_.isFunction(method)) {
112
+ throw Error(`Missing domain method: ${methodPath}`);
113
+ }
114
+ getAPISchemaDoc(verb, route, methodPath);
115
+ server[verb](route, async (req, res, next) => {
116
+ const profile = makeProfile(req, methodPath, makeProfileHook);
117
+ const params = makeParams(req);
118
+ // 额外处理 params
119
+ if (handler)
120
+ handler(params);
121
+ res.header("X-RequestID", profile.requestId);
122
+ try {
123
+ let results = await method(profile, params);
124
+ res.header("X-ConsumedTime", Date.now() - profile.startedAt.valueOf());
125
+ if (results == null)
126
+ results = "Ok";
127
+ if (resHandler) {
128
+ resHandler(results, res);
129
+ }
130
+ else if (isList) {
131
+ const { _ignoreTotal, _format } = params;
132
+ if (_ignoreTotal !== "yes") {
133
+ res.header("X-Content-Record-Total", results.count);
134
+ }
135
+ let ok = false;
136
+ if (_format === "csv" || _format === "xlsx") {
137
+ // 导出csv
138
+ ok = await outputCSV(results.rows, params, res, _format === "xlsx");
139
+ }
140
+ if (!ok)
141
+ res.send(code, results.rows);
142
+ }
143
+ else if (!_.isObject(results)) {
144
+ if (code === 204) {
145
+ res.send(code);
146
+ }
147
+ else {
148
+ res.sendRaw(code, String(results));
149
+ }
150
+ }
151
+ else {
152
+ res.send(code, code !== 204 && results);
153
+ }
154
+ }
155
+ catch (e) {
156
+ res.header("X-ConsumedTime", Date.now() - profile.startedAt.valueOf());
157
+ next(error2httpError(e));
158
+ return;
159
+ }
160
+ next();
161
+ });
162
+ }
163
+ function RouterVerbFn(verb) {
164
+ return (routePath, ctlAct, code = 200, isList = false, handler, resHandler) => {
165
+ register(verb, routePath, ctlAct, code, isList, handler, resHandler);
166
+ if (verb === "put") {
167
+ register("patch", routePath, ctlAct, code, isList, handler, resHandler);
168
+ }
169
+ };
170
+ }
171
+ const router = {
172
+ get: RouterVerbFn("get"),
173
+ post: RouterVerbFn("post"),
174
+ put: RouterVerbFn("put"),
175
+ del: RouterVerbFn("del"),
176
+ };
177
+ /**
178
+ * controller 为可选参数,如果不填写则控制器名称直接就是 res ,方法为 list,add
179
+ * 如果设置了controller 则控制器为 controller,方法为 #{res}s, add{Res}
180
+ */
181
+ const collection = (res, _routePath, controller) => {
182
+ let routePath;
183
+ if (typeof _routePath !== "string") {
184
+ if (controller) {
185
+ routePath = `/${controller}s/:${controller}Id/${res}s`;
186
+ }
187
+ else {
188
+ routePath = `/${res}s`;
189
+ }
190
+ }
191
+ else {
192
+ routePath = _routePath;
193
+ }
194
+ if (controller) {
195
+ register("get", routePath, `${controller}.${res}s`, 200, true);
196
+ register("post", routePath, `${controller}.add${ucwords(res)}`, 201);
197
+ }
198
+ else {
199
+ register("get", routePath, `${res}.list`, 200, true);
200
+ register("post", routePath, `${res}.add`, 201);
201
+ }
202
+ };
203
+ const model = (res, routePath = `/${res}s/:id`) => {
204
+ register("get", routePath, `${res}.detail`);
205
+ register("put", routePath, `${res}.modify`);
206
+ register("patch", routePath, `${res}.modify`);
207
+ register("del", routePath, `${res}.remove`, 204);
208
+ };
209
+ const resource = (res, routePath = `/${res}s`) => {
210
+ collection(res, routePath);
211
+ model(res, `${routePath}/:id`);
212
+ };
213
+ return Object.assign(router, { collection, model, resource });
214
+ }
215
+ exports.Router = Router;
@@ -0,0 +1,29 @@
1
+ import * as restify from "restify";
2
+ import { Cnf, Profile } from "./defines";
3
+ export declare function Utils(cnf: Cnf): {
4
+ ucwords(value: string): string;
5
+ /** 真实的连接请求端ip */
6
+ remoteIp(req: restify.Request): string;
7
+ /**
8
+ * 获取客户端真实ip地址
9
+ */
10
+ clientIp(req: restify.Request): string;
11
+ /**
12
+ * 获取可信任的真实ip
13
+ */
14
+ realIp(req: restify.Request): string;
15
+ /**
16
+ * 构造profile参数
17
+ */
18
+ makeProfile(req: restify.Request, method: string, customFn?: Function | undefined): Readonly<Profile>;
19
+ /**
20
+ * 构造领域方法所需的 params 参数
21
+ */
22
+ makeParams(req: restify.Request): any;
23
+ /**
24
+ *
25
+ * 输出csv相关
26
+ */
27
+ outputCSV(rows: any[], params: any, res: restify.Response, isXLSX?: boolean): Promise<boolean>;
28
+ jsonSchema2Swagger(schema: any, verb: string, methodPath: string, swaggerDocJson: any): any[];
29
+ };