From 6ea16eb698038d895601fd4f006e28475968f60e Mon Sep 17 00:00:00 2001 From: liamcottle Date: Mon, 15 Mar 2021 20:50:49 +1300 Subject: [PATCH] added sendRequestAsync which returns a promise when sending requests --- examples/6_async_requests.js | 35 +++++++++++++++++++++++++++++++++++ rustplus.js | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 examples/6_async_requests.js diff --git a/examples/6_async_requests.js b/examples/6_async_requests.js new file mode 100644 index 0000000..5ec5fd9 --- /dev/null +++ b/examples/6_async_requests.js @@ -0,0 +1,35 @@ +const RustPlus = require('@liamcottle/rustplus.js'); +var rustplus = new RustPlus('ip', 'port', 'playerId', 'playerToken'); + +// wait until connected before sending commands +rustplus.on('connected', () => { + + /** + * sendRequestAsync will return a promise for your request. + * you can optionally pass in a second parameter for the timeout in milliseconds + * - AppResponse packets will be sent to `then` on success. + * - AppError packets and Timeout Errors will be sent to `catch`. + */ + rustplus.sendRequestAsync({ + getInfo: {}, // get server info with a timeout of 2 seconds + }, 2000).then((response) => { + + // AppResponse + console.log(response); + + }).catch((error) => { + + // AppError or Error('Timeout'); + console.log(error); + + }).finally(() => { + + // disconnect so our script is finished + rustplus.disconnect(); + + }); + +}); + +// connect to rust server +rustplus.connect(); \ No newline at end of file diff --git a/rustplus.js b/rustplus.js index ac89b93..492d536 100644 --- a/rustplus.js +++ b/rustplus.js @@ -150,6 +150,42 @@ class RustPlus extends EventEmitter { } + /** + * Send a Request to the Rust Server and return a Promise + * @param data this should contain valid data for the AppRequest packet defined in the rustplus.proto schema file + * @param timeoutMilliseconds milliseconds before the promise will be rejected. Defaults to 10 seconds. + */ + sendRequestAsync(data, timeoutMilliseconds = 10000) { + return new Promise((resolve, reject) => { + + // reject promise after timeout + var timeout = setTimeout(() => { + reject(new Error('Timeout reached while waiting for response')); + }, timeoutMilliseconds); + + // send request + this.sendRequest(data, (message) => { + + // cancel timeout + clearTimeout(timeout); + + if(message.response.error){ + + // reject promise if server returns an AppError for this request + reject(message.response.error); + + } else { + + // request was successful, resolve with message.response + resolve(message.response); + + } + + }); + + }); + } + /** * Send a Request to the Rust Server to set the Entity Value. * @param entityId the entity id to set the value for