@faasjs/http 0.0.2-beta.302 → 0.0.2-beta.314

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/dist/index.mjs ADDED
@@ -0,0 +1,498 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined")
5
+ return require.apply(this, arguments);
6
+ throw new Error('Dynamic require of "' + x + '" is not supported');
7
+ });
8
+
9
+ // src/index.ts
10
+ import {
11
+ usePlugin
12
+ } from "@faasjs/func";
13
+ import { deepMerge as deepMerge2 } from "@faasjs/deep_merge";
14
+ import { Logger } from "@faasjs/logger";
15
+
16
+ // src/session.ts
17
+ import {
18
+ randomBytes,
19
+ pbkdf2Sync,
20
+ createCipheriv,
21
+ createHmac,
22
+ createDecipheriv
23
+ } from "crypto";
24
+ var Session = class {
25
+ constructor(cookie, config) {
26
+ this.cookie = cookie;
27
+ this.config = Object.assign({
28
+ key: "key",
29
+ secret: randomBytes(128).toString("hex"),
30
+ salt: "salt",
31
+ signedSalt: "signedSalt",
32
+ keylen: 64,
33
+ iterations: 100,
34
+ digest: "sha256",
35
+ cipherName: "aes-256-cbc"
36
+ }, config);
37
+ this.secret = pbkdf2Sync(this.config.secret, this.config.salt, this.config.iterations, this.config.keylen / 2, this.config.digest);
38
+ this.signedSecret = pbkdf2Sync(this.config.secret, this.config.signedSalt, this.config.iterations, this.config.keylen, this.config.digest);
39
+ this.content = Object.create(null);
40
+ }
41
+ invoke(cookie) {
42
+ try {
43
+ this.content = cookie ? this.decode(cookie) : Object.create(null);
44
+ } catch (error) {
45
+ console.error(error);
46
+ this.content = Object.create(null);
47
+ }
48
+ this.changed = false;
49
+ }
50
+ encode(text) {
51
+ if (typeof text !== "string")
52
+ text = JSON.stringify(text);
53
+ const iv = randomBytes(16);
54
+ const cipher = createCipheriv(this.config.cipherName, this.secret, iv);
55
+ const encrypted = Buffer.concat([cipher.update(text), cipher.final()]).toString("base64");
56
+ const main = Buffer.from([encrypted, iv.toString("base64")].join("--")).toString("base64");
57
+ const hmac = createHmac(this.config.digest, this.signedSecret);
58
+ hmac.update(main);
59
+ const digest = hmac.digest("hex");
60
+ return main + "--" + digest;
61
+ }
62
+ decode(text) {
63
+ text = decodeURIComponent(text);
64
+ const signedParts = text.split("--");
65
+ const hmac = createHmac(this.config.digest, this.signedSecret);
66
+ hmac.update(signedParts[0]);
67
+ const digest = hmac.digest("hex");
68
+ if (signedParts[1] !== digest)
69
+ throw Error("Not valid");
70
+ const message = Buffer.from(signedParts[0], "base64").toString();
71
+ const parts = message.split("--").map(function(part2) {
72
+ return Buffer.from(part2, "base64");
73
+ });
74
+ const cipher = createDecipheriv(this.config.cipherName, this.secret, parts[1]);
75
+ const part = Buffer.from(cipher.update(parts[0])).toString("utf8");
76
+ const final = cipher.final("utf8");
77
+ const decrypt = [part, final].join("");
78
+ return JSON.parse(decrypt);
79
+ }
80
+ read(key) {
81
+ return this.content[key];
82
+ }
83
+ write(key, value) {
84
+ if (value === null || typeof value === "undefined")
85
+ delete this.content[key];
86
+ else
87
+ this.content[key] = value;
88
+ this.changed = true;
89
+ return this;
90
+ }
91
+ update() {
92
+ if (this.changed)
93
+ this.cookie.write(this.config.key, this.encode(JSON.stringify(this.content)));
94
+ return this;
95
+ }
96
+ };
97
+
98
+ // src/cookie.ts
99
+ import { deepMerge } from "@faasjs/deep_merge";
100
+ var Cookie = class {
101
+ constructor(config) {
102
+ this.config = deepMerge({
103
+ path: "/",
104
+ expires: 31536e3,
105
+ secure: true,
106
+ httpOnly: true,
107
+ session: {}
108
+ }, config);
109
+ this.session = new Session(this, this.config.session);
110
+ this.content = Object.create(null);
111
+ this.setCookie = Object.create(null);
112
+ }
113
+ invoke(cookie) {
114
+ this.content = Object.create(null);
115
+ if (cookie)
116
+ cookie.split(";").forEach((x) => {
117
+ x = x.trim();
118
+ const k = /([^=]+)/.exec(x);
119
+ if (k !== null)
120
+ this.content[k[0]] = decodeURIComponent(x.replace(`${k[0]}=`, "").replace(/;$/, ""));
121
+ });
122
+ this.setCookie = Object.create(null);
123
+ this.session.invoke(this.read(this.session.config.key));
124
+ return this;
125
+ }
126
+ read(key) {
127
+ return this.content[key];
128
+ }
129
+ write(key, value, opts) {
130
+ opts = Object.assign(this.config, opts || {});
131
+ let cookie;
132
+ if (value === null || typeof value === "undefined") {
133
+ opts.expires = "Thu, 01 Jan 1970 00:00:01 GMT";
134
+ cookie = `${key}=;`;
135
+ delete this.content[key];
136
+ } else {
137
+ cookie = `${key}=${encodeURIComponent(value)};`;
138
+ this.content[key] = value;
139
+ }
140
+ if (typeof opts.expires === "number")
141
+ cookie += `max-age=${opts.expires};`;
142
+ else if (typeof opts.expires === "string")
143
+ cookie += `expires=${opts.expires};`;
144
+ cookie += `path=${opts.path || "/"};`;
145
+ if (opts.domain)
146
+ cookie += `domain=${opts.domain};`;
147
+ if (opts.secure)
148
+ cookie += "Secure;";
149
+ if (opts.httpOnly)
150
+ cookie += "HttpOnly;";
151
+ if (opts.sameSite)
152
+ cookie += `SameSite=${opts.sameSite};`;
153
+ this.setCookie[key] = cookie;
154
+ return this;
155
+ }
156
+ headers() {
157
+ if (Object.keys(this.setCookie).length === 0)
158
+ return {};
159
+ else
160
+ return { "Set-Cookie": Object.values(this.setCookie) };
161
+ }
162
+ };
163
+
164
+ // src/validator.ts
165
+ var Validator = class {
166
+ constructor(config, logger) {
167
+ this.paramsConfig = config.params;
168
+ this.cookieConfig = config.cookie;
169
+ this.sessionConfig = config.session;
170
+ this.before = config.before;
171
+ this.logger = logger;
172
+ }
173
+ async valid(request) {
174
+ if (this.before) {
175
+ const result = await this.before(request);
176
+ if (result)
177
+ throw new HttpError(result);
178
+ }
179
+ this.request = request;
180
+ if (this.paramsConfig && request.params) {
181
+ this.logger.debug("Valid Params");
182
+ this.validContent("params", request.params, "", this.paramsConfig);
183
+ }
184
+ if (this.cookieConfig && request.cookie) {
185
+ this.logger.debug("Valid Cookie");
186
+ if (request.cookie == null)
187
+ throw Error("Not found Cookie");
188
+ this.validContent("cookie", request.cookie.content, "", this.cookieConfig);
189
+ }
190
+ if (this.sessionConfig && request.session) {
191
+ this.logger.debug("Valid Session");
192
+ if (request.session == null)
193
+ throw Error("Not found Session");
194
+ this.validContent("session", request.session.content, "", this.sessionConfig);
195
+ }
196
+ }
197
+ validContent(type, params, baseKey, config) {
198
+ if (config.whitelist) {
199
+ const paramsKeys = Object.keys(params);
200
+ const rulesKeys = Object.keys(config.rules);
201
+ const diff = paramsKeys.filter((k) => !rulesKeys.includes(k));
202
+ if (diff.length > 0) {
203
+ if (config.whitelist === "error") {
204
+ const diffKeys = diff.map((k) => `${baseKey}${k}`);
205
+ const error = Error(`[${type}] Not permitted keys: ${diffKeys.join(", ")}`);
206
+ if (config.onError) {
207
+ const res = config.onError(`${type}.whitelist`, baseKey, diffKeys);
208
+ if (res)
209
+ throw new HttpError(res);
210
+ }
211
+ throw error;
212
+ } else if (config.whitelist === "ignore")
213
+ for (const key of diff)
214
+ delete params[key];
215
+ }
216
+ }
217
+ for (const key in config.rules) {
218
+ const rule = config.rules[key];
219
+ if (!rule)
220
+ continue;
221
+ let value = params[key];
222
+ if (rule.default) {
223
+ if (type === "cookie" || type === "session")
224
+ this.logger.warn("Cookie and Session not support default rule.");
225
+ else if (typeof value === "undefined" && rule.default) {
226
+ value = typeof rule.default === "function" ? rule.default(this.request) : rule.default;
227
+ params[key] = value;
228
+ }
229
+ }
230
+ if (rule.required) {
231
+ if (typeof value === "undefined" || value === null) {
232
+ const error = Error(`[${type}] ${baseKey}${key} is required.`);
233
+ if (config.onError) {
234
+ const res = config.onError(`${type}.rule.required`, `${baseKey}${key}`, value);
235
+ if (res)
236
+ throw new HttpError(res);
237
+ }
238
+ throw error;
239
+ }
240
+ }
241
+ if (typeof value !== "undefined" && value !== null) {
242
+ if (rule.type)
243
+ if (type === "cookie")
244
+ this.logger.warn("Cookie not support type rule");
245
+ else {
246
+ let typed = true;
247
+ switch (rule.type) {
248
+ case "array":
249
+ typed = Array.isArray(value);
250
+ break;
251
+ case "object":
252
+ typed = Object.prototype.toString.call(value) === "[object Object]";
253
+ break;
254
+ default:
255
+ typed = typeof value === rule.type;
256
+ break;
257
+ }
258
+ if (!typed) {
259
+ const error = Error(`[${type}] ${baseKey}${key} must be a ${rule.type}.`);
260
+ if (config.onError) {
261
+ const res = config.onError(`${type}.rule.type`, `${baseKey}${key}`, value);
262
+ if (res)
263
+ throw new HttpError(res);
264
+ }
265
+ throw error;
266
+ }
267
+ }
268
+ if (rule.in && !rule.in.includes(value)) {
269
+ const error = Error(`[${type}] ${baseKey}${key} must be in ${rule.in.join(", ")}.`);
270
+ if (config.onError) {
271
+ const res = config.onError(`${type}.rule.in`, `${baseKey}${key}`, value);
272
+ if (res)
273
+ throw new HttpError(res);
274
+ }
275
+ throw error;
276
+ }
277
+ if (rule.config) {
278
+ if (type === "cookie")
279
+ this.logger.warn("Cookie not support nest rule.");
280
+ else if (Array.isArray(value))
281
+ for (const val of value)
282
+ this.validContent(type, val, baseKey ? `${baseKey}.${key}.` : `${key}.`, rule.config);
283
+ else if (typeof value === "object")
284
+ this.validContent(type, value, baseKey ? `${baseKey}.${key}.` : `${key}.`, rule.config);
285
+ }
286
+ }
287
+ }
288
+ }
289
+ };
290
+
291
+ // src/index.ts
292
+ import {
293
+ gzipSync,
294
+ deflateSync,
295
+ brotliCompressSync
296
+ } from "zlib";
297
+ var ContentType = {
298
+ plain: "text/plain",
299
+ html: "text/html",
300
+ xml: "application/xml",
301
+ csv: "text/csv",
302
+ css: "text/css",
303
+ javascript: "application/javascript",
304
+ json: "application/json",
305
+ jsonp: "application/javascript"
306
+ };
307
+ var HttpError = class extends Error {
308
+ constructor({
309
+ statusCode,
310
+ message
311
+ }) {
312
+ super(message);
313
+ if (Error.captureStackTrace)
314
+ Error.captureStackTrace(this, HttpError);
315
+ this.statusCode = statusCode || 500;
316
+ this.message = message;
317
+ }
318
+ };
319
+ var Name = "http";
320
+ var Http = class {
321
+ constructor(config) {
322
+ this.type = Name;
323
+ this.name = Name;
324
+ this.name = (config == null ? void 0 : config.name) || this.type;
325
+ this.config = (config == null ? void 0 : config.config) || Object.create(null);
326
+ if (config == null ? void 0 : config.validator)
327
+ this.validatorOptions = config.validator;
328
+ this.logger = new Logger(this.name);
329
+ this.headers = Object.create(null);
330
+ this.cookie = new Cookie(this.config.cookie || {});
331
+ this.session = this.cookie.session;
332
+ }
333
+ async onDeploy(data, next) {
334
+ var _a;
335
+ await next();
336
+ this.logger.debug("\u7EC4\u88C5\u7F51\u5173\u914D\u7F6E");
337
+ this.logger.debug("%j", data);
338
+ const config = data.config.plugins ? deepMerge2(data.config.plugins[this.name || this.type], { config: this.config }) : { config: this.config };
339
+ if (!config.config.path) {
340
+ config.config.path = "/" + ((_a = data.name) == null ? void 0 : _a.replace(/_/g, "/").replace(/\/index$/, ""));
341
+ if (config.config.path === "/index")
342
+ config.config.path = "/";
343
+ if (config.config.ignorePathPrefix) {
344
+ config.config.path = config.config.path.replace(new RegExp("^" + config.config.ignorePathPrefix), "");
345
+ if (config.config.path === "")
346
+ config.config.path = "/";
347
+ }
348
+ }
349
+ this.logger.debug("\u7EC4\u88C5\u5B8C\u6210 %j", config);
350
+ const Provider = __require(config.provider.type).Provider;
351
+ const provider = new Provider(config.provider.config);
352
+ await provider.deploy(this.type, data, config);
353
+ }
354
+ async onMount(data, next) {
355
+ this.logger.debug("[onMount] merge config");
356
+ if (data.config.plugins && data.config.plugins[this.name || this.type])
357
+ this.config = deepMerge2(this.config, data.config.plugins[this.name || this.type].config);
358
+ this.logger.debug("[onMount] prepare cookie & session");
359
+ this.cookie = new Cookie(this.config.cookie || {});
360
+ this.session = this.cookie.session;
361
+ if (this.validatorOptions) {
362
+ this.logger.debug("[onMount] prepare validator");
363
+ this.validator = new Validator(this.validatorOptions, this.logger);
364
+ }
365
+ await next();
366
+ }
367
+ async onInvoke(data, next) {
368
+ var _a, _b;
369
+ this.headers = data.event.headers || Object.create(null);
370
+ this.body = data.event.body;
371
+ this.params = Object.create(null);
372
+ this.response = { headers: Object.create(null) };
373
+ if (data.event.body) {
374
+ if (data.event.headers && data.event.headers["content-type"] && data.event.headers["content-type"].includes("application/json")) {
375
+ this.logger.debug("[onInvoke] Parse params from json body");
376
+ this.params = JSON.parse(data.event.body);
377
+ } else {
378
+ this.logger.debug("[onInvoke] Parse params from raw body");
379
+ this.params = data.event.body;
380
+ }
381
+ this.logger.debug("[onInvoke] Params: %j", this.params);
382
+ } else if (data.event.queryString) {
383
+ this.logger.debug("[onInvoke] Parse params from queryString");
384
+ this.params = data.event.queryString;
385
+ this.logger.debug("[onInvoke] Params: %j", this.params);
386
+ }
387
+ this.cookie.invoke(this.headers.cookie);
388
+ if (this.headers.cookie) {
389
+ this.logger.debug("[onInvoke] Cookie: %j", this.cookie.content);
390
+ this.logger.debug("[onInvoke] Session: %j", this.session.content);
391
+ }
392
+ if (this.validator) {
393
+ this.logger.debug("[onInvoke] Valid request");
394
+ try {
395
+ await this.validator.valid({
396
+ headers: this.headers,
397
+ params: this.params,
398
+ cookie: this.cookie,
399
+ session: this.session
400
+ });
401
+ } catch (error) {
402
+ this.logger.error(error);
403
+ data.response = {
404
+ statusCode: error.statusCode || 500,
405
+ headers: { "Content-Type": "application/json; charset=utf-8" },
406
+ body: JSON.stringify({ error: { message: error.message } })
407
+ };
408
+ return;
409
+ }
410
+ }
411
+ try {
412
+ await next();
413
+ } catch (error) {
414
+ data.response = error;
415
+ }
416
+ this.session.update();
417
+ if (data.response)
418
+ if (data.response instanceof Error || ((_a = data.response.constructor) == null ? void 0 : _a.name) === "Error") {
419
+ this.logger.error(data.response);
420
+ this.response.body = JSON.stringify({ error: { message: data.response.message } });
421
+ try {
422
+ this.response.statusCode = data.response.statusCode || 500;
423
+ } catch (error) {
424
+ this.response.statusCode = 500;
425
+ }
426
+ } else if (Object.prototype.toString.call(data.response) === "[object Object]" && data.response.statusCode && data.response.headers)
427
+ this.response = data.response;
428
+ else
429
+ this.response.body = JSON.stringify({ data: data.response });
430
+ if (!this.response.statusCode)
431
+ this.response.statusCode = this.response.body ? 200 : 201;
432
+ this.response.headers = Object.assign({
433
+ "Content-Type": "application/json; charset=utf-8",
434
+ "Cache-Control": "no-cache, no-store"
435
+ }, this.cookie.headers(), this.response.headers);
436
+ data.response = this.response;
437
+ if (process.env.FaasMode === "local") {
438
+ this.logger.debug("[onInvoke] Response: %j", data.response);
439
+ return;
440
+ }
441
+ if (data.response.isBase64Encoded || typeof data.response.body !== "string" || !((_b = data.response.headers["Content-Type"]) == null ? void 0 : _b.includes("json")) || data.response.body.length < 100)
442
+ return;
443
+ const acceptEncoding = this.headers["accept-encoding"] || this.headers["Accept-Encoding"];
444
+ if (!acceptEncoding || !/(br|gzip|deflate)/.test(acceptEncoding))
445
+ return;
446
+ const originBody = data.response.body;
447
+ try {
448
+ if (acceptEncoding.includes("br")) {
449
+ data.response.headers["Content-Encoding"] = "br";
450
+ data.response.body = brotliCompressSync(originBody).toString("base64");
451
+ } else if (acceptEncoding.includes("gzip")) {
452
+ data.response.headers["Content-Encoding"] = "gzip";
453
+ data.response.body = gzipSync(originBody).toString("base64");
454
+ } else if (acceptEncoding.includes("deflate")) {
455
+ data.response.headers["Content-Encoding"] = "deflate";
456
+ data.response.body = deflateSync(originBody).toString("base64");
457
+ } else
458
+ throw Error("No matched compression.");
459
+ data.response.isBase64Encoded = true;
460
+ data.response.originBody = originBody;
461
+ } catch (error) {
462
+ console.error(error);
463
+ data.response.body = originBody;
464
+ delete data.response.headers["Content-Encoding"];
465
+ }
466
+ }
467
+ setHeader(key, value) {
468
+ this.response.headers[key] = value;
469
+ return this;
470
+ }
471
+ setContentType(type, charset = "utf-8") {
472
+ if (ContentType[type])
473
+ this.setHeader("Content-Type", `${ContentType[type]}; charset=${charset}`);
474
+ else
475
+ this.setHeader("Content-Type", `${type}; charset=${charset}`);
476
+ return this;
477
+ }
478
+ setStatusCode(code) {
479
+ this.response.statusCode = code;
480
+ return this;
481
+ }
482
+ setBody(body) {
483
+ this.response.body = body;
484
+ return this;
485
+ }
486
+ };
487
+ function useHttp(config) {
488
+ return usePlugin(new Http(config));
489
+ }
490
+ export {
491
+ ContentType,
492
+ Cookie,
493
+ Http,
494
+ HttpError,
495
+ Session,
496
+ Validator,
497
+ useHttp
498
+ };
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@faasjs/http",
3
- "version": "0.0.2-beta.302",
3
+ "version": "0.0.2-beta.314",
4
4
  "license": "MIT",
5
- "main": "lib/index.js",
6
- "module": "lib/index.es.js",
7
- "types": "lib/index.d.ts",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "module": "dist/index.mjs",
8
8
  "homepage": "https://faasjs.com/docs/http",
9
9
  "repository": {
10
10
  "type": "git",
@@ -16,22 +16,21 @@
16
16
  },
17
17
  "funding": "https://github.com/sponsors/faasjs",
18
18
  "scripts": {
19
- "prepack": "rm -rf ./lib && rollup -c && mv lib/*/src/* lib/"
19
+ "build": "rm -rf ./dist && tsup-node src/index.ts --format esm,cjs --dts"
20
20
  },
21
21
  "files": [
22
- "lib"
22
+ "dist"
23
23
  ],
24
- "devDependencies": {
24
+ "peerDependencies": {
25
25
  "@faasjs/func": "^0.0.2-beta.302",
26
- "@types/debug": "*",
27
- "@types/jest": "*",
28
- "@types/node": "*",
29
- "rollup": "*",
30
- "rollup-plugin-typescript2": "*",
26
+ "@faasjs/logger": "^0.0.2-beta.302"
27
+ },
28
+ "devDependencies": {
29
+ "tsup": "*",
31
30
  "typescript": "*"
32
31
  },
33
32
  "engines": {
34
33
  "npm": ">=8.0.0"
35
34
  },
36
- "gitHead": "b53fb35a91369afd0185fb555d98e5c9d90b54bd"
35
+ "gitHead": "60be0e54eb369177b416d109a3f9a5a12dedbf24"
37
36
  }
package/lib/cookie.d.ts DELETED
@@ -1,39 +0,0 @@
1
- import { Session, SessionOptions } from './session';
2
- export declare type CookieOptions = {
3
- domain?: string;
4
- path?: string;
5
- expires?: number;
6
- secure?: boolean;
7
- httpOnly?: boolean;
8
- sameSite?: 'Strict' | 'Lax' | 'None';
9
- session?: SessionOptions;
10
- [key: string]: any;
11
- };
12
- export declare class Cookie<C extends Record<string, string> = any, S extends Record<string, string> = any> {
13
- session: Session<S, C>;
14
- content: Record<string, string>;
15
- readonly config: {
16
- domain?: string;
17
- path: string;
18
- expires: number;
19
- secure: boolean;
20
- httpOnly: boolean;
21
- sameSite?: 'Strict' | 'Lax' | 'None';
22
- session: SessionOptions;
23
- };
24
- private setCookie;
25
- constructor(config: CookieOptions);
26
- invoke(cookie: string | undefined): Cookie<C, S>;
27
- read(key: string): any;
28
- write(key: string, value: string, opts?: {
29
- domain?: string;
30
- path?: string;
31
- expires?: number | string;
32
- secure?: boolean;
33
- httpOnly?: boolean;
34
- sameSite?: 'Strict' | 'Lax' | 'None';
35
- }): Cookie<C, S>;
36
- headers(): {
37
- 'Set-Cookie'?: string[];
38
- };
39
- }
package/lib/index.d.ts DELETED
@@ -1,105 +0,0 @@
1
- import { Plugin, InvokeData, MountData, DeployData, Next, UseifyPlugin } from '@faasjs/func';
2
- import { Cookie, CookieOptions } from './cookie';
3
- import { Session, SessionOptions } from './session';
4
- import { Validator, ValidatorOptions, ValidatorRuleOptions, ValidatorConfig } from './validator';
5
- export { Cookie, CookieOptions, Session, SessionOptions, Validator, ValidatorConfig, ValidatorOptions, ValidatorRuleOptions };
6
- export declare const ContentType: {
7
- [key: string]: string;
8
- };
9
- export declare type HttpConfig<TParams extends Record<string, any> = any, TCookie extends Record<string, string> = any, TSession extends Record<string, string> = any> = {
10
- [key: string]: any;
11
- name?: string;
12
- config?: {
13
- [key: string]: any;
14
- method?: 'BEGIN' | 'GET' | 'POST' | 'DELETE' | 'HEAD' | 'PUT' | 'OPTIONS' | 'TRACE' | 'PATCH' | 'ANY';
15
- timeout?: number;
16
- path?: string;
17
- ignorePathPrefix?: string;
18
- functionName?: string;
19
- cookie?: CookieOptions;
20
- };
21
- validator?: ValidatorConfig<TParams, TCookie, TSession>;
22
- };
23
- export declare type Response = {
24
- statusCode?: number;
25
- headers?: {
26
- [key: string]: string;
27
- };
28
- body?: string;
29
- message?: string;
30
- };
31
- export declare class HttpError extends Error {
32
- readonly statusCode: number;
33
- readonly message: string;
34
- constructor({ statusCode, message }: {
35
- statusCode?: number;
36
- message: string;
37
- });
38
- }
39
- export declare class Http<TParams extends Record<string, any> = any, TCookie extends Record<string, string> = any, TSession extends Record<string, string> = any> implements Plugin {
40
- readonly type: string;
41
- readonly name: string;
42
- headers: {
43
- [key: string]: string;
44
- };
45
- body: any;
46
- params: TParams;
47
- cookie: Cookie<TCookie, TSession>;
48
- session: Session<TSession, TCookie>;
49
- config: HttpConfig<TParams, TCookie, TSession>;
50
- private readonly validatorOptions?;
51
- private response?;
52
- private validator?;
53
- private readonly logger;
54
- /**
55
- * 创建 Http 插件实例
56
- * @param config {object} 配置项
57
- * @param config.name {string} 配置名
58
- * @param config.config {object} 网关配置
59
- * @param config.config.method {string} 请求方法,默认为 POST
60
- * @param config.config.path {string} 请求路径,默认为云函数文件路径
61
- * @param config.config.ignorePathPrefix {string} 排除的路径前缀,当设置 path 时无效
62
- * @param config.config.cookie {object} Cookie 配置
63
- * @param config.validator {object} 入参校验配置
64
- * @param config.validator.params {object} params 校验配置
65
- * @param config.validator.params.whitelist {string} 白名单配置
66
- * @param config.validator.params.onError {function} 自定义报错
67
- * @param config.validator.params.rules {object} 参数校验规则
68
- * @param config.validator.cookie {object} cookie 校验配置
69
- * @param config.validator.cookie.whitelist {string} 白名单配置
70
- * @param config.validator.cookie.onError {function} 自定义报错
71
- * @param config.validator.cookie.rules {object} 参数校验规则
72
- * @param config.validator.session {object} session 校验配置
73
- * @param config.validator.session.whitelist {string} 白名单配置
74
- * @param config.validator.session.onError {function} 自定义报错
75
- * @param config.validator.session.rules {object} 参数校验规则
76
- * @param config.validator.before {function} 参数校验前自定义函数
77
- */
78
- constructor(config?: HttpConfig<TParams, TCookie, TSession>);
79
- onDeploy(data: DeployData, next: Next): Promise<void>;
80
- onMount(data: MountData, next: Next): Promise<void>;
81
- onInvoke(data: InvokeData, next: Next): Promise<void>;
82
- /**
83
- * 设置 header
84
- * @param key {string} key
85
- * @param value {*} value
86
- */
87
- setHeader(key: string, value: string): Http<TParams, TCookie, TSession>;
88
- /**
89
- * 设置 Content-Type
90
- * @param type {string} 类型
91
- * @param charset {string} 编码
92
- */
93
- setContentType(type: string, charset?: string): Http<TParams, TCookie, TSession>;
94
- /**
95
- * 设置状态码
96
- * @param code {number} 状态码
97
- */
98
- setStatusCode(code: number): Http<TParams, TCookie, TSession>;
99
- /**
100
- * 设置 body
101
- * @param body {*} 内容
102
- */
103
- setBody(body: string): Http<TParams, TCookie, TSession>;
104
- }
105
- export declare function useHttp<TParams extends Record<string, any> = any, TCookie extends Record<string, string> = any, TSession extends Record<string, string> = any>(config?: HttpConfig<TParams, TCookie, TSession>): Http<TParams, TCookie, TSession> & UseifyPlugin;