rage-framework/rpc/src/index.ts

79 lines
2.2 KiB
TypeScript
Raw Normal View History

2024-08-15 19:47:22 +00:00
import { Environment, utils } from './utils'
import { EVENT_LISTENER } from './events'
2024-08-15 19:47:22 +00:00
import { client } from './modules/client'
import { server } from './modules/server'
import { cef } from './modules/cef'
2024-08-15 19:47:22 +00:00
class Rpc {
private _environment = utils.getEnvironment()
private _state =
utils.getEnvironment() === Environment.CEF
? window.rpcEvents
: global.rpcEvents
2024-08-15 19:47:22 +00:00
constructor() {
if (this._environment === Environment.UNKNOWN) return
2024-08-15 19:47:22 +00:00
mp.events.add(EVENT_LISTENER, async (player: any, request: string) => {
2024-09-15 20:55:08 +00:00
switch (this._environment) {
case Environment.SERVER:
await server.listenEvent(player, request)
break
2024-08-15 19:47:22 +00:00
case Environment.CLIENT:
request = player
2024-09-15 18:32:27 +00:00
// await client.listenEvent(request)
break
2024-09-15 18:32:27 +00:00
case Environment.CEF:
request = player
//
// await cef
2024-08-15 19:47:22 +00:00
}
})
}
public register<Callback extends any[] = unknown[], Return = unknown>(
2024-08-15 19:47:22 +00:00
eventName: string,
cb: (...args: Callback) => Return,
2024-08-15 19:47:22 +00:00
) {
if (this._environment === Environment.UNKNOWN) return
this._state[eventName] = cb
2024-08-15 19:47:22 +00:00
}
public async callClient<Args extends any[] = unknown[], Return = unknown>(
2024-08-15 19:47:22 +00:00
player: any,
eventName: string,
...args: Args
): Promise<Return | unknown> {
if (this._environment === Environment.UNKNOWN) return
if (this._environment === Environment.SERVER) {
// return client.executeClient(player, eventName, args)
}
2024-08-15 19:47:22 +00:00
}
public async callServer<Args extends any[] = unknown[], Return = unknown>(
2024-08-15 19:47:22 +00:00
eventName: string,
...args: Args
): Promise<Return | unknown> {
switch (this._environment) {
case Environment.UNKNOWN:
return
2024-09-15 18:32:27 +00:00
case Environment.SERVER:
return
2024-09-15 18:32:27 +00:00
case Environment.CEF:
return client
2024-09-15 18:32:27 +00:00
case Environment.CLIENT:
return server.executeServer(eventName, args)
}
2024-08-15 19:47:22 +00:00
}
}
const testRpc = new Rpc()
export { testRpc }