diff --git a/serverDate.js b/serverDate.js index 4dc65b6..0a3ebc2 100644 --- a/serverDate.js +++ b/serverDate.js @@ -22,13 +22,15 @@ const fetchSampleImplementation = async () => { }; export const getServerDate = async ( - { fetchSample } = { fetchSample: fetchSampleImplementation } + { fetchSample, withErrors } = { fetchSample: fetchSampleImplementation, withErrors: false } ) => { - let best = { uncertainty: Number.MAX_VALUE }; + const fetchCount = 10; + const errors = []; + let best = { date: new Date(), offset: 0, uncertainty: Number.MAX_VALUE }; // Fetch 10 samples to increase the chance of getting one with low // uncertainty. - for (let index = 0; index < 10; index++) { + for (let index = 0; index < fetchCount; index++) { try { const { requestDate, responseDate, serverDate } = await fetchSample(); @@ -46,9 +48,10 @@ export const getServerDate = async ( }; } } catch (exception) { + errors.push(exception); console.warn(exception); } } - return best; + return withErrors ? { ...best, errors, fetchCount } : best; }; diff --git a/test.js b/test.js index 1a13d95..3e9e44e 100644 --- a/test.js +++ b/test.js @@ -77,3 +77,22 @@ it(`synchronizes the time with the server`, async () => { uncertainty: 582.5, }); }); + +it(`returns offset 0 and local Date on error`, async () => { + const fetchSample = async () => { + throw new Error(`oh dang`); + }; + const { date, offset, uncertainty } = await getServerDate({ fetchSample }); + assert(offset === 0); + assert(uncertainty === Number.MAX_VALUE); + assert(Date.now() - date < 100); +}) + +it(`reports errors if you ask it to`, async () => { + const fetchSample = async () => { + throw new Error(`oh dang`); + }; + const { errors, fetchCount } = await getServerDate({ fetchSample, withErrors: true }); + assert(errors.length === fetchCount); + assert(errors[0].message === `oh dang`); +})