From df3bc37a8772a43525aa40d105733b1de05c4618 Mon Sep 17 00:00:00 2001 From: Chris Edwards Date: Sat, 14 Jan 2017 10:55:50 -0500 Subject: [PATCH] improved error handling, handling bad api key, better 404 info --- src/google-places.js | 31 +++++++++++++++++++++++-------- test/test_google-places.js | 28 +++++++++++++++++++++++++--- 2 files changed, 48 insertions(+), 11 deletions(-) diff --git a/src/google-places.js b/src/google-places.js index 561227e..118d6da 100644 --- a/src/google-places.js +++ b/src/google-places.js @@ -26,7 +26,11 @@ export function setGoogleAPIKey(key) { _apiKey = key; } -export const NO_OFFICES_FOUND = 'No offices found.'; +export const NO_OFFICES_FOUND = query => + `No offices found for: "${query}".`; + + +export const ACCESS_DENIED = 'Access denied. Check API credentials.'; export function findOffice(name) { @@ -38,14 +42,25 @@ export function findOffice(name) { return request .get(options) - .then(({ results }) => { - if (!results || !results.length) { - throw new CustomError( - NO_OFFICES_FOUND, - 404 - ); + .then(({ results, status }) => { + switch (status) { + case 'OK': + return { + placeId : results[0].place_id + }; + + case 'REQUEST_DENIED': + throw new CustomError( + ACCESS_DENIED, + 401 + ); + default: + throw new CustomError( + // eslint-disable-next-line babel/new-cap + NO_OFFICES_FOUND(name), + 404 + ); } - return { placeId : results[0].place_id }; }); } diff --git a/test/test_google-places.js b/test/test_google-places.js index 84a4a67..ceb5e75 100644 --- a/test/test_google-places.js +++ b/test/test_google-places.js @@ -42,12 +42,14 @@ describe('The Google Places API Helper', () => { context('with an empty result', () => { it('rejects the promise with a 404', (done) => { - findOffice('Bo Jackson') + + const name = 'Bo Jackson'; + findOffice(name) .then(() => { done(Error('Promise Should be Rejected')); }) .catch((err) => { - expect(err.message).to.eq(NO_OFFICES_FOUND); + expect(err.message).to.eq(NO_OFFICES_FOUND(name)); expect(err.statusCode).to.eq(404); done(); }) @@ -68,7 +70,27 @@ describe('The Google Places API Helper', () => { }) .catch(done); }); - }) + }); + + context('with an invalid api key', () => { + + beforeEach((done) => { + setGoogleAPIKey('foo'); + done(); + }); + + it('rejects with a 401', (done) => { + getPhoneNumber('Bob Casey') + .then(() => { + done(Error('Promise should be rejected.')); + }) + .catch((err) => { + expect(err.statusCode).to.eq(401); + done(); + }) + .catch(done); + }) + }); }); });