From 7e1b1f952cc6083981fd83f32918d40319b4e5af Mon Sep 17 00:00:00 2001 From: yutent Date: Thu, 19 Dec 2024 15:47:52 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0.d.ts=E5=A3=B0=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- index.d.ts | 42 ++++++++++++++++++++++++++++++++++++++++++ index.js | 16 ++++++++++------ package.json | 3 ++- 3 files changed, 54 insertions(+), 7 deletions(-) create mode 100644 index.d.ts diff --git a/index.d.ts b/index.d.ts new file mode 100644 index 0000000..1665f80 --- /dev/null +++ b/index.d.ts @@ -0,0 +1,42 @@ +import Request from '@gm5/request' +import Response from '@gm5/response' +import Five from '@gm5/core' + +declare class Controller { + readonly context: Five + readonly request: Request + readonly response: Response + + readonly method: string + readonly host: string + readonly hostname: string + readonly ua: string + readonly jwt: { + result: object | null + sign(data: object): string + verify(token?: string): boolean + } + + assign(key: string | number, val: any): void + + render(file: string, noParse?: boolean): void + + cookie(key: string): string + + cookie( + key: string, + val: any, + opt?: { + domain?: string + expires?: Date + maxAge?: number + [key: string]: any + } + ): void + + session(key: string): Promise + + session(key: string, val: any): void +} + +export default Controller diff --git a/index.js b/index.js index 6eb4fb5..e1d8514 100644 --- a/index.js +++ b/index.js @@ -31,14 +31,17 @@ export default class Controller { return this.context.$$jwt.sign(data, __mix_key__) }, verify: token => { - this.#auth = null let { __mix_key__ } = this.request + let jwt = this.context.$$jwt + token ??= this.request.header('authorization') + this.#auth = null + if (token) { - this.#auth = this.context.$$jwt.verify(token, __mix_key__) + this.#auth = jwt.verify(token, __mix_key__) } - return this.#auth + return !!this.#auth } } } @@ -97,14 +100,15 @@ export default class Controller { // 会话读写, 返回的是Promise对象 session(key, val) { let { ssid } = this.request - if (this.context.$$session) { + let store = this.context.$$session + if (store) { key += '' if (arguments.length < 2) { // 这里返回的是Promise对象 - return this.context.$$session.get(ssid, key) + return store.get(ssid, key) } - this.context.$$session.set(ssid, key, val) + store.set(ssid, key, val) } else { throw new Error('Session was disabled.') } diff --git a/package.json b/package.json index 738c414..3e4beff 100644 --- a/package.json +++ b/package.json @@ -1,9 +1,10 @@ { "name": "@gm5/controller", - "version": "2.0.3", + "version": "2.0.4", "type": "module", "description": "控制器基类。", "main": "index.js", + "types": "index.d.ts", "author": "yutent ", "keywords": [ "fivejs",