Skip to content

Commit

Permalink
improved error handling, handling bad api key, better 404 info
Browse files Browse the repository at this point in the history
  • Loading branch information
Chris Edwards authored and Chris Edwards committed Jan 14, 2017
1 parent 53d9d59 commit df3bc37
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 11 deletions.
31 changes: 23 additions & 8 deletions src/google-places.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {

Expand All @@ -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 };
});
}

Expand Down
28 changes: 25 additions & 3 deletions test/test_google-places.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
})
Expand All @@ -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);
})
});
});

});
Expand Down

0 comments on commit df3bc37

Please sign in to comment.