Skip to content

Instantly share code, notes, and snippets.

@umer4ik
Created July 6, 2018 10:40
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 umer4ik/368b02a3c8bbf4e837fe7c3038c9bba6 to your computer and use it in GitHub Desktop.
Save umer4ik/368b02a3c8bbf4e837fe7c3038c9bba6 to your computer and use it in GitHub Desktop.
const createHeaders = ({
json = true,
...rest
}) => {
const headers = new Headers()
if (json) {
headers.append('Content-type', 'application/json')
}
Object.keys(rest).forEach(key => {
headers.append(key, rest[key])
})
return headers
}
const WITH_BODY_METHODS = ['POST', 'PUT']
const ALLOWED_METHODS = ['GET', 'POST', 'PUT']
const createRequest = ({
url,
method,
body,
headersData: {
json,
...rest
}
}) => {
if (typeof url !== 'string' || !url) {
throw new Error('`url` is required')
}
if (typeof method !== 'string' || !method) {
throw new Error('`method` is required')
}
if (ALLOWED_METHODS.indexOf(method.toUpperCase()) === -1) {
throw new Error(`Method ${method} is not allowed`)
}
if (body && WITH_BODY_METHODS.indexOf(method) === -1) {
throw new Error(`Only ${WITH_BODY_METHODS.join(', ')} can have \`body\` option`)
}
if (body === null) {
throw new Error('`body` cannot be null')
}
if (typeof body === 'object') {
body = JSON.parse(body)
} else if (typeof body === 'string') {
try {
JSON.parse(body)
} catch (error) {
throw new Error('Cannot parse `body` param')
}
}
const headers = createHeaders({ json, ...rest })
const requestOptions = {
credentials: 'include',
method,
headers
}
if (body) {
requestOptions.body = body
}
const request = new Request(url, requestOptions)
return request
}
const ajaxInterface = async (options) => {
const request = createRequest(options)
const response = await fetch(request)
const data = await response.json()
}
class AjaxInterface {
constructor() {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment