Last active
February 5, 2018 08:27
-
-
Save kdepp/c003c48f9d46c44c39e05725c3399451 to your computer and use it in GitHub Desktop.
For J V
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function request (url, params = {}) { | |
return fetch(url, params) | |
.then(res => res && res.json()) | |
} | |
export function withTimeout (timeout, fn, context) { | |
return (...args) => { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => reject(new Error('Function timeout')), timeout) | |
const res = fn.apply(context, args) | |
if (!res.then) return resolve(res) | |
return res.then(resolve, reject) | |
}) | |
} | |
} | |
export const requestWithTimeout = withTimeout(2000, request) | |
export const apiFactory = (requestWithTimeout) => ({ | |
doSomething: () => requestWithTimeout('https://YOUR_DOMAIN/api/SOME_END_POINT') | |
.then( | |
data => 'do something here', | |
e => console.error(e.stack) | |
) | |
}) | |
export const detailLogicFactory = (api) => { | |
playWithDoSomething: () => { | |
api.doSomething().then(data => { | |
'end user logic here' | |
}) | |
} | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { detailLogicFactory } from './request_with_timeout' | |
describe('detailLogic', () => { | |
it('success', (done) => { | |
const detailLogic = detailLogicFactory({ | |
doSomething: () => Promise.resolve('correct result') | |
}) | |
detailLogic.playWithDoSomething().then(res => { | |
expect(res).to.eql('correct result') | |
done() | |
}) | |
}) | |
it('timeout', (done) => { | |
const detailLogic = detailLogicFactory({ | |
doSomething: () => new Promise(resolve => setTimeout(resolve, 10000)) | |
}) | |
detailLogic.playWithDoSomething().catch(e => { | |
expect(e.message).to.eql('Function timeout') | |
done() | |
}) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment