@eggjs/tegg-ajv-plugin 3.36.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2017-present Alibaba Group Holding Limited and other contributors.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,144 @@
1
+ # @eggjs/tegg-ajv-plugin
2
+
3
+ 参考 [egg-typebox-validate](https://github.com/xiekw2010/egg-typebox-validate) 的最佳实践,结合 ajv + typebox,只需要定义一次参数类型和规则,就能同时拥有参数校验和类型定义(完整的 ts 类型提示)。
4
+
5
+ ## egg 模式
6
+
7
+ ### Install
8
+
9
+ ```shell
10
+ # tegg 注解
11
+ npm i --save @eggjs/tegg
12
+ # tegg 插件
13
+ npm i --save @eggjs/tegg-plugin
14
+ # tegg ajv 插件
15
+ npm i --save @eggjs/tegg-ajv-plugin
16
+ ```
17
+
18
+ ### Prepare
19
+
20
+ ```json
21
+ // tsconfig.json
22
+ {
23
+ "extends": "@eggjs/tsconfig"
24
+ }
25
+ ```
26
+
27
+ ### Config
28
+
29
+ ```js
30
+ // config/plugin.js
31
+ exports.tegg = {
32
+ package: '@eggjs/tegg-plugin',
33
+ enable: true,
34
+ };
35
+
36
+ exports.teggAjv = {
37
+ package: '@eggjs/tegg-ajv-plugin',
38
+ enable: true,
39
+ };
40
+ ```
41
+
42
+ ## standalone 模式
43
+
44
+ ### Install
45
+
46
+ ```shell
47
+ # tegg 注解
48
+ npm i --save @eggjs/tegg
49
+ # tegg ajv 插件
50
+ npm i --save @eggjs/tegg-ajv-plugin
51
+ ```
52
+
53
+ ### Prepare
54
+
55
+ ```json
56
+ // tsconfig.json
57
+ {
58
+ "extends": "@eggjs/tsconfig"
59
+ }
60
+ ```
61
+
62
+ ## Usage
63
+
64
+ 1、定义入参校验 Schema
65
+
66
+ 使用 typebox 定义,会内置到 tegg 导出
67
+
68
+ ```ts
69
+ import { Type, TransformEnum } from '@eggjs/tegg/ajv';
70
+
71
+ const SyncPackageTaskSchema = Type.Object({
72
+ fullname: Type.String({
73
+ transform: [ TransformEnum.trim ],
74
+ maxLength: 100,
75
+ }),
76
+ tips: Type.String({
77
+ transform: [ TransformEnum.trim ],
78
+ maxLength: 1024,
79
+ }),
80
+ skipDependencies: Type.Boolean(),
81
+ syncDownloadData: Type.Boolean(),
82
+ // force sync immediately, only allow by admin
83
+ force: Type.Boolean(),
84
+ // sync history version
85
+ forceSyncHistory: Type.Boolean(),
86
+ // source registry
87
+ registryName: Type.Optional(Type.String()),
88
+ });
89
+ ```
90
+
91
+ 2、从校验 Schema 生成静态的入参类型
92
+
93
+ ```ts
94
+ import { Static } from '@eggjs/tegg/ajv';
95
+
96
+ type SyncPackageTaskType = Static<typeof SyncPackageTaskSchema>;
97
+ ```
98
+
99
+ 3、在 Controller 中使用入参类型和校验 Schema
100
+
101
+ 注入全局单例 ajv,调用 `ajv.validate(XxxSchema, params)` 进行参数校验,参数校验失败会直接抛出 `AjvInvalidParamError` 异常,
102
+ tegg 会自动返回相应的错误响应给客户端。
103
+
104
+ ```ts
105
+ import { Inject, HTTPController, HTTPMethod, HTTPMethodEnum, HTTPBody } from '@eggjs/tegg';
106
+ import { Ajv, Type, Static, TransformEnum } from '@eggjs/tegg/ajv';
107
+
108
+ const SyncPackageTaskSchema = Type.Object({
109
+ fullname: Type.String({
110
+ transform: [ TransformEnum.trim ],
111
+ maxLength: 100,
112
+ }),
113
+ tips: Type.String({
114
+ transform: [ TransformEnum.trim ],
115
+ maxLength: 1024,
116
+ }),
117
+ skipDependencies: Type.Boolean(),
118
+ syncDownloadData: Type.Boolean(),
119
+ // force sync immediately, only allow by admin
120
+ force: Type.Boolean(),
121
+ // sync history version
122
+ forceSyncHistory: Type.Boolean(),
123
+ // source registry
124
+ registryName: Type.Optional(Type.String()),
125
+ });
126
+
127
+ type SyncPackageTaskType = Static<typeof SyncPackageTaskSchema>;
128
+
129
+ @HTTPController()
130
+ export class HelloController {
131
+ private readonly ajv: Ajv;
132
+
133
+ @HTTPMethod({
134
+ method: HTTPMethodEnum.POST,
135
+ path: '/sync',
136
+ })
137
+ async sync(@HTTPBody() task: SyncPackageTaskType) {
138
+ this.ajv.validate(SyncPackageTaskSchema, task);
139
+ return {
140
+ task,
141
+ };
142
+ }
143
+ }
144
+ ```
package/lib/Ajv.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { type Schema } from 'ajv/dist/2019';
2
+ import { type Ajv as IAjv, AjvInvalidParamError } from '@eggjs/tegg/ajv';
3
+ export declare class Ajv implements IAjv {
4
+ #private;
5
+ static InvalidParamErrorClass: typeof AjvInvalidParamError;
6
+ protected _init(): void;
7
+ /**
8
+ * Validate data with typebox Schema.
9
+ *
10
+ * If validate fail, with throw `Ajv.InvalidParamErrorClass`
11
+ */
12
+ validate(schema: Schema, data: unknown): void;
13
+ }
package/lib/Ajv.js ADDED
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
12
+ if (kind === "m") throw new TypeError("Private method is not writable");
13
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
14
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
15
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
16
+ };
17
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
18
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
19
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
20
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
21
+ };
22
+ var __importDefault = (this && this.__importDefault) || function (mod) {
23
+ return (mod && mod.__esModule) ? mod : { "default": mod };
24
+ };
25
+ var _Ajv_ajvInstance;
26
+ var Ajv_1;
27
+ Object.defineProperty(exports, "__esModule", { value: true });
28
+ exports.Ajv = void 0;
29
+ const _2019_1 = __importDefault(require("ajv/dist/2019"));
30
+ const ajv_formats_1 = __importDefault(require("ajv-formats"));
31
+ const ajv_keywords_1 = __importDefault(require("ajv-keywords"));
32
+ const ajv_1 = require("@eggjs/tegg/ajv");
33
+ const tegg_1 = require("@eggjs/tegg");
34
+ let Ajv = Ajv_1 = class Ajv {
35
+ constructor() {
36
+ _Ajv_ajvInstance.set(this, void 0);
37
+ }
38
+ _init() {
39
+ __classPrivateFieldSet(this, _Ajv_ajvInstance, new _2019_1.default(), "f");
40
+ (0, ajv_keywords_1.default)(__classPrivateFieldGet(this, _Ajv_ajvInstance, "f"), 'transform');
41
+ (0, ajv_formats_1.default)(__classPrivateFieldGet(this, _Ajv_ajvInstance, "f"), [
42
+ 'date-time',
43
+ 'time',
44
+ 'date',
45
+ 'email',
46
+ 'hostname',
47
+ 'ipv4',
48
+ 'ipv6',
49
+ 'uri',
50
+ 'uri-reference',
51
+ 'uuid',
52
+ 'uri-template',
53
+ 'json-pointer',
54
+ 'relative-json-pointer',
55
+ 'regex',
56
+ ])
57
+ .addKeyword('kind')
58
+ .addKeyword('modifier');
59
+ }
60
+ /**
61
+ * Validate data with typebox Schema.
62
+ *
63
+ * If validate fail, with throw `Ajv.InvalidParamErrorClass`
64
+ */
65
+ validate(schema, data) {
66
+ const result = __classPrivateFieldGet(this, _Ajv_ajvInstance, "f").validate(schema, data);
67
+ if (!result) {
68
+ throw new Ajv_1.InvalidParamErrorClass('Validation Failed', {
69
+ errorData: data,
70
+ currentSchema: JSON.stringify(schema),
71
+ errors: __classPrivateFieldGet(this, _Ajv_ajvInstance, "f").errors,
72
+ });
73
+ }
74
+ }
75
+ };
76
+ exports.Ajv = Ajv;
77
+ _Ajv_ajvInstance = new WeakMap();
78
+ Ajv.InvalidParamErrorClass = ajv_1.AjvInvalidParamError;
79
+ __decorate([
80
+ (0, tegg_1.LifecycleInit)(),
81
+ __metadata("design:type", Function),
82
+ __metadata("design:paramtypes", []),
83
+ __metadata("design:returntype", void 0)
84
+ ], Ajv.prototype, "_init", null);
85
+ exports.Ajv = Ajv = Ajv_1 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JBQWEsQ0FBQyxRQUFRLENBQUMsTUFBTSxFQUFFLElBQUksQ0FBQyxDQUFDO1FBQ3hELElBQUksQ0FBQyxNQUFNLEVBQUUsQ0FBQztZQUNaLE1BQU0sSUFBSSxLQUFHLENBQUMsc0JBQXNCLENBQUMsbUJBQW1CLEVBQUU7Z0JBQ3hELFNBQVMsRUFBRSxJQUFJO2dCQUNmLGFBQWEsRUFBRSxJQUFJLENBQUMsU0FBUyxDQUFDLE1BQU0sQ0FBQztnQkFDckMsTUFBTSxFQUFFLHVCQUFBLElBQUksd0JBQWEsQ0FBQyxNQUFPO2FBQ2xDLENBQUMsQ0FBQztRQUNMLENBQUM7SUFDSCxDQUFDOztBQTNDVSxrQkFBRzs7QUFDUCwwQkFBc0IsR0FBRywwQkFBb0IsQUFBdkIsQ0FBd0I7QUFLM0M7SUFEVCxJQUFBLG9CQUFhLEdBQUU7Ozs7Z0NBc0JmO2NBM0JVLEdBQUc7SUFIZixJQUFBLHFCQUFjLEVBQUM7UUFDZCxXQUFXLEVBQUUsa0JBQVcsQ0FBQyxNQUFNO0tBQ2hDLENBQUM7R0FDVyxHQUFHLENBNENmIn0=
package/package.json ADDED
@@ -0,0 +1,72 @@
1
+ {
2
+ "name": "@eggjs/tegg-ajv-plugin",
3
+ "eggPlugin": {
4
+ "name": "teggAjv",
5
+ "strict": false,
6
+ "dependencies": [
7
+ "tegg"
8
+ ]
9
+ },
10
+ "eggModule": {
11
+ "name": "teggAjv"
12
+ },
13
+ "version": "3.36.0",
14
+ "description": "ajv plugin for egg and tegg",
15
+ "keywords": [
16
+ "egg",
17
+ "plugin",
18
+ "typescript",
19
+ "module",
20
+ "tegg",
21
+ "ajv"
22
+ ],
23
+ "files": [
24
+ "lib/**/*.js",
25
+ "lib/**/*.d.ts",
26
+ "typings/*.d.ts"
27
+ ],
28
+ "types": "typings/index.d.ts",
29
+ "scripts": {
30
+ "test": "cross-env NODE_ENV=test NODE_OPTIONS='--no-deprecation' mocha",
31
+ "clean": "tsc -b --clean",
32
+ "tsc": "npm run clean && tsc -p ./tsconfig.json",
33
+ "tsc:pub": "npm run clean && tsc -p ./tsconfig.pub.json",
34
+ "prepublishOnly": "npm run tsc:pub"
35
+ },
36
+ "homepage": "https://github.com/eggjs/tegg",
37
+ "bugs": {
38
+ "url": "https://github.com/eggjs/tegg/issues"
39
+ },
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "git@github.com:eggjs/tegg.git",
43
+ "directory": "plugin/ajv"
44
+ },
45
+ "engines": {
46
+ "node": ">=16.0.0"
47
+ },
48
+ "dependencies": {
49
+ "@eggjs/tegg": "^3.36.0",
50
+ "@sinclair/typebox": "^0.32.20",
51
+ "ajv": "^8.12.0",
52
+ "ajv-formats": "^3.0.1",
53
+ "ajv-keywords": "^5.1.0"
54
+ },
55
+ "devDependencies": {
56
+ "@eggjs/tegg-config": "^3.36.0",
57
+ "@eggjs/tegg-controller-plugin": "^3.36.0",
58
+ "@eggjs/tegg-plugin": "^3.36.0",
59
+ "@types/mocha": "^10.0.1",
60
+ "@types/node": "^20.2.4",
61
+ "cross-env": "^7.0.3",
62
+ "egg": "^3.9.1",
63
+ "egg-mock": "^5.5.0",
64
+ "mocha": "^10.2.0",
65
+ "ts-node": "^10.9.1",
66
+ "typescript": "^5.0.4"
67
+ },
68
+ "publishConfig": {
69
+ "access": "public"
70
+ },
71
+ "gitHead": "b550d59a21f7c9991310ca6b6fd16ee581a5e17d"
72
+ }
@@ -0,0 +1,4 @@
1
+ import 'egg';
2
+ import '@eggjs/tegg-plugin';
3
+ import '@eggjs/tegg-config';
4
+ import '@eggjs/tegg-controller-plugin';