Skip to content

Commit

Permalink
DRYing up response formatting, sending responses for all errors
Browse files Browse the repository at this point in the history
  • Loading branch information
Chris Edwards authored and Chris Edwards committed Jan 1, 2017
1 parent e6b7b90 commit 99b793f
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 28 deletions.
50 changes: 24 additions & 26 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,49 +1,47 @@

import { getDistrictByLatLng } from 'congressional-district-finder';

const DEFAULT_HEADERS = {
'Content-Type': 'application/json'
};

function response(body, statusCode = 200, headers = DEFAULT_HEADERS) {
return {
statusCode,
headers,
body: JSON.stringify(
Object.assign({ statusCode }, body)
)
}
}

function handler(event, context, callback) {

const { queryStringParameters } = event;
const { latLng } = queryStringParameters || {};

if (!latLng) {

const error = new Error(
'Must provide a query string value: "latLng", ' +
'a comma delimited set of coordinates.'
);
error.statusCode = 400;
callback(error);
const message = 'Must provide a query string value: "latLng", ' +
'a comma delimited set of coordinates.';
callback(null, response({ message }, 400));

} else {

const [lat, lng] = latLng.split(',');

getDistrictByLatLng(lat, lng)
.then(({ district }) => {

const { name, districtCode } = district;
const statusCode = 200;

callback(null, {
statusCode,
body: JSON.stringify({
statusCode,
district: {
districtCode,
name
}
}),
headers: {
'Content-Type': 'application/json',
},
});
callback(null, response({
district: {
districtCode,
name
}
}));
})
.catch(({ statusCode, message }) => {
callback(null, {
statusCode,
body: JSON.stringify({ message, statusCode })
})
callback(null, response({ message }, statusCode))
});
}
}
Expand Down
4 changes: 2 additions & 2 deletions test/test_index.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ describe('The Index Lambda Handler', () => {
};

it('sends a statusCode 400', (done) => {
handler(event, {}, ({ statusCode }) => {
handler(event, {}, (err, { statusCode }) => {
try {
expect(statusCode)
.to.eq(400);
Expand All @@ -116,7 +116,7 @@ describe('The Index Lambda Handler', () => {
};

it('sends a statusCode 400', (done) => {
handler(event, {}, ({ statusCode }) => {
handler(event, {}, (err, { statusCode }) => {
try {
expect(statusCode)
.to.eq(400);
Expand Down

0 comments on commit 99b793f

Please sign in to comment.