Skip to content

Instantly share code, notes, and snippets.

@schabluk
Last active May 30, 2018 18:37
Show Gist options
  • Save schabluk/96e6dd402fcfc76fb23b993660e89cb5 to your computer and use it in GitHub Desktop.
Save schabluk/96e6dd402fcfc76fb23b993660e89cb5 to your computer and use it in GitHub Desktop.
Service dependency for MobX State Tree
import axios, { get, CancelToken } from 'axios'
import faker from 'faker'
//
// Only data property will be returned from the reuquest. This will simplify
// data processing, as it won't be neccesary to call .then() each time
// to return the request.data.
// See: https://github.com/axios/axios#response-schema
//
// The status codes validation, if needed, should be done in 'validateStatus'
// method of the Request config.
// See: https://github.com/axios/axios#request-config
//
axios.interceptors.response.use(({data}) => data)
//
// Request cancellation setup.
// See: https://github.com/axios/axios#cancellation
//
const CancelSource = CancelToken.source()
//
// Axios default configuration.
// See: https://github.com/axios/axios#request-config
//
const Options = headers => ({
mode: 'cors',
headers,
// withCredentials: true,
// credentials: 'same-origin',
timeout: 3000,
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
})
// Config for endpoint that is accepting and returning only text.
const configText = Options({
'Content-Type': 'text/plain;charset=UTF-8',
'Accept': 'text/plain',
})
// // Config for endpoint that is accepting and returning only json.
const configJson = Options({
'Content-Type': 'application/json;charset=UTF-8',
'Accept': 'application/json',
})
// REST services Address book.
// const Address = {
// TEST: 'http://api.test.org',
// }
//
// const { TEST } = Address
// Fake request delay.
const Delay = time => new Promise(resolve => setTimeout(() => resolve(), time))
const Service = {
// Fake data generated by Faker.js.
fake: {
getAddress: async function () {
try {
return await Delay(500).then(data => {
return Array.from({length: 10}, (v, k) => ({
id: k,
email: faker.internet.email(),
image: faker.image.imageUrl(),
descr: faker.lorem.paragraph(),
uuid: faker.random.uuid()
}))
})
} catch (error) {
throw new Error(`Fake API getAddress: ${error.message}`)
}
},
},
// Testing different functions and custom requests.
test: {
test: async function (url, defaultConfig = configText || configJson) {
// Example of a config for cancelable request.
const config = {...defaultConfig, cancelToken: CancelSource.token}
try {
return await get(url, config)
} catch (error) {
// Custom Error handling.
if (error.response) {
throw new Error(`Status code out of valid range: ${error.message}`)
} else if (error.request) {
throw new Error(`The request was made, but no response was received.`)
} else {
throw new Error(`Request triggered an Error: ${error.message}`)
}
}
},
}
}
export default Service
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment