feat: Client calling server API

This commit is contained in:
CrescentLeaf
2025-09-06 01:51:57 +08:00
parent 7d407d02ca
commit d5e38a8167
4 changed files with 68 additions and 71 deletions

View File

@@ -10,5 +10,6 @@ type ApiCallbackMessage = {
* 501: 伺服器端不支持請求的功能
*/
code: 200 | 400 | 401 | 403 | 404 | 500 | 501,
data?: { [key: string]: unknown },
}
export default ApiCallbackMessage

View File

@@ -1,3 +1,7 @@
export type CallMethod =
"User.auth" |
"User.register" |
"User.login"
export type ClientEvent =
"Client.onMessage"

View File

@@ -1,21 +1,41 @@
import { io, Socket } from 'https://unpkg.com/socket.io-client@4.8.1/dist/socket.io.esm.min.js'
import { CallMethod } from './ApiDeclare.ts'
import { CallMethod, ClientEvent } from './ApiDeclare.ts'
import ApiCallbackMessage from './ApiCallbackMessage.ts'
type UnknownObject = { [key: string]: unknown }
class Client {
static socket: Socket
static socket?: Socket
static events: { [key: string]: (data: UnknownObject) => UnknownObject } = {}
static connect() {
this.socket && this.socket.disconnect()
this.socket?.disconnect()
this.socket && delete this.socket
this.socket = io()
this.socket!.on("The_White_Silk", (name: string, data: UnknownObject, callback: (ret: UnknownObject) => void) => {
try {
if (name == null || data == null) return
const re = this.events[name]?.(data)
re && callback(re)
} catch (e) {
console.error(e)
}
})
}
static call(method: CallMethod, args: {}, timeout: number = 5000) {
static invoke(method: CallMethod, args: UnknownObject = {}, timeout: number = 5000): Promise<ApiCallbackMessage> {
if (this.socket == null) throw new Error("客戶端未與伺服器端建立連接!")
return new Promise((resolve, reject) => {
this.socket.timeout().emit("The_White_Silk", (err, res: ApiCallbackMessage) => {
if (err) return reject(err)
this.socket!.timeout(timeout).emit("The_White_Silk", method, args, (err: string, res: ApiCallbackMessage) => {
if (err) return reject(err)
resolve(res)
})
})
}
static on(eventName: ClientEvent, func: (data: UnknownObject) => UnknownObject) {
this.events[eventName] = func
}
static off(eventName: ClientEvent){
delete this.events[eventName]
}
}
export default Client