@domain.js/main 0.1.0 → 0.1.1

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 (59) hide show
  1. package/.husky/pre-commit +1 -1
  2. package/dist/Errors/index.d.ts +16 -0
  3. package/dist/Errors/index.js +27 -0
  4. package/dist/basic-errors.d.ts +1 -0
  5. package/dist/basic-errors.js +10 -0
  6. package/dist/cfg/index.d.ts +6 -0
  7. package/dist/cfg/index.js +26 -0
  8. package/dist/defaults.d.ts +102 -0
  9. package/dist/defaults.js +36 -0
  10. package/dist/deps/cache/After.d.ts +1 -2
  11. package/dist/deps/cache/Before.js +3 -3
  12. package/dist/deps/cache/Define.d.ts +2 -0
  13. package/dist/deps/cache/index.js +2 -2
  14. package/dist/deps/checker/index.d.ts +4 -0
  15. package/dist/deps/checker/index.js +2 -3
  16. package/dist/deps/cia/index.d.ts +8 -0
  17. package/dist/deps/cia/index.js +3 -6
  18. package/dist/deps/cron/index.d.ts +4 -0
  19. package/dist/deps/cron/index.js +2 -4
  20. package/dist/deps/defines.d.ts +2 -2
  21. package/dist/deps/defines.js +2 -2
  22. package/dist/deps/errors/index.d.ts +1 -0
  23. package/dist/deps/errors/index.js +10 -0
  24. package/dist/deps/logger/index.d.ts +12 -1
  25. package/dist/deps/logger/index.js +6 -6
  26. package/dist/deps/parallel/index.d.ts +22 -4
  27. package/dist/deps/parallel/index.js +20 -11
  28. package/dist/deps/redis/index.d.ts +12 -1
  29. package/dist/deps/redis/index.js +12 -4
  30. package/dist/deps/request/index.d.ts +43 -0
  31. package/dist/deps/request/index.js +67 -0
  32. package/dist/deps/rest/index.d.ts +16 -3
  33. package/dist/deps/rest/index.js +41 -2
  34. package/dist/deps/rest/stats.d.ts +8 -1
  35. package/dist/deps/rest/stats.js +9 -2
  36. package/dist/deps/rest/utils.d.ts +8 -0
  37. package/dist/deps/rest/utils.js +1 -3
  38. package/dist/deps/schema/index.d.ts +20 -5
  39. package/dist/deps/schema/index.js +35 -11
  40. package/dist/deps/sequelize/index.d.ts +7 -2
  41. package/dist/deps/sequelize/index.js +3 -4
  42. package/dist/deps/signer/index.d.ts +33 -8
  43. package/dist/deps/signer/index.js +50 -27
  44. package/dist/dm/index.d.ts +16 -1
  45. package/dist/dm/index.js +15 -0
  46. package/dist/errors/index.d.ts +16 -0
  47. package/dist/errors/index.js +27 -0
  48. package/dist/errors.d.ts +1 -0
  49. package/dist/errors.js +10 -0
  50. package/dist/http/defines.d.ts +45 -0
  51. package/dist/http/defines.js +2 -0
  52. package/dist/index.d.ts +12 -8
  53. package/dist/index.js +11 -4
  54. package/dist/npms.d.ts +88 -0
  55. package/dist/npms.js +31 -0
  56. package/dist/utils/index.d.ts +55 -13
  57. package/dist/utils/index.js +61 -15
  58. package/jest.config.js +8 -1
  59. package/package.json +13 -12
@@ -1,10 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Deps = exports.Main = void 0;
4
- const async = require("async");
4
+ const utils = require("../../utils");
5
+ /**
6
+ * Parallel control module
7
+ * @param cnf Module initialization configuration parameters
8
+ * @param deps Module initialization dependency
9
+ * @returns Parallel control function
10
+ */
5
11
  function Main(cnf, deps) {
6
- const { parallel: { key: KEY, defaultErrorFn }, } = cnf;
7
- const { logger, graceful, utils: { sleep }, redis, } = deps;
12
+ const { parallel: { key: KEY, defaultErrorFn, maxExpireSeconds = 300, resetExpireIntervalMS = 100 * 1000, }, } = cnf;
13
+ const { async, logger, graceful, redis } = deps;
14
+ const { sleep } = utils;
8
15
  // 存放当前处于执行中的 key
9
16
  const doings = new Set();
10
17
  let exiting = false;
@@ -22,26 +29,28 @@ function Main(cnf, deps) {
22
29
  const delay = async () => {
23
30
  if (!doings.size)
24
31
  return;
25
- logger.info("start parallel delay keys: %o", doings);
26
32
  await async.eachLimit([...doings], 10, async (key) => {
27
- // 延长 300 秒
28
- await redis.expire(key, 300);
33
+ await redis.expire(key, maxExpireSeconds);
29
34
  });
30
- logger.info("end parallel delay keys: %o", doings);
31
35
  };
32
36
  async.forever(async () => {
33
37
  try {
34
- await sleep(100 * 1000);
38
+ await sleep(resetExpireIntervalMS);
35
39
  await delay();
36
40
  }
37
41
  catch (e) {
38
42
  logger.error(e);
39
43
  }
40
44
  }, logger.error);
41
- /* 将 method 函数处理为有并发控制功能的函数 */
45
+ /**
46
+ * Parallel control function
47
+ * @param method Functions that need to control parallel execution
48
+ * @param opt Parallel control parameters
49
+ * @returns Functions with parallel control capability
50
+ */
42
51
  function control(method, opt) {
43
52
  const { path, keyFn = () => opt.path, minMS = 0, errorFn = defaultErrorFn, needWaitMS = 0, neverReturn = false, } = opt;
44
- const error = (errorFn || defaultErrorFn)(path, minMS);
53
+ const error = errorFn(path, minMS);
45
54
  const end = async (key, startAt) => {
46
55
  const timing = Date.now() - startAt; // 执行总用时毫秒数
47
56
  const remainMS = minMS - timing; // 计算和最小耗时的差值毫秒数
@@ -90,4 +99,4 @@ function Main(cnf, deps) {
90
99
  return control;
91
100
  }
92
101
  exports.Main = Main;
93
- exports.Deps = ["logger", "graceful", "redis", "utils"];
102
+ exports.Deps = ["async", "logger", "graceful", "redis"];
@@ -2,5 +2,16 @@ import * as Redis from "ioredis";
2
2
  interface Cnf {
3
3
  redis: Redis.RedisOptions;
4
4
  }
5
- export declare function Main(cnf: Cnf): Redis.Redis;
5
+ interface Deps {
6
+ IORedis: typeof Redis;
7
+ }
8
+ /**
9
+ * @link https://www.npmjs.com/package/ioredis
10
+ *
11
+ * Redis module, an instance based on ioredis
12
+ * @param cnf
13
+ * @returns An instance of ioredis
14
+ */
15
+ export declare function Main(cnf: Cnf, deps: Deps): Redis.Redis;
16
+ export declare const Deps: string[];
6
17
  export {};
@@ -1,9 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Main = void 0;
4
- const Redis = require("ioredis");
5
- function Main(cnf) {
3
+ exports.Deps = exports.Main = void 0;
4
+ /**
5
+ * @link https://www.npmjs.com/package/ioredis
6
+ *
7
+ * Redis module, an instance based on ioredis
8
+ * @param cnf
9
+ * @returns An instance of ioredis
10
+ */
11
+ function Main(cnf, deps) {
6
12
  const { redis } = cnf;
7
- return new Redis(redis);
13
+ const { IORedis } = deps;
14
+ return new IORedis(redis);
8
15
  }
9
16
  exports.Main = Main;
17
+ exports.Deps = ["IORedis"];
@@ -0,0 +1,43 @@
1
+ import axios, { AxiosInstance } from "axios";
2
+ import { Main as Logger } from "../logger";
3
+ import * as utils from "../../utils";
4
+ interface Cnf {
5
+ /** axios config */
6
+ axios?: {
7
+ /** auto record log methods list */
8
+ loggers?: string[];
9
+ /** auto retry methods list */
10
+ retrys?: string[];
11
+ /** retry max times */
12
+ retryTimes?: number;
13
+ /** retry interval millisecond */
14
+ retryIntervalMS?: number;
15
+ /** axios.create the first argument */
16
+ conf?: Parameters<typeof axios.create>[0];
17
+ };
18
+ }
19
+ interface Deps {
20
+ axios: {
21
+ create: typeof axios.create;
22
+ };
23
+ logger: ReturnType<typeof Logger>;
24
+ utils: {
25
+ sleep: typeof utils.sleep;
26
+ };
27
+ }
28
+ /**
29
+ * axios module
30
+ * @link https://www.npmjs.com/package/axios
31
+ *
32
+ * @param cnf module initialize config
33
+ * @param deps module initalize dependents
34
+ * @returns returns of axios.create
35
+ */
36
+ export declare function Main(cnf: Cnf, deps: Deps): AxiosInstance & {
37
+ /** Original Axios module */
38
+ origin?: {
39
+ create: (config?: import("axios").AxiosRequestConfig<any> | undefined) => AxiosInstance;
40
+ } | undefined;
41
+ };
42
+ export declare const Deps: string[];
43
+ export {};
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Deps = exports.Main = void 0;
4
+ /**
5
+ * axios module
6
+ * @link https://www.npmjs.com/package/axios
7
+ *
8
+ * @param cnf module initialize config
9
+ * @param deps module initalize dependents
10
+ * @returns returns of axios.create
11
+ */
12
+ function Main(cnf, deps) {
13
+ const axiosError = (e) => (() => {
14
+ if (!e.response)
15
+ return ["no-response", e.message];
16
+ const r = e.response;
17
+ if (!r.data)
18
+ return [r.status, r.statusText];
19
+ const d = r.data;
20
+ if (typeof d === "string")
21
+ return [r.status, d];
22
+ return [d.code || r.status, d.message || r.statusText];
23
+ })().join("\t");
24
+ if (!cnf.axios)
25
+ cnf.axios = {};
26
+ const { loggers, retrys, retryTimes = 3, retryIntervalMS = 3000, conf } = cnf.axios;
27
+ const { axios, utils: { sleep }, logger, } = deps;
28
+ const retryAble = (fn, times, interval) => {
29
+ const exec = async (args, no) => {
30
+ try {
31
+ const res = await fn(...args);
32
+ return res;
33
+ }
34
+ catch (e) {
35
+ if (e.code === "ETIMEDOUT") {
36
+ if (interval)
37
+ await sleep(interval);
38
+ if (times <= no)
39
+ throw e;
40
+ return exec(args, no + 1);
41
+ }
42
+ throw e;
43
+ }
44
+ };
45
+ return ((...args) => exec(args, 1));
46
+ };
47
+ const instance = axios.create(conf);
48
+ instance.origin = axios;
49
+ if (loggers) {
50
+ for (const x of loggers) {
51
+ if (typeof instance[x] !== "function")
52
+ continue;
53
+ const method = logger.logger(instance[x], `axios.${x}`, true, (res) => res.data, axiosError);
54
+ instance[x] = method;
55
+ }
56
+ }
57
+ if (retrys) {
58
+ for (const x of retrys) {
59
+ if (typeof instance[x] !== "function")
60
+ continue;
61
+ instance[x] = retryAble(instance[x], retryTimes, retryIntervalMS);
62
+ }
63
+ }
64
+ return instance;
65
+ }
66
+ exports.Main = Main;
67
+ exports.Deps = ["logger", "utils", "axios"];
@@ -1,24 +1,37 @@
1
+ import * as _ from "lodash";
1
2
  import * as Sequelize from "sequelize";
2
3
  import { TModel, Params } from "./defines";
3
4
  import { Stats } from "./stats";
4
5
  import { Utils } from "./utils";
5
6
  export { Before } from "./Before";
6
7
  declare type Cnf = Parameters<typeof Utils>[0] & Parameters<typeof Stats>[0];
7
- declare type Deps = Parameters<typeof Utils>[1] & Parameters<typeof Stats>[1];
8
+ declare type Deps = Parameters<typeof Utils>[1] & Parameters<typeof Stats>[1] & {
9
+ _: typeof _;
10
+ Sequelize: Pick<typeof Sequelize, "literal" | "and" | "fn" | "Op">;
11
+ };
8
12
  declare type UserId = string | number;
9
13
  export interface CreatorAndClientIp {
14
+ /** ID of the resource creator */
10
15
  creatorId: UserId;
16
+ /** IP of the resource creator */
11
17
  clientIp: string;
12
18
  }
19
+ /**
20
+ * Standard(CRUD) restful module, including list, add, edit, delete and statistics
21
+ * @param cnf Configuration information of initialization function
22
+ * @param deps Dependent object of the initialization function
23
+ * @param utils Tool function object
24
+ * @returns modify, add, remove, list, stats five methods
25
+ */
13
26
  export declare function Main(cnf: Cnf, deps: Deps, utils: ReturnType<typeof Utils>): {
14
27
  modify: (Model: TModel, model: Sequelize.Model<any, any>, params: Params, isAdmin?: boolean, _cols?: string[] | undefined) => Promise<Sequelize.Model<any, any>>;
15
28
  add: (Model: TModel, params: Params, isAdmin: boolean | undefined, _cols: string[] | undefined, { creatorId, clientIp }: CreatorAndClientIp) => Promise<any>;
16
29
  remove: (model: Sequelize.Model, deletorId: UserId) => Promise<void | Sequelize.Model<any, any>>;
17
30
  list: (Model: TModel, params: Params, allowAttrs?: string[] | undefined, toJSON?: boolean | undefined) => Promise<{
18
31
  count: number;
19
- rows: any;
32
+ rows: any[];
20
33
  }>;
21
- stats: (Model: TModel, params: Params, where: any, conf?: {
34
+ stats: (Model: TModel, params: Params, where?: any, conf?: {
22
35
  dimensions?: Record<string, string> | undefined;
23
36
  metrics: Record<string, string>;
24
37
  pagination?: {
@@ -5,9 +5,25 @@ const _ = require("lodash");
5
5
  const stats_1 = require("./stats");
6
6
  var Before_1 = require("./Before");
7
7
  Object.defineProperty(exports, "Before", { enumerable: true, get: function () { return Before_1.Before; } });
8
+ /**
9
+ * Standard(CRUD) restful module, including list, add, edit, delete and statistics
10
+ * @param cnf Configuration information of initialization function
11
+ * @param deps Dependent object of the initialization function
12
+ * @param utils Tool function object
13
+ * @returns modify, add, remove, list, stats five methods
14
+ */
8
15
  function Main(cnf, deps, utils) {
9
16
  const { errors } = deps;
10
17
  const { findAllOpts, pickParams } = utils;
18
+ /**
19
+ * Restful modify(U of CRUD) for update a resource
20
+ * @param Model Model definition of resources
21
+ * @param model the resources will be updated
22
+ * @param params parameters for updating
23
+ * @param isAdmin Is it an administrator
24
+ * @param _cols Allow columns to be updated
25
+ * @returns The resource that has been updated
26
+ */
11
27
  const modify = (Model, model, params, isAdmin = false, _cols) => {
12
28
  const cols = _cols || Model.editableCols || Model.writableCols || [];
13
29
  const attr = pickParams(params, cols, Model, isAdmin);
@@ -17,6 +33,15 @@ function Main(cnf, deps, utils) {
17
33
  Object.assign(model, attr);
18
34
  return model.save();
19
35
  };
36
+ /**
37
+ * Restful add(C of CRUD) for create a resource
38
+ * @param Model Model definition of resources
39
+ * @param params parameters for updating
40
+ * @param isAdmin Is it an administrator
41
+ * @param _cols Allow columns to be set
42
+ * @param creatorAndClientIp creatorId and clientIp
43
+ * @returns The resource that has been created
44
+ */
20
45
  const add = async (Model, params, isAdmin = false, _cols, { creatorId, clientIp }) => {
21
46
  const cols = _cols || Model.writableCols || [];
22
47
  const attr = pickParams(params, cols, Model, isAdmin);
@@ -44,6 +69,12 @@ function Main(cnf, deps, utils) {
44
69
  return model.save();
45
70
  };
46
71
  const TRASH_OPT = Object.freeze({ fields: ["isDeleted", "deletorId"] });
72
+ /**
73
+ * Restful remove (D of CRUD) for delete a resource
74
+ * @param model the resources will be removed
75
+ * @param deletorId Operator Id
76
+ * @returns void OR Resources put in the recycle bin
77
+ */
47
78
  const remove = async (model, deletorId) => {
48
79
  // 未开启回收站,直接删除
49
80
  if (!model.isDeleted)
@@ -56,6 +87,14 @@ function Main(cnf, deps, utils) {
56
87
  };
57
88
  // count条件所需属性
58
89
  const COUNT_OPT = Object.freeze(["where", "include"]);
90
+ /**
91
+ * Restful list (R of CRUD) for list resource
92
+ * @param Model Model definition of resources
93
+ * @param params parameters for updating
94
+ * @param allowAttrs Allow columns to be returned
95
+ * @param toJSON Whether to directly return JSON formatted objects
96
+ * @returns findAll resource result, object propoties has count, rows
97
+ */
59
98
  const list = async (Model, params, allowAttrs, toJSON) => {
60
99
  const opt = findAllOpts(Model, params);
61
100
  const { _ignoreTotal } = params;
@@ -65,7 +104,7 @@ function Main(cnf, deps, utils) {
65
104
  count = await Model.count(_.pick(opt, COUNT_OPT));
66
105
  if (Array.isArray(allowAttrs) && allowAttrs.length)
67
106
  opt.attributes = allowAttrs;
68
- const rows = await Model.findAll(opt);
107
+ const rows = (await Model.findAll(opt));
69
108
  if (toJSON) {
70
109
  for (let i = 0; i < rows.length; i += 1) {
71
110
  rows[i] = rows[i].toJSON();
@@ -76,4 +115,4 @@ function Main(cnf, deps, utils) {
76
115
  return { modify, add, remove, list, stats: (0, stats_1.Stats)(cnf, deps, utils) };
77
116
  }
78
117
  exports.Main = Main;
79
- exports.Deps = ["errors"];
118
+ exports.Deps = ["errors", "_", "moment", "mysql", "Sequelize"];
@@ -1,6 +1,13 @@
1
+ import * as _ from "lodash";
2
+ import * as Sequelize from "sequelize";
1
3
  import { Params, ModelExtraAtts, TModel } from "./defines";
2
4
  import { Utils } from "./utils";
3
- export declare function Stats(cnf: {}, deps: {}, utils: ReturnType<typeof Utils>): (Model: TModel, params: Params, where: any, conf?: ModelExtraAtts["stats"]) => Promise<{
5
+ interface Deps {
6
+ _: typeof _;
7
+ Sequelize: Pick<typeof Sequelize, "literal" | "and" | "fn">;
8
+ }
9
+ export declare function Stats(cnf: {}, deps: Deps, utils: ReturnType<typeof Utils>): (Model: TModel, params: Params, where?: any, conf?: ModelExtraAtts["stats"]) => Promise<{
4
10
  count: number;
5
11
  rows: any;
6
12
  }>;
13
+ export {};
@@ -1,14 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Stats = void 0;
4
- const _ = require("lodash");
5
- const Sequelize = require("sequelize");
6
4
  function Stats(cnf, deps, utils) {
7
5
  const defaultPagination = {
8
6
  maxResults: 10,
9
7
  maxStartIndex: 10000,
10
8
  maxResultsLimit: 5000,
11
9
  };
10
+ const { _, Sequelize } = deps;
12
11
  // 获取统计的条目数
13
12
  const statsCount = async (Model, opts, dims) => {
14
13
  if (!dims)
@@ -100,6 +99,14 @@ function Stats(cnf, deps, utils) {
100
99
  const pagination = ((_a = Model.stats) === null || _a === void 0 ? void 0 : _a.pagination) || defaultPagination;
101
100
  return utils.pageParams(pagination, params);
102
101
  };
102
+ /**
103
+ * Restful stats method
104
+ * @param Model Model definition of resources
105
+ * @param params parameters for updating
106
+ * @param where Initial where condition
107
+ * @param conf Model stats conf
108
+ * @returns Stats result object has two propoties, count and rows
109
+ */
103
110
  const statistics = async (Model, params, where, conf) => {
104
111
  if (!conf)
105
112
  throw Error("Model.stats undefined");
@@ -1,3 +1,7 @@
1
+ import * as _ from "lodash";
2
+ import * as mysql from "mysql2";
3
+ import * as Sequelize from "sequelize";
4
+ import * as moment from "moment";
1
5
  import { ModelExtraAtts, TModel, Params } from "./defines";
2
6
  interface Cnf {
3
7
  rest: {
@@ -5,6 +9,10 @@ interface Cnf {
5
9
  };
6
10
  }
7
11
  interface Deps {
12
+ _: typeof _;
13
+ mysql: Pick<typeof mysql, "escape">;
14
+ moment: typeof moment extends (...args: infer A) => infer B ? (...args: A) => B : never;
15
+ Sequelize: Pick<typeof Sequelize, "where" | "fn" | "col" | "literal" | "Op">;
8
16
  errors: {
9
17
  notAllowed: (...args: any[]) => Error;
10
18
  resourceDuplicateAdd: (...args: any[]) => Error;
@@ -3,11 +3,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Utils = void 0;
4
4
  const _ = require("lodash");
5
5
  const mysql = require("mysql2");
6
- const Sequelize = require("sequelize");
7
- const moment = require("moment");
8
6
  function Utils(cnf, deps) {
9
7
  const { rest: { relativeMaxRangeDays: RELATIVE_MAX_RANGE = 100 }, } = cnf;
10
- const { errors } = deps;
8
+ const { errors, moment, Sequelize } = deps;
11
9
  /**
12
10
  * 相对多少天的时间
13
11
  * @param Number days 相对多少天
@@ -1,11 +1,26 @@
1
- import Ajv, { Schema } from "ajv";
1
+ import * as ajv from "ajv";
2
+ import addFormats from "ajv-formats";
2
3
  interface Cnf {
3
- schema?: ConstructorParameters<typeof Ajv>[0];
4
+ schema?: ConstructorParameters<typeof ajv.default>[0];
4
5
  }
5
- export declare function Main(cnf: Cnf): Readonly<{
6
+ interface Deps {
7
+ ajv: {
8
+ default: typeof ajv.default;
9
+ };
10
+ ajvFormats: typeof addFormats;
11
+ }
12
+ declare type Schema = ajv.Schema;
13
+ /**
14
+ * JSON schema validation module, based on Ajv: https://www.npmjs.com/package/ajv
15
+ * @param cnf Ajv initialization parameters
16
+ * @returns auto, validate, complie, ajv
17
+ */
18
+ export declare function Main(cnf: Cnf, deps: Deps): Readonly<{
6
19
  auto: <F extends (...args: any[]) => any>(fn: F, schema: Schema[], errorFn: Function, extra: any) => (...args: Parameters<F>) => ReturnType<F>;
7
20
  validate: (schema: Schema, data: any) => boolean;
8
- compile: (x: Schema) => import("ajv").ValidateFunction<unknown>;
9
- ajv: Ajv;
21
+ compile: (schema: Schema) => ajv.ValidateFunction<unknown>;
22
+ /** intance of Ajv */
23
+ ajv: ajv.default;
10
24
  }>;
25
+ export declare const Deps: string[];
11
26
  export {};
@@ -1,19 +1,33 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Main = void 0;
3
+ exports.Deps = exports.Main = void 0;
4
4
  const util = require("util");
5
- const ajv_1 = require("ajv");
6
- const ajv_formats_1 = require("ajv-formats");
7
- function Main(cnf) {
8
- const ajv = new ajv_1.default(cnf.schema || {});
9
- (0, ajv_formats_1.default)(ajv);
10
- const compile = (x) => ajv.compile(x);
5
+ /**
6
+ * JSON schema validation module, based on Ajv: https://www.npmjs.com/package/ajv
7
+ * @param cnf Ajv initialization parameters
8
+ * @returns auto, validate, complie, ajv
9
+ */
10
+ function Main(cnf, deps) {
11
+ const { ajv: { default: Ajv }, ajvFormats, } = deps;
12
+ const ajv = new Ajv(cnf.schema || {});
13
+ ajvFormats(ajv);
11
14
  /**
12
- * 将函数处理为自动校验参数合法性
15
+ * Ajv complie function
16
+ * @param schema Definition of data format, Ajv specification
17
+ * @returns Verification function
18
+ */
19
+ const compile = (schema) => ajv.compile(schema);
20
+ /**
21
+ * Automatically process functions as functions with parameter validate
22
+ * @param fn Function to be processed
23
+ * @param schema Format definition of function parameters, Ajv specification
24
+ * @param errorFn Error handling function
25
+ * @param extra Additional information passed to the error function
26
+ * @returns Processed function
13
27
  */
14
28
  function auto(fn, schema, errorFn, extra) {
15
29
  if (!Array.isArray(schema)) {
16
- throw Error(`方法参数定义必须是一个数组 ${util.format(schema)}`);
30
+ throw Error(`Method arguments must be an array: ${util.format(schema)}`);
17
31
  }
18
32
  const validators = schema.map((x) => ajv.compile(x));
19
33
  return (...args) => {
@@ -27,13 +41,23 @@ function Main(cnf) {
27
41
  };
28
42
  }
29
43
  /**
30
- * 检测数据是否符合 schema 设定
44
+ * Verification functoin
45
+ * @param schema Definition of data format, Ajv specification
46
+ * @param data Data to be verified
47
+ * @returns ture or throw ajv.errors
31
48
  */
32
49
  const validate = (schema, data) => {
33
50
  if (ajv.validate(schema, data))
34
51
  return true;
35
52
  throw ajv.errors;
36
53
  };
37
- return Object.freeze({ auto, validate, compile, ajv });
54
+ return Object.freeze({
55
+ auto,
56
+ validate,
57
+ compile,
58
+ /** intance of Ajv */
59
+ ajv,
60
+ });
38
61
  }
39
62
  exports.Main = Main;
63
+ exports.Deps = ["ajv", "ajvFormats"];
@@ -4,8 +4,13 @@ interface Cnf {
4
4
  [propName: string]: Sequelize.Options;
5
5
  };
6
6
  }
7
- export declare function Main(cnf: Cnf): {
7
+ interface Deps {
8
+ Sequelize: {
9
+ Sequelize: typeof Sequelize.Sequelize;
10
+ };
11
+ }
12
+ export declare function Main(cnf: Cnf, deps: Deps): {
8
13
  [propName: string]: Sequelize.Sequelize;
9
14
  };
10
- export declare const Deps: never[];
15
+ export declare const Deps: string[];
11
16
  export {};
@@ -1,17 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Deps = exports.Main = void 0;
4
- const Sequelize = require("sequelize");
5
- function Main(cnf) {
4
+ function Main(cnf, deps) {
6
5
  // 这里之所以要注入 Sequelize 是为了保证项目自身可以灵活选择自己的 Sequelize 版本, 这样改公共模块就会更加稳定, 避免频繁升级
7
6
  const { sequelize: dbs } = cnf;
7
+ const { Sequelize } = deps;
8
8
  const sequelizes = {};
9
9
  for (const k of Object.keys(dbs)) {
10
10
  const db = dbs[k];
11
- // sequelizes[k] = new Sequelize(db.name, db.user, db.pass, db);
12
11
  sequelizes[k] = new Sequelize.Sequelize(db);
13
12
  }
14
13
  return sequelizes;
15
14
  }
16
15
  exports.Main = Main;
17
- exports.Deps = [];
16
+ exports.Deps = ["Sequelize"];
@@ -1,20 +1,45 @@
1
+ /** Objects to be encrypted */
1
2
  export interface Opt {
3
+ /** The URI does not contain the root path part */
2
4
  uri: string;
5
+ /** Key for signature calculation */
3
6
  key: string;
7
+ /** Second timestamp */
4
8
  timestamp: number;
9
+ /** Signature algorithm, fixed as hmacsha256 */
5
10
  signMethod: "HmacSHA256";
11
+ /** Signature version, fixed as 1 */
6
12
  signVersion: "1";
13
+ /** Method name of the request interface, internal domain method name, not HTTP verb */
7
14
  method: string;
8
15
  }
16
+ /**
17
+ * API interface encryption signature algorithm module, based on sha256
18
+ * @returns generator And request Methods
19
+ */
9
20
  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";
21
+ /**
22
+ * Core encryption algorithm, the result is returned as Base64 string
23
+ * @param opt Objects to be encrypted
24
+ * @param secret Calculate the private key of the signature
25
+ * @returns The result of the signature is in the format of Base64 string
26
+ */
27
+ generator(opt: Opt, secret: string): string;
28
+ /**
29
+ * Get all the signature encryption information required for a request
30
+ * @param uri The URI does not contain the root path part
31
+ * @param method Method name of the request interface, internal domain method name not HTTP verb
32
+ * @param key Key for signature calculation
33
+ * @param secret Calculate the private key of the signature
34
+ * @returns
35
+ */
36
+ request(uri: string, method: string, key: string, secret: string): {
37
+ readonly "x-auth-signature": string;
38
+ readonly "x-auth-key": string;
39
+ readonly "x-auth-method": string;
40
+ readonly "x-auth-timestamp": number;
41
+ readonly "x-auth-sign-method": "HmacSHA256";
42
+ readonly "x-auth-sign-version": "1";
18
43
  };
19
44
  };
20
45
  export declare const Deps: never[];