Skip to content

Commit

Permalink
Merge 9f8a6d6 into 7e134ea
Browse files Browse the repository at this point in the history
  • Loading branch information
tomchentw committed Aug 5, 2016
2 parents 7e134ea + 9f8a6d6 commit 1e61d65
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/__tests__/catchErrors.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import 'isomorphic-fetch';

import { expect } from 'chai';
import { catchErrors } from '../index';

const echo = (input, options) =>
Promise.resolve({ input, options });

describe('catchErrors', () => {
it('do notthing for normal request', () => {
expect(() => {
catchErrors()(echo, 'url', {
method: 'post',
body: JSON.stringify({ name: 'catchErrors' }),
});
}).to.not.throw();
});

describe('when the options has a data property', () => {
it('throws an error', () =>
expect(() => {
catchErrors()(echo, 'url', {
method: 'post',
data: JSON.stringify({ name: 'catchErrors' }),
});
}).to.throw(/Did you try to use 'body:/)
);
});

describe('when the options has a POJO body property', () => {
it('throws an error', () =>
expect(() => {
catchErrors()(echo, 'url', {
method: 'post',
body: { name: 'catchErrors' },
});
}).to.throw(/Did you forgot to 'JSON\.stringify/)
);
});
});
53 changes: 53 additions & 0 deletions src/catchErrors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const OptionsKeyValidators = [
{
name: 'data',
validate: (input, options) => {
const verb = (options.method || 'GET').toUpperCase();
if (verb === 'GET' || verb === 'HEAD') {
return;
}
throw new Error(`Did you try to use 'body: ${JSON.stringify(options.data)}'?`);
},
},
{
name: 'body',
validate: (input, options) => {
const verb = (options.method || 'GET').toUpperCase();
if (verb === 'GET' || verb === 'HEAD') {
return;
}
function isPojo(obj) {
// Just copy for now.
// https://github.com/nickb1080/is-pojo/blob/master/lib/index.js
if (obj === null || typeof obj !== 'object') {
return false;
}
return Object.getPrototypeOf(obj) === Object.prototype;
}
// https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch#Parameters
if (isPojo(options.body)) {
throw new Error(`Did you forgot to 'JSON.stringify(${JSON.stringify(options.body)})'`);
}
},
},
];

function checkOptions(input, options) {
OptionsKeyValidators.forEach(({ name, validate }) => {
if (name in options) {
validate(input, options);
}
});
}

/**
* Check agains the final input and options to check if there's missing/misconfigured
* properties.
*/
export const catchErrors = () => (
(fetch, input, options = {}) => {
checkOptions(input, options);

return fetch(input, options);
}
);
1 change: 1 addition & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './console';
export * from './catchErrors';

0 comments on commit 1e61d65

Please sign in to comment.