Skip to content

Instantly share code, notes, and snippets.

@kdepp
Last active February 5, 2018 08:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kdepp/c003c48f9d46c44c39e05725c3399451 to your computer and use it in GitHub Desktop.
Save kdepp/c003c48f9d46c44c39e05725c3399451 to your computer and use it in GitHub Desktop.
For J V
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'
})
}
}
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