feat(client/net): Promisfied net events (#95)

This commit is contained in:
Taso authored and GitHub committed 2021-02-16 17:31:22 -05:00
1 parent 3bf098c5ee
commit 513407249a
3 files changed
+88

No files matched your search

+59
View File
@@ -0,0 +1,59 @@
import { uuidv4 } from '../utils/fivem';
interface ISettings {
promiseTimeout: number;
}
interface ISettingsParams {
promiseTimeout?: number;
}
export default class ClientUtils {
private _settings: ISettings;
private _defaultSettings: ISettings = {
promiseTimeout: 5000,
};
constructor(settings?: ISettingsParams) {
this.setSettings(settings);
}
public setSettings(settings: ISettingsParams) {
this._settings = {
...this._defaultSettings,
...settings,
};
}
public emitNetPromise<T = any>(
eventName: string,
...args: any[]
): Promise<T> {
return new Promise((resolve, reject) => {
let hasTimedOut = false;
setTimeout(() => {
hasTimedOut = true;
reject(
`${eventName} has timed out after ${this._settings.promiseTimeout} ms`
);
}, this._settings.promiseTimeout);
// Have to use this as the regular uuid refused to work here for some
// fun reason
const uniqId = uuidv4();
const listenEventName = `${eventName}:${uniqId}`;
emitNet(eventName, listenEventName, ...args);
const handleListenEvent = (data: T, err: unknown) => {
removeEventListener(listenEventName, handleListenEvent);
if (hasTimedOut) return;
if (err) reject(err);
resolve(data);
};
onNet(listenEventName, handleListenEvent);
});
}
}
+3
View File
@@ -1,4 +1,5 @@
import { Client } from 'esx.js';
import ClientUtils from './cl_utils';
import './cl_main';
import './cl_twitter';
@@ -17,3 +18,5 @@ setTick(() => {
emit('esx:getSharedObject', (obj: Client) => (ESX = obj));
}
});
export const ClUtils = new ClientUtils();
+26
View File
@@ -1,2 +1,28 @@
// https://forum.cfx.re/t/typescript-vs-lua-questions/612483/11
export const Delay = (ms: number) => new Promise((res) => setTimeout(res, ms));
// Credits to d0p3t
// https://github.com/d0p3t/fivem-js/blob/master/src/utils/UUIDV4.ts
export const uuidv4 = (): string => {
let uuid = '';
for (let ii = 0; ii < 32; ii += 1) {
switch (ii) {
case 8:
case 20:
uuid += '-';
uuid += ((Math.random() * 16) | 0).toString(16);
break;
case 12:
uuid += '-';
uuid += '4';
break;
case 16:
uuid += '-';
uuid += ((Math.random() * 4) | 8).toString(16);
break;
default:
uuid += ((Math.random() * 16) | 0).toString(16);
}
}
return uuid;
};