diff --git a/phone/src/utils/fetchNui.ts b/phone/src/utils/fetchNui.ts new file mode 100644 index 0000000..f97c40e --- /dev/null +++ b/phone/src/utils/fetchNui.ts @@ -0,0 +1,26 @@ +/** + * Simple wrapper around fetch API tailored for CEF/NUI use. + * @param eventName - The endpoint eventname to target + * @param data - Data you wish to send in the NUI Callback + * + * @return returnData - A promise for the data sent back by the NuiCallbacks CB argument + */ +import LogDebugEvent from '../os/debug/LogDebugEvents'; + +export async function fetchNui(eventName: string, data?: any): Promise { + const options = { + method: 'post', + headers: { + 'Content-Type': 'application/json; charset=UTF-8', + }, + body: JSON.stringify(data), + }; + + LogDebugEvent({ data, action: 'fetchNui' }); + + const resourceName = (window as any)?.GetParentResourceName() || 'npwd'; + + const resp = await fetch(`https://${resourceName}/${eventName}`, options); + + return await resp.json(); +} diff --git a/resources/client/cl_utils.ts b/resources/client/cl_utils.ts index 6db155c..a481556 100644 --- a/resources/client/cl_utils.ts +++ b/resources/client/cl_utils.ts @@ -1,4 +1,5 @@ import { uuidv4 } from '../utils/fivem'; +import { ClUtils } from './client'; interface ISettings { promiseTimeout: number; @@ -42,10 +43,9 @@ export default class ClientUtils { emitNet(eventName, listenEventName, ...args); - const handleListenEvent = (data: T, err: unknown) => { + const handleListenEvent = (data: T) => { removeEventListener(listenEventName, handleListenEvent); if (hasTimedOut) return; - if (err) reject(err); resolve(data); }; onNet(listenEventName, handleListenEvent); @@ -53,9 +53,44 @@ export default class ClientUtils { } } -export const NuiCallback = (event: string, callback: Function) => { - RegisterRawNuiCallback(event, (data: any) => { - const parsed = JSON.parse(data?.body); - callback(parsed); +type CallbackFn = (data: T, cb: Function) => void; + +/** + * A wrapper for handling NUI Callbacks + * @param event - The event name to listen for + * @param callback - The callback function + */ +export const RegisterNuiCB = (event: string, callback: CallbackFn) => { + RegisterNuiCallbackType(event); + on(`__cfx_nui:${event}`, callback); +}; + +/** + * Will Register an NUI event listener that will immediately + * proxy to a server side event of the same name and wait + * for the response. + * @param event - The event name to listen for + */ +export const RegisterNuiProxy = (event: string) => { + RegisterNuiCallbackType(event); + on(`__cfx_nui:${event}`, async (data: unknown, cb: Function) => { + try { + const res = await ClUtils.emitNetPromise(event, data); + cb(res); + } catch (e) { + console.error('Error encountered while listening to resp. Error:', e); + cb({ err: e }); + } }); }; + +type WrapperNetEventCb = (...args: T) => void; + +/** + * Wrapped onNet so we can use generic types on return values from server + * @param event - The event name to listen to + * @param cb - The callback function to execute + */ +export const onNpwdEvent = (event: string, cb: WrapperNetEventCb) => { + onNet(event, cb); +}; diff --git a/resources/server/utils/PromiseNetEvents/PromiseResponse.ts b/resources/server/utils/PromiseNetEvents/PromiseResponse.ts deleted file mode 100644 index 428a1ab..0000000 --- a/resources/server/utils/PromiseNetEvents/PromiseResponse.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { FxServerRespError } from '../../../../typings/phone'; -import { JSONLike, PromiseRespStatus, RawDataResp } from './promise.types'; -import { netEventLogger } from './utils'; -import { config } from '../../server'; - -// Meh temp maybe not idk. -interface PromiseRespDebug { - /* Start time returned by process.hrtime()*/ - started: [number, number]; -} - -export class PromiseResponse { - public readonly respEventName: string; - public readonly source: number; - private promiseRespDebug: PromiseRespDebug; - protected responseData: RawDataResp; - - /** - * Create a new promise response context for use in the onNetPrommise, - * callback argument - * - * @param respEventName - The response event name to emit to on resp.send() - * @param source - The source of the player to emit back to - */ - constructor(respEventName: string, source: number) { - this.respEventName = respEventName; - this.source = source; - - this.promiseRespDebug = { - started: process.hrtime(), - }; - - this.responseData = { - body: {}, - status: 'in-progress', - }; - } - - /** - * Will emit back to the client with the data assigned using - * `setData`. Will send all data assigned to the this.responseData - * back to the client to resolve the promise. - * - * @return void - */ - public send(obj: JSONLike): void { - this.responseData.body = obj; - this.responseData.status = 'success'; - emitNet(this.respEventName, this.source, this.responseData); - - if (config.debug.level === 'silly') { - // Debug time data - const hrEnd = process.hrtime(this.promiseRespDebug.started); - // Divide by good old 1 x 10^6 - const nanoToMicro = hrEnd[1] / 1e6; - const secondExec = hrEnd[0]; - - netEventLogger.silly(`Promise emitted to client after ${secondExec}s ${nanoToMicro}ms`); - } - } - - /** - * Will change the status field present on promiseResponses, this doesn't - * really have a use for now except metadata - * - * @return void - */ - - public setStatus(status: PromiseRespStatus): this { - this.responseData.status = status; - return this; - } - - /** - * Will emit back to the client with the data assigned using - * `setData`. Will send all data assigned to the this.responseData - * back to the client to resolve the promise. - * - * @return void - */ - public sendError({ errorCode, message }: FxServerRespError): void { - this.responseData = { - error: { - errorCode, - message, - }, - body: {}, - status: 'error', - }; - } -} diff --git a/resources/server/utils/PromiseNetEvents/onNetPromise.ts b/resources/server/utils/PromiseNetEvents/onNetPromise.ts index 83d151a..3da9848 100644 --- a/resources/server/utils/PromiseNetEvents/onNetPromise.ts +++ b/resources/server/utils/PromiseNetEvents/onNetPromise.ts @@ -1,22 +1,23 @@ -import { ErrorStringKeys } from '../../../../typings/phone'; import { getSource } from '../miscUtils'; -import { PromiseResponse } from './PromiseResponse'; import { mainLogger } from '../../sv_logger'; -import { CBSignature, PromiseRequest, PromiseRequestData } from './promise.types'; +import { CBSignature, PromiseEventReturnFunc, PromiseRequest } from './promise.types'; const netEventLogger = mainLogger.child({ module: 'events' }); -export function onNetPromise(eventName: string, cb: CBSignature) { - onNet(eventName, async (respEventName: string, data: PromiseRequestData) => { +export function onNetPromise(eventName: string, cb: CBSignature): void { + onNet(eventName, async (respEventName: string, data: T) => { const src = getSource(); const promiseRequest: PromiseRequest = { source: src, - body: data, + data, }; - // Lets hope GC can clean you up - const promiseResp = new PromiseResponse(respEventName, src); + const promiseResp: PromiseEventReturnFunc = (data: unknown) => { + emitNet(respEventName, src, data); + netEventLogger.debug(`Response Promise Event ${respEventName}, Data >>`); + netEventLogger.debug(data); + }; // In case the cb is a promise, we use Promise.resolve Promise.resolve(cb(promiseRequest, promiseResp)).catch((e) => { @@ -24,10 +25,7 @@ export function onNetPromise(eventName: string, cb: CBSignature) { `An error occured for a onNetPromise (${eventName}), Error: ${e.message}`, ); - promiseResp.sendError({ - errorCode: ErrorStringKeys.SERVER_ERROR, - message: 'An error occured on the server', - }); + promiseResp({ err: true, errMsg: 'Server error occurred' }); }); }); } diff --git a/resources/server/utils/PromiseNetEvents/promise.types.ts b/resources/server/utils/PromiseNetEvents/promise.types.ts index 1afe60d..2e8e1ed 100644 --- a/resources/server/utils/PromiseNetEvents/promise.types.ts +++ b/resources/server/utils/PromiseNetEvents/promise.types.ts @@ -1,30 +1,8 @@ -import { FxServerRespError } from '../../../../typings/phone'; -import { PromiseResponse } from './PromiseResponse'; - -export type BasicPrimitives = string | number | boolean; - -export interface JSONLike { - [key: string]: BasicPrimitives; -} - -export type PromiseRespStatus = 'error' | 'success' | 'warning' | 'in-progress'; - -export interface RawDataResp { - status: PromiseRespStatus; - error?: FxServerRespError; - body: JSONLike; -} - export interface PromiseRequest { - body: PromiseRequestData; + data: T; source: number; } -export interface PromiseRequestData { - data: T; -} +export type PromiseEventReturnFunc = (returnData: unknown) => void; -export type CBSignature = ( - request: PromiseRequest, - response: PromiseResponse, -) => Promise | void; +export type CBSignature = (reqObj: PromiseRequest, resp: PromiseEventReturnFunc) => void; diff --git a/resources/server/utils/PromiseNetEvents/utils.ts b/resources/server/utils/PromiseNetEvents/utils.ts deleted file mode 100644 index 93e2fb6..0000000 --- a/resources/server/utils/PromiseNetEvents/utils.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { mainLogger } from '../../sv_logger'; - -export const netEventLogger = mainLogger.child({ - module: 'net-events', -});