MCPcopy Index your code
hub / github.com/codecombat/codecombat / fetchWrapper

Function fetchWrapper

app/core/api/fetch-json.js:23–57  ·  view source on GitHub ↗
(url, options)

Source from the content-addressed store, hash-verified

21const utils = require('core/utils')
22
23const fetchWrapper = function (url, options) {
24 if (options == null) { options = {} }
25 options = _.cloneDeep(options)
26 if (!_.isUndefined(options.json)) {
27 if (options.headers == null) { options.headers = {} }
28 options.headers['content-type'] = 'application/json'
29 options.body = JSON.stringify(options.json)
30 delete options.json
31 }
32 if (options.data) {
33 // shore up fetch API: https://github.com/github/fetch/issues/256
34 url = url.split('?')[0] + '?' + $.param(options.data)
35 delete options.data
36 }
37 if (options.callOz) {
38 // todo: change to callOther so that can call coco from oz too
39 url = utils.getProductUrl('OZ', url)
40 }
41 if (options.credentials == null) { options.credentials = 'same-origin' }
42
43 return fetch(url, options).then(function (res) {
44 const isJson = _.string.startsWith(res.headers.get('content-type'), 'application/json')
45 if (res.status >= 400) {
46 if (isJson) {
47 // should be a standard server error response, see /server/commons/errors.coffee for schema
48 return res.json().then(json => Promise.reject(Object.assign({ code: res.status }, json)))
49 } else {
50 // old style (handler) raw text response. Wrap it in an object.
51 // eslint-disable-next-line prefer-promise-reject-errors
52 return res.text().then(message => Promise.reject({ message, code: res.status }))
53 }
54 }
55 if (isJson) { return res.json() } else { return res.text() }
56 })
57}
58
59module.exports = fetchWrapper

Callers

nothing calls this directly

Calls 3

fetchFunction · 0.50
stringifyMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected