Skip to content

Commit

Permalink
dev(errors): better errors WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
goldylucks committed Jul 7, 2019
1 parent aac050a commit c480be9
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 1 deletion.
1 change: 0 additions & 1 deletion .npmrc
Original file line number Diff line number Diff line change
@@ -1 +0,0 @@
//registry.npmjs.org/:_authToken = ${NPM_TOKEN}
30 changes: 30 additions & 0 deletions src/validateCoords.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import validateCoords from './validateCoords';

const spy = jest.spyOn(console, 'error');

afterEach(() => {
spy.mockRestore();
});

describe('validateCoords', () => {
it('should log errors in the console for invalid from/to coords', () => {
validateCoords({ from: {}, to: {} });
expect(spy).toHaveBeenCalledTimes(4);
});

it('should NOT log errors in the console for valid from/to coords', () => {
expect(spy).toHaveBeenCalledTimes(0);
let from = { lat: 1, lng: 1 };
let to = { lat: 2, lng: 2 };
validateCoords({ from, to });
expect(spy).toHaveBeenCalledTimes(0);
from = { latitude: 1, longitude: 1 };
to = { latitude: 2, longitude: 2 };
validateCoords({ from, to });
expect(spy).toHaveBeenCalledTimes(0);
from = { latitude: 1, lon: 1 };
to = { latitude: 2, lon: 2 };
validateCoords({ from, to });
expect(spy).toHaveBeenCalledTimes(0);
});
});
36 changes: 36 additions & 0 deletions src/validateCoords.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const lonKeys = ['lng', 'lon', 'longitude'];
const latKeys = ['lat', 'latitude'];
const typesRegex = /number|string/;

const isLongValid = (arg) =>
!!lonKeys.find((key) => (typeof arg[key]).match(typesRegex));

const isLatValid = (arg) =>
!!latKeys.find((key) => (typeof arg[key]).match(typesRegex));

const reportInvalid = (arg, fromOrTo, latOrLong) =>
console.error(
`[geolib] -> Get distance -> ${latOrLong} invalid for object "${fromOrTo}". expected property lng, lon or longitude to be present and have type of string or number, but received:`,
arg
);

const validateLong = (arg, fromOrTo) => {
if (!isLongValid(arg)) {
reportInvalid(arg, fromOrTo, 'longitude');
}
};

const validateLat = (arg, fromOrTo) => {
if (!isLatValid(arg)) {
reportInvalid(arg, fromOrTo, 'latitude');
}
};

const validateCoords = ({ from, to }) => {
validateLat(from, 'from');
validateLong(from, 'from');
validateLat(to, 'to');
validateLong(to, 'to');
};

export default validateCoords;

0 comments on commit c480be9

Please sign in to comment.