Skip to content

Commit

Permalink
Merge pull request #27 from swellstores/fix/promise-rejection-on-auth
Browse files Browse the repository at this point in the history
Fix: handle promise rejection in auth stage
  • Loading branch information
awwit authored Nov 14, 2023
2 parents acca672 + 4c25c43 commit cbce439
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 18 deletions.
48 changes: 30 additions & 18 deletions lib/client.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
'use strict';

const EventEmitter = require('events');
const crypto = require('crypto');

Expand Down Expand Up @@ -263,7 +265,7 @@ class Client extends EventEmitter {
*/
get(url, data, callback) {
if (!url) {
throw new Error('url is required');
return Promise.reject(new Error('url is required'));
}

if (typeof data === 'function') {
Expand All @@ -277,10 +279,8 @@ class Client extends EventEmitter {
}

if (!this.authed) {
return new Promise((resolve) => {
// If not connected, do auth to get updated versions first
this.getPendingAuth(url, data, callback, resolve);
});
// If not connected, do auth to get updated versions first
return this.getPendingAuth(url, data, callback);
}

// Indicates whether to check the request cache or not
Expand All @@ -301,23 +301,35 @@ class Client extends EventEmitter {
return this.request('get', url, data, callback);
}

getPendingAuth(url, data, callback, resolve) {
if (this.requestsPendingAuth) {
this.requestsPendingAuth.push({ url, data, callback, resolve });
return;
}
getPendingAuth(url, data, callback) {
return new Promise((resolve, reject) => {
if (this.requestsPendingAuth) {
this.requestsPendingAuth.push({ url, data, callback, resolve });
return;
}

this.requestsPendingAuth = [];
this.requestsPendingAuth = [];

this.authWithKey(() => {
this.get(url, data, (_err, result, headers) => {
if (callback) {
callback(null, result, headers);
}
resolve(result);
});
this.authWithKey(() => {
this.get(url, data, (err, result, headers) => {
if (typeof callback === 'function') {
callback(err, result, headers);
}

if (err) {
reject(err);
return;
}

resolve(result);
})
.catch((err) => {
reject(err.message);
});
});
}).then((result) => {
this.flushRequestsPendingAuth();
return result;
});
}

Expand Down
2 changes: 2 additions & 0 deletions lib/connection.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
'use strict';

const EventEmitter = require('events');
const tls = require('tls');
const net = require('net');
Expand Down

0 comments on commit cbce439

Please sign in to comment.