Created
October 4, 2017 04:51
-
-
Save saibotsivad/89b0f9542fd2d4707b2e0ba203c21d10 to your computer and use it in GitHub Desktop.
browser sdk for the moot app
This file contains 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 fetch from 'whatwg-fetch' | |
// TODO need to actually use encode/decode on parameters | |
function generateQueryParameters({ filter, include, fields }) { | |
const fieldParameters = (fields || []) | |
.map(field => { | |
return `fields[${field.name}]=${field.keys.join(',')}` | |
}) | |
.join('&') | |
const includeParameters = (include || []).join(',') | |
const filterParameters = Object.keys(filter || {}) | |
.map(key => `${key}=${filter[key]}`) | |
.join('&') | |
const properties = [ | |
fieldParameters, | |
includeParameters, | |
filterParameters | |
] | |
.filter(Boolean) | |
.join('&') | |
return properties && ('?' + properties) || '' | |
} | |
export default ({ baseUrl, apiUsesDifferentDomain }) => ({ method, url, filter, include, fields, body, files }) => { | |
const actualUrl = baseUrl + url + generateQueryParameters({ filter, include, fields }) | |
const options = { | |
method, | |
credentials: apiUsesDifferentDomain | |
? 'include' | |
: 'same-origin' | |
} | |
if (files) { | |
options.body = files | |
.map((form, file) => { | |
form.append(file.name, file.data) | |
}, new FormData()) | |
} else { | |
options.header = { | |
'Content-Type': 'application/json' | |
} | |
if (body) { | |
options.body = JSON.stringify(body) | |
} | |
} | |
return fetch(actualUrl, options) | |
.then(response => { | |
if (response.status >= 200 && response.status < 300) { | |
return response | |
} else { | |
const error = new Error(response.statusText) | |
error.name = 'ApiException' | |
error.response = response | |
throw error | |
} | |
}) | |
.then(response => response.json()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment