From b7559411c6322e471e2155491dbd4efa950378a4 Mon Sep 17 00:00:00 2001 From: ChrisChrome Date: Sun, 26 Jan 2025 11:13:44 -0700 Subject: [PATCH] Add automatic client token renewal --- freepbx.js | 45 +++++++++++++++++++++++++++++++++------------ 1 file changed, 33 insertions(+), 12 deletions(-) diff --git a/freepbx.js b/freepbx.js index 4843f25..2672e13 100644 --- a/freepbx.js +++ b/freepbx.js @@ -11,12 +11,31 @@ class FreepbxManager { * @param {Object} config.dbPool - The connection pool for managing database connections. */ constructor(config) { - this.client = new FreepbxGqlClient(config.url, { - client: { - id: config.clientId, - secret: config.clientSecret, - }, - }); + this.client = null; + this.renewClient = async () => { + this.client = new FreepbxGqlClient(config.url, { + client: { + id: config.clientId, + secret: config.clientSecret, + }, + }); + } + this.renewClient(); + + this.pbxCall = async (query, variables) => { + try { + return await this.client.request(query, variables); + } catch (err) { + if (err.response && err.response.error && err.response.error.message === "The resource owner or authorization server denied the request.") { + await this.renewClient(); + console.log("Client renewed"); + return await this.pbxCall(query, variables); + } else { + throw err; + } + } + } + this.pool = config.dbPool; if (!this.pool) { @@ -26,6 +45,8 @@ class FreepbxManager { } + + async getExtension(ext) { ext = String(ext); @@ -46,7 +67,7 @@ class FreepbxManager { extensionId: ext.match(/\d+/)[0], }; - return await this.client.request(query, variables); + return await this.pbxCall(query, variables); } async listExtensions() { @@ -63,7 +84,7 @@ class FreepbxManager { } `; - return await this.client.request(query); + return await this.pbxCall(query); } async addExtension(ext, name) { @@ -92,7 +113,7 @@ class FreepbxManager { vmPassword: ext, }; - return await this.client.request(query, variables); + return await this.pbxCall(query, variables); } async deleteExtension(ext) { @@ -109,7 +130,7 @@ class FreepbxManager { ext, }; - const fpbxQuery = this.client.request(query, variables); + const fpbxQuery = this.pbxCall(query, variables); const dbQuery = this.pool.query('DELETE FROM paging_groups WHERE ext = ?', [ext]); return await Promise.all([fpbxQuery, dbQuery]); } @@ -123,7 +144,7 @@ class FreepbxManager { } `; - return await this.client.request(query); + return await this.pbxCall(query); } // async updateName(ext, name) { @@ -140,7 +161,7 @@ class FreepbxManager { // name, // }; - // return await this.client.request(query, variables); + // return await this.pbxCall(query, variables); // } // TODO: Implement updateName method, Current implementation resets extension for some reason