chore: 使 Client.invoke 支持等待后請求, 解耦 updateCachedProfile
This commit is contained in:
@@ -2,6 +2,7 @@ import { io, Socket } from 'socket.io-client'
|
|||||||
import { CallMethod, ClientEvent } from './ApiDeclare.ts'
|
import { CallMethod, ClientEvent } from './ApiDeclare.ts'
|
||||||
import ApiCallbackMessage from './ApiCallbackMessage.ts'
|
import ApiCallbackMessage from './ApiCallbackMessage.ts'
|
||||||
import User from "./client_data/User.ts"
|
import User from "./client_data/User.ts"
|
||||||
|
import data from "../Data.ts";
|
||||||
|
|
||||||
type UnknownObject = { [key: string]: unknown }
|
type UnknownObject = { [key: string]: unknown }
|
||||||
|
|
||||||
@@ -26,7 +27,11 @@ class Client {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
static invoke(method: CallMethod, args: UnknownObject = {}, timeout: number = 5000): Promise<ApiCallbackMessage> {
|
static invoke(method: CallMethod, args: UnknownObject = {}, timeout: number = 5000): Promise<ApiCallbackMessage> {
|
||||||
if (this.socket == null) throw new Error("客戶端未與伺服器端建立連接!")
|
if (this.socket == null) {
|
||||||
|
return new Promise((reslove) => {
|
||||||
|
setTimeout(async () => reslove(await this.invoke(method, args, timeout)), 500)
|
||||||
|
})
|
||||||
|
}
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
this.socket!.timeout(timeout).emit("The_White_Silk", method, args, (err: string, res: ApiCallbackMessage) => {
|
this.socket!.timeout(timeout).emit("The_White_Silk", method, args, (err: string, res: ApiCallbackMessage) => {
|
||||||
if (err) return reject(err)
|
if (err) return reject(err)
|
||||||
@@ -39,11 +44,14 @@ class Client {
|
|||||||
access_token: token
|
access_token: token
|
||||||
}, timeout)
|
}, timeout)
|
||||||
if (re.code == 200)
|
if (re.code == 200)
|
||||||
this.myUserProfile = (await Client.invoke("User.getMyInfo", {
|
await this.updateCachedProfile()
|
||||||
token: token
|
|
||||||
})).data as unknown as User
|
|
||||||
return re
|
return re
|
||||||
}
|
}
|
||||||
|
static async updateCachedProfile() {
|
||||||
|
this.myUserProfile = (await Client.invoke("User.getMyInfo", {
|
||||||
|
token: data.access_token
|
||||||
|
})).data as unknown as User
|
||||||
|
}
|
||||||
static on(eventName: ClientEvent, func: (data: UnknownObject) => UnknownObject) {
|
static on(eventName: ClientEvent, func: (data: UnknownObject) => UnknownObject) {
|
||||||
this.events[eventName] = func
|
this.events[eventName] = func
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user