gooddata
Advanced tools
Comparing version 6.0.0-alpha2 to 6.0.0-lhorak-pzb-650-apierror-2018-03-19T13-08-13-400Z
@@ -391,2 +391,25 @@ // Copyright (C) 2007-2017, GoodData(R) Corporation. All rights reserved. | ||
declare class ApiResponse<T> { | ||
public response: Response; | ||
public responseBody: string; | ||
getData(): T; | ||
} | ||
declare class ApiError extends Error { | ||
public cause: Error | null; | ||
} | ||
declare class ApiResponseError extends ApiError { | ||
public cause: Error | null; | ||
// get statusCode.. | ||
} | ||
declare class ApiNetworkError extends ApiError { | ||
public cause: Error | null; | ||
} | ||
export interface IXhrMockInBeforeSend { | ||
@@ -402,7 +425,7 @@ setRequestHeader(key: string, value: string): void; | ||
export interface IXhr { | ||
get<T>(uri: string, settings?: IXhrSettings): Promise<T>; | ||
post<T>(uri: string, settings?: IXhrSettings): Promise<T>; | ||
put<T>(uri: string, settings?: IXhrSettings): Promise<T>; | ||
ajax<T>(uri: string, settings?: IXhrSettings): Promise<T>; | ||
export interface IXhr { // all throws ApiError() | ||
get<T>(uri: string, settings?: IXhrSettings): Promise<ApiResponse<T>>; | ||
post<T>(uri: string, settings?: IXhrSettings): Promise<ApiResponse<T>>; | ||
put<T>(uri: string, settings?: IXhrSettings): Promise<ApiResponse<T>>; | ||
ajax<T>(uri: string, settings?: IXhrSettings): Promise<ApiResponse<T>>; | ||
ajaxSetup(settings: IXhrSettings): void; | ||
@@ -409,0 +432,0 @@ } |
@@ -45,3 +45,5 @@ 'use strict'; | ||
return xhr.get(uri).then(function (result) { | ||
return xhr.get(uri).then(function (r) { | ||
return r.getData(); | ||
}).then(function (result) { | ||
return transformClient(result); | ||
@@ -56,3 +58,5 @@ }); | ||
if (uri) { | ||
return xhr.get(uri).then(function (result) { | ||
return xhr.get(uri).then(function (r) { | ||
return r.getData(); | ||
}).then(function (result) { | ||
return { | ||
@@ -75,3 +79,5 @@ items: result.clients.items.map(transformClient), | ||
return xhr.get(uri).then(function (result) { | ||
return xhr.get(uri).then(function (r) { | ||
return r.getData(); | ||
}).then(function (result) { | ||
return _extends({}, result.clientUsers, { | ||
@@ -78,0 +84,0 @@ items: result.clientUsers.items.map(transformClientUser) |
@@ -16,3 +16,5 @@ 'use strict'; | ||
var getUserContracts = function getUserContracts() { | ||
return xhr.get(routes.CONTRACTS).then(function (data) { | ||
return xhr.get(routes.CONTRACTS).then(function (r) { | ||
return r.getData(); | ||
}).then(function (data) { | ||
return { | ||
@@ -19,0 +21,0 @@ items: data.contracts.items.map(function (item) { |
@@ -46,3 +46,5 @@ 'use strict'; | ||
var getDataProducts = function getDataProducts(contractId, include) { | ||
return xhr.get(routes.interpolate(routes.CONTRACT_DATA_PRODUCTS, { contractId: contractId }, include && { include: include })).then(function (data) { | ||
return xhr.get(routes.interpolate(routes.CONTRACT_DATA_PRODUCTS, { contractId: contractId }, include && { include: include })).then(function (r) { | ||
return r.getData(); | ||
}).then(function (data) { | ||
return { | ||
@@ -55,3 +57,5 @@ items: data.dataProducts.items.map(transformDataProduct) | ||
var getDataProduct = function getDataProduct(contractId, dataProductId, include, stats, state) { | ||
return xhr.get(routes.interpolate(routes.CONTRACT_DATA_PRODUCT, { contractId: contractId, dataProductId: dataProductId }, Object.assign(include && { include: include }, stats && { stats: stats }, state && { state: state }))).then(function (data) { | ||
return xhr.get(routes.interpolate(routes.CONTRACT_DATA_PRODUCT, { contractId: contractId, dataProductId: dataProductId }, Object.assign(include && { include: include }, stats && { stats: stats }, state && { state: state }))).then(function (r) { | ||
return r.getData(); | ||
}).then(function (data) { | ||
return transformDataProduct(data); | ||
@@ -58,0 +62,0 @@ }); |
@@ -35,3 +35,5 @@ 'use strict'; | ||
var getDomainDataProducts = function getDomainDataProducts(contractId, dataProductId) { | ||
return xhr.get(routes.interpolate(routes.CONTRACT_DATA_PRODUCT_DOMAIN_DATA_PRODUCTS, { contractId: contractId, dataProductId: dataProductId })).then(function (_ref2) { | ||
return xhr.get(routes.interpolate(routes.CONTRACT_DATA_PRODUCT_DOMAIN_DATA_PRODUCTS, { contractId: contractId, dataProductId: dataProductId })).then(function (r) { | ||
return r.getData(); | ||
}).then(function (_ref2) { | ||
var items = _ref2.domainDataProducts.items, | ||
@@ -38,0 +40,0 @@ status = _ref2.status; |
@@ -43,7 +43,11 @@ 'use strict'; | ||
return xhr.get(uri).then(transformDomain); | ||
return xhr.get(uri).then(function (r) { | ||
return r.getData(); | ||
}).then(transformDomain); | ||
}; | ||
var getDomains = function getDomains(contractId, query) { | ||
return xhr.get(routes.interpolate(routes.CONTRACT_DOMAINS, { contractId: contractId }, query)).then(function (result) { | ||
return xhr.get(routes.interpolate(routes.CONTRACT_DOMAINS, { contractId: contractId }, query)).then(function (r) { | ||
return r.getData(); | ||
}).then(function (result) { | ||
return { items: result.domains.items.map(transformDomain) }; | ||
@@ -60,3 +64,5 @@ }); // TODO: paging? | ||
return xhr.get(uri).then(function (result) { | ||
return xhr.get(uri).then(function (r) { | ||
return r.getData(); | ||
}).then(function (result) { | ||
return _extends({}, result.domainUsers, { | ||
@@ -75,3 +81,5 @@ items: result.domainUsers.items.map(transformDomainUser) | ||
return xhr.get(uri).then(function (result) { | ||
return xhr.get(uri).then(function (r) { | ||
return r.getData(); | ||
}).then(function (result) { | ||
return _extends({}, result.domainProjects, { | ||
@@ -78,0 +86,0 @@ items: result.domainProjects.items.map(function (item) { |
@@ -37,3 +37,5 @@ 'use strict'; | ||
var getDomainSegments = function getDomainSegments(contractId, dataProductId, segmentId, query) { | ||
return xhr.get(routes.interpolate(routes.CONTRACT_DATA_PRODUCT_DOMAIN_SEGMENTS, { contractId: contractId, dataProductId: dataProductId, segmentId: segmentId }, query)).then(function (result) { | ||
return xhr.get(routes.interpolate(routes.CONTRACT_DATA_PRODUCT_DOMAIN_SEGMENTS, { contractId: contractId, dataProductId: dataProductId, segmentId: segmentId }, query)).then(function (r) { | ||
return r.getData(); | ||
}).then(function (result) { | ||
return { items: result.domainSegments.items.map(transformDomainSegment) }; | ||
@@ -44,3 +46,5 @@ }); | ||
var getDomainSegment = function getDomainSegment(contractId, dataProductId, segmentId, domainId, query) { | ||
return xhr.get(routes.interpolate(routes.CONTRACT_DATA_PRODUCT_DOMAIN_SEGMENT, { contractId: contractId, dataProductId: dataProductId, segmentId: segmentId, domainId: domainId }, query)).then(function (result) { | ||
return xhr.get(routes.interpolate(routes.CONTRACT_DATA_PRODUCT_DOMAIN_SEGMENT, { contractId: contractId, dataProductId: dataProductId, segmentId: segmentId, domainId: domainId }, query)).then(function (r) { | ||
return r.getData(); | ||
}).then(function (result) { | ||
return transformDomainSegment(result); | ||
@@ -47,0 +51,0 @@ }); |
@@ -21,3 +21,5 @@ 'use strict'; | ||
segmentId: segmentId | ||
})).then(function (data) { | ||
})).then(function (r) { | ||
return r.getData(); | ||
}).then(function (data) { | ||
return data.logs.map(function (item) { | ||
@@ -24,0 +26,0 @@ return item.log; |
@@ -40,3 +40,5 @@ 'use strict'; | ||
var getDataProductSegments = function getDataProductSegments(contractId, dataProductId) { | ||
return xhr.get(routes.interpolate(routes.CONTRACT_DATA_PRODUCT_SEGMENTS, { contractId: contractId, dataProductId: dataProductId })).then(function (data) { | ||
return xhr.get(routes.interpolate(routes.CONTRACT_DATA_PRODUCT_SEGMENTS, { contractId: contractId, dataProductId: dataProductId })).then(function (r) { | ||
return r.getData(); | ||
}).then(function (data) { | ||
return { | ||
@@ -43,0 +45,0 @@ items: data.segments.items.map(transformSegment), |
@@ -82,3 +82,5 @@ 'use strict'; | ||
return xhr.post(uri, { data: { catalogRequest: catalogRequest } }).then(xhr.parseJSON).then(function (data) { | ||
return xhr.post(uri, { data: { catalogRequest: catalogRequest } }).then(function (r) { | ||
return r.getData(); | ||
}).then(function (data) { | ||
return data.catalogResponse; | ||
@@ -110,3 +112,5 @@ }); | ||
return xhr.post(uri, { data: { dateDataSetsRequest: dateDataSetsRequest } }).then(xhr.parseJSON).then(function (data) { | ||
return xhr.post(uri, { data: { dateDataSetsRequest: dateDataSetsRequest } }).then(function (r) { | ||
return r.getData(); | ||
}).then(function (data) { | ||
return data.dateDataSetsResponse; | ||
@@ -113,0 +117,0 @@ }); |
@@ -115,6 +115,6 @@ 'use strict'; | ||
return xhr.ajax(finalPollingUri, { method: 'GET' }).then(function (r) { | ||
if (r.status === 204) { | ||
if (r.response.status === 204) { | ||
return null; | ||
} | ||
return r.json(); | ||
return r.getData(); | ||
}); | ||
@@ -152,3 +152,5 @@ } | ||
return xhr.post('/gdc/app/projects/' + projectId + '/executeAfm', { body: JSON.stringify(execution) }).then(xhr.parseJSON).then(function (executionResponse) { | ||
return xhr.post('/gdc/app/projects/' + projectId + '/executeAfm', { body: JSON.stringify(execution) }).then(function (r) { | ||
return r.getData(); | ||
}).then(function (executionResponse) { | ||
var offset = Array(dimensionality).fill(0); // offset holds information on dimensionality | ||
@@ -155,0 +157,0 @@ var pollingUri = executionResponse.executionResponse.links.executionResult; |
@@ -491,5 +491,8 @@ 'use strict'; | ||
xhr.ajax(uri, settings).then(function (r) { | ||
if (r.status === 204) { | ||
var response = r.response; | ||
if (response.status === 204) { | ||
return { | ||
status: r.status, | ||
status: response.status, | ||
result: '' | ||
@@ -499,8 +502,6 @@ }; | ||
return r.json().then(function (result) { | ||
return { | ||
status: r.status, | ||
result: result | ||
}; | ||
}); | ||
return { | ||
status: response.status, | ||
result: r.getData() | ||
}; | ||
}).then(function (_ref4) { | ||
@@ -577,7 +578,9 @@ var status = _ref4.status, | ||
body: JSON.stringify(request) | ||
})).then(xhr.parseJSON).then(function (result) { | ||
executedReport.headers = wrapMeasureIndexesFromMappings((0, _lodash.get)(executionConfiguration, 'metricMappings'), (0, _lodash.get)(result, ['executionResult', 'headers'], [])); | ||
})).then(function (r) { | ||
return r.getData(); | ||
}).then(function (response) { | ||
executedReport.headers = wrapMeasureIndexesFromMappings((0, _lodash.get)(executionConfiguration, 'metricMappings'), (0, _lodash.get)(response, ['executionResult', 'headers'], [])); | ||
// Start polling on url returned in the executionResult for tabularData | ||
return loadExtendedDataResults(result.executionResult.extendedTabularDataResult, settings); | ||
return loadExtendedDataResults(response.executionResult.extendedTabularDataResult, settings); | ||
}).then(function (r) { | ||
@@ -584,0 +587,0 @@ var result = r.result, |
@@ -17,2 +17,4 @@ 'use strict'; | ||
var _xhr = require('./xhr'); | ||
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } // Copyright (C) 2007-2014, GoodData(R) Corporation. All rights reserved. | ||
@@ -53,9 +55,7 @@ | ||
}).then(function (r) { | ||
if (!r.ok) { | ||
var err = new Error(r.statusText); | ||
err.response = r; | ||
throw err; | ||
if (!r.response.ok) { | ||
throw new _xhr.ApiResponseError(r.response.statusText, r.response, r.responseBody); | ||
} | ||
return r.json(); | ||
return r.getData(); | ||
}).then(function (result) { | ||
@@ -85,3 +85,5 @@ return (0, _lodash.get)(result, ['objects', 'items']); | ||
return xhr.get(uri).then(function (_ref) { | ||
return xhr.get(uri).then(function (r) { | ||
return r.getData(); | ||
}).then(function (_ref) { | ||
var objects = _ref.objects; | ||
@@ -133,9 +135,9 @@ | ||
}).then(function (r) { | ||
if (!r.ok) { | ||
var err = new Error(r.statusText); | ||
err.response = r; | ||
if (!r.response.ok) { | ||
var err = new Error(r.response.statusText); | ||
err.response = r.response; | ||
throw err; | ||
} | ||
return r.json(); | ||
return r.getData(); | ||
}).then(function (result) { | ||
@@ -179,9 +181,9 @@ return result.entries; | ||
}).then(function (r) { | ||
if (!r.ok) { | ||
var err = new Error(r.statusText); | ||
err.response = r; | ||
if (!r.response.ok) { | ||
var err = new Error(r.response.statusText); | ||
err.response = r.response; | ||
throw err; | ||
} | ||
return r.json(); | ||
return r.getData(); | ||
}).then(function (result) { | ||
@@ -200,4 +202,4 @@ return result.useMany; | ||
function getVisualizations(projectId) { | ||
return xhr.get('/gdc/md/' + projectId + '/query/visualizations').then(function (r) { | ||
return r.ok ? r.json() : r; | ||
return xhr.get('/gdc/md/' + projectId + '/query/visualizations').then(function (apiResponse) { | ||
return apiResponse.response.ok ? apiResponse.getData() : apiResponse.response; | ||
}).then((0, _util.getIn)('query.entries')); | ||
@@ -214,4 +216,4 @@ } | ||
function getAttributes(projectId) { | ||
return xhr.get('/gdc/md/' + projectId + '/query/attributes').then(function (r) { | ||
return r.ok ? r.json() : r; | ||
return xhr.get('/gdc/md/' + projectId + '/query/attributes').then(function (apiResponse) { | ||
return apiResponse.response.ok ? apiResponse.getData() : apiResponse.response; | ||
}).then((0, _util.getIn)('query.entries')); | ||
@@ -229,4 +231,4 @@ } | ||
function getDimensions(projectId) { | ||
return xhr.get('/gdc/md/' + projectId + '/query/dimensions').then(function (r) { | ||
return r.ok ? r.json() : r; | ||
return xhr.get('/gdc/md/' + projectId + '/query/dimensions').then(function (apiResponse) { | ||
return apiResponse.response.ok ? apiResponse.getData() : apiResponse.response; | ||
}).then((0, _util.getIn)('query.entries')); | ||
@@ -248,3 +250,5 @@ } | ||
return xhr.get('/gdc/md/' + pId + '/query/folders' + typeURL).then((0, _util.getIn)('query.entries')); | ||
return xhr.get('/gdc/md/' + pId + '/query/folders' + typeURL).then(function (r) { | ||
return r.getData(); | ||
}).then((0, _util.getIn)('query.entries')); | ||
} | ||
@@ -278,4 +282,4 @@ | ||
function getFacts(projectId) { | ||
return xhr.get('/gdc/md/' + projectId + '/query/facts').then(function (r) { | ||
return r.ok ? r.json() : r; | ||
return xhr.get('/gdc/md/' + projectId + '/query/facts').then(function (apiResponse) { | ||
return apiResponse.response.ok ? apiResponse.getData() : apiResponse.response; | ||
}).then((0, _util.getIn)('query.entries')); | ||
@@ -292,4 +296,4 @@ } | ||
function getMetrics(projectId) { | ||
return xhr.get('/gdc/md/' + projectId + '/query/metrics').then(function (r) { | ||
return r.ok ? r.json() : r; | ||
return xhr.get('/gdc/md/' + projectId + '/query/metrics').then(function (apiResponse) { | ||
return apiResponse.response.ok ? apiResponse.getData() : apiResponse.response; | ||
}).then((0, _util.getIn)('query.entries')); | ||
@@ -313,6 +317,6 @@ } | ||
data: JSON.stringify(attrs) | ||
}).then(function (r) { | ||
return r.ok ? r.json() : r; | ||
}).then(function (r) { | ||
return r.entries; | ||
}).then(function (apiResponse) { | ||
return apiResponse.response.ok ? apiResponse.getData() : apiResponse.response; | ||
}).then(function (data) { | ||
return data.entries; | ||
}); | ||
@@ -336,5 +340,5 @@ } | ||
body: JSON.stringify(metrics) | ||
}).then(function (apiResponse) { | ||
return apiResponse.response.ok ? apiResponse.getData() : apiResponse.response; | ||
}).then(function (r) { | ||
return r.ok ? r.json() : r; | ||
}).then(function (r) { | ||
return r.drillcrosspath.links; | ||
@@ -360,3 +364,3 @@ }); | ||
}).then(function (r) { | ||
return r.ok ? r.json() : r; | ||
return r.response.ok ? r.getData() : r.response; | ||
}).then(function (r) { | ||
@@ -375,3 +379,5 @@ return r.entries; | ||
function getObjectDetails(uri) { | ||
return xhr.get(uri); | ||
return xhr.get(uri).then(function (r) { | ||
return r.getData(); | ||
}); | ||
} | ||
@@ -568,8 +574,8 @@ | ||
function getObjectUri(projectId, identifier) { | ||
return xhr.ajax('/gdc/md/' + projectId + '/identifiers', { | ||
method: 'POST', | ||
return xhr.post('/gdc/md/' + projectId + '/identifiers', { | ||
body: { | ||
identifierToUri: [identifier] | ||
} | ||
}).then(xhr.parseJSON).then(function (data) { | ||
}).then(function (r) { | ||
var data = r.getData(); | ||
var found = data.identifiers.find(function (pair) { | ||
@@ -583,3 +589,3 @@ return pair.identifier === identifier; | ||
throw new Error('Object with identifier ' + identifier + ' not found in project ' + projectId); | ||
throw new _xhr.ApiResponseError('Object with identifier ' + identifier + ' not found in project ' + projectId, r.response, r.responseBody); | ||
}); | ||
@@ -601,3 +607,5 @@ } | ||
} | ||
}).then(xhr.parseJSON).then(function (data) { | ||
}).then(function (r) { | ||
return r.getData(); | ||
}).then(function (data) { | ||
return data.identifiers; | ||
@@ -620,3 +628,5 @@ }); | ||
} | ||
}).then(xhr.parseJSON).then(function (data) { | ||
}).then(function (r) { | ||
return r.getData(); | ||
}).then(function (data) { | ||
return data.identifiers; | ||
@@ -647,5 +657,3 @@ }); | ||
}).then(function (r) { | ||
return r.ok ? r.json() : r; | ||
}).then(function (r) { | ||
return (0, _lodash.get)(r, 'elementLabelUri'); | ||
return r.response.ok ? (0, _lodash.get)(r.getData(), 'elementLabelUri') : r.response; | ||
}); | ||
@@ -686,3 +694,5 @@ } | ||
}) | ||
}).then(xhr.parseJSON); | ||
}).then(function (r) { | ||
return r.getData(); | ||
}); | ||
} | ||
@@ -712,3 +722,5 @@ | ||
data: JSON.stringify(obj) | ||
}).then(xhr.parseJSON); | ||
}).then(function (r) { | ||
return r.getData(); | ||
}); | ||
} | ||
@@ -744,3 +756,5 @@ | ||
}) | ||
}).then(xhr.parseJSON).then(function (response) { | ||
}).then(function (r) { | ||
return r.getData(); | ||
}).then(function (response) { | ||
var manageStatusUri = response.entries[0].link; | ||
@@ -767,3 +781,5 @@ return (0, _util.handlePolling)(xhr.get, manageStatusUri, isTaskFinished, options); | ||
}) | ||
}).then(xhr.parseJSON).then(function (response) { | ||
}).then(function (r) { | ||
return r.getData(); | ||
}).then(function (response) { | ||
var etlPullStatusUri = response.pull2Task.links.poll; | ||
@@ -770,0 +786,0 @@ return (0, _util.handlePolling)(xhr.get, etlPullStatusUri, isTaskFinished, options); |
@@ -34,3 +34,5 @@ 'use strict'; | ||
function getCurrentProjectId() { | ||
return xhr.get('/gdc/app/account/bootstrap').then(function (result) { | ||
return xhr.get('/gdc/app/account/bootstrap').then(function (r) { | ||
return r.getData(); | ||
}).then(function (result) { | ||
var currentProject = result.bootstrapResource.current.project; | ||
@@ -55,2 +57,4 @@ // handle situation in which current project is missing (e.g. new user) | ||
return xhr.get('/gdc/account/profile/' + profileId + '/projects').then(function (r) { | ||
return r.getData(); | ||
}).then(function (r) { | ||
return r.projects.map(function (p) { | ||
@@ -70,3 +74,5 @@ return p.project; | ||
function getDatasets(projectId) { | ||
return xhr.get('/gdc/md/' + projectId + '/query/datasets').then((0, _util.getIn)('query.entries')); | ||
return xhr.get('/gdc/md/' + projectId + '/query/datasets').then(function (r) { | ||
return r.getData(); | ||
}).then((0, _util.getIn)('query.entries')); | ||
} | ||
@@ -84,3 +90,5 @@ | ||
function getColorPalette(projectId) { | ||
return xhr.get('/gdc/projects/' + projectId + '/styleSettings').then(function (result) { | ||
return xhr.get('/gdc/projects/' + projectId + '/styleSettings').then(function (r) { | ||
return r.getData(); | ||
}).then(function (result) { | ||
return result.styleSettings.chartPalette.map(function (c) { | ||
@@ -137,3 +145,5 @@ return { | ||
return xhr.get(bootstrapUrl).then(function (result) { | ||
return xhr.get(bootstrapUrl).then(function (r) { | ||
return r.getData(); | ||
}).then(function (result) { | ||
return result.bootstrapResource.current.timezone; | ||
@@ -152,3 +162,5 @@ }); | ||
body: data | ||
}).then(xhr.parseJSON); | ||
}).then(function (r) { | ||
return r.getData(); | ||
}); | ||
} | ||
@@ -195,3 +207,5 @@ | ||
}) | ||
}).then(xhr.parseJSON).then(function (project) { | ||
}).then(function (r) { | ||
return r.getData(); | ||
}).then(function (project) { | ||
return (0, _util.handlePolling)(xhr.get, project.uri, function (response) { | ||
@@ -198,0 +212,0 @@ return isProjectCreated(response.project); |
@@ -18,6 +18,4 @@ 'use strict'; | ||
return new Promise(function (resolve, reject) { | ||
// cannot use get here directly - we need to access to response | ||
// not to responses JSON get returns | ||
xhr.ajax('/gdc/account/token', { method: 'GET' }).then(function (r) { | ||
if (r.ok) { | ||
xhr.get('/gdc/account/token').then(function (r) { | ||
if (r.response.ok) { | ||
resolve(true); | ||
@@ -57,3 +55,5 @@ } | ||
}) | ||
}).then(xhr.parseJSON); | ||
}).then(function (r) { | ||
return r.getData(); | ||
}); | ||
} | ||
@@ -71,4 +71,3 @@ | ||
function loginSso(sessionId, serverUrl, targetUrl) { | ||
// cannot use xhr.get, server doesn't respond with JSON | ||
return xhr.ajax('/gdc/account/customerlogin?sessionId=' + sessionId + '&serverURL=' + serverUrl + '&targetURL=' + targetUrl, { method: 'GET' }); | ||
return xhr.get('/gdc/account/customerlogin?sessionId=' + sessionId + '&serverURL=' + serverUrl + '&targetURL=' + targetUrl); | ||
} | ||
@@ -84,8 +83,7 @@ | ||
return xhr.get('/gdc/app/account/bootstrap').then(function (result) { | ||
var userUri = result.bootstrapResource.accountSetting.links.self; | ||
var data = result.getData(); | ||
var userUri = data.bootstrapResource.accountSetting.links.self; | ||
var userId = userUri.match(/([^\/]+)\/?$/)[1]; // eslint-disable-line no-useless-escape | ||
return xhr.ajax('/gdc/account/login/' + userId, { | ||
method: 'delete' | ||
}); | ||
return xhr.del('/gdc/account/login/' + userId); | ||
}); | ||
@@ -95,2 +93,4 @@ } | ||
return Promise.resolve(); | ||
}, function (err) { | ||
return Promise.reject(err); | ||
}); | ||
@@ -117,10 +117,12 @@ } | ||
return xhr.get('/gdc/app/account/bootstrap').then(function (result) { | ||
var br = result.bootstrapResource; | ||
var _result$getData = result.getData(), | ||
bootstrapResource = _result$getData.bootstrapResource; | ||
var accountInfo = { | ||
login: br.accountSetting.login, | ||
loginMD5: br.current.loginMD5, | ||
firstName: br.accountSetting.firstName, | ||
lastName: br.accountSetting.lastName, | ||
organizationName: br.settings.organizationName, | ||
profileUri: br.accountSetting.links.self | ||
login: bootstrapResource.accountSetting.login, | ||
loginMD5: bootstrapResource.current.loginMD5, | ||
firstName: bootstrapResource.accountSetting.firstName, | ||
lastName: bootstrapResource.accountSetting.lastName, | ||
organizationName: bootstrapResource.settings.organizationName, | ||
profileUri: bootstrapResource.accountSetting.links.self | ||
}; | ||
@@ -137,3 +139,5 @@ | ||
function getFeatureFlags() { | ||
return xhr.get('/gdc/app/account/bootstrap').then(function (result) { | ||
return xhr.get('/gdc/app/account/bootstrap').then(function (r) { | ||
return r.getData(); | ||
}).then(function (result) { | ||
return result.bootstrapResource.current.featureFlags; | ||
@@ -140,0 +144,0 @@ }); |
@@ -63,3 +63,5 @@ 'use strict'; | ||
return xhrGet(uri).then(function (response) { | ||
return xhrGet(uri).then(function (r) { | ||
return r.getData(); | ||
}).then(function (response) { | ||
if (attempts > maxAttempts) { | ||
@@ -66,0 +68,0 @@ return Promise.reject(new Error(response)); |
430
lib/xhr.js
@@ -6,6 +6,7 @@ 'use strict'; | ||
}); | ||
exports.originPackageHeaders = exports.parseJSON = undefined; | ||
exports.ApiResponse = exports.ApiNetworkError = exports.ApiResponseError = exports.ApiError = exports.originPackageHeaders = undefined; | ||
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; // Copyright (C) 2007-2013, GoodData(R) Corporation. All rights reserved. | ||
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; | ||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); | ||
@@ -25,2 +26,11 @@ exports.handlePolling = handlePolling; | ||
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } | ||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } | ||
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } // Copyright (C) 2007-2013, GoodData(R) Corporation. All rights reserved. | ||
/** | ||
@@ -40,3 +50,3 @@ * Ajax wrapper around GDC authentication mechanisms, SST and TT token handling and polling. | ||
function simulateBeforeSend(settings, url) { | ||
function simulateBeforeSend(url, settings) { | ||
var xhrMockInBeforeSend = { | ||
@@ -68,32 +78,2 @@ setRequestHeader: function setRequestHeader(key, value) { | ||
function isLoginRequest(url) { | ||
return url.indexOf('/gdc/account/login') !== -1; | ||
} | ||
/** | ||
* @param {Response} response | ||
* @return {Promise} promise which resolves to result JSON () | ||
*/ | ||
var parseJSON = exports.parseJSON = function parseJSON(response) { | ||
return response.json(); | ||
}; | ||
/** | ||
* @param {Response} response see https://developer.mozilla.org/en-US/docs/Web/API/Response | ||
* @return {Response} or {Error} | ||
*/ | ||
var checkStatus = function checkStatus(response) { | ||
if (response.status >= 200 && response.status < 399) { | ||
return response; | ||
} | ||
if (response instanceof Error && (0, _lodash.has)(response, 'response')) { | ||
throw response; | ||
} | ||
var error = new Error(response.statusText); | ||
error.response = response; | ||
throw error; | ||
}; | ||
function handlePolling(url, settings, sendRequest) { | ||
@@ -118,5 +98,250 @@ var pollingDelay = (0, _lodash.result)(settings, 'pollDelay'); | ||
var ApiError = exports.ApiError = function (_Error) { | ||
_inherits(ApiError, _Error); | ||
function ApiError(message, cause) { | ||
_classCallCheck(this, ApiError); | ||
var _this = _possibleConstructorReturn(this, (ApiError.__proto__ || Object.getPrototypeOf(ApiError)).call(this, message)); | ||
_this.cause = cause; | ||
return _this; | ||
} | ||
return ApiError; | ||
}(Error); | ||
var ApiResponseError = exports.ApiResponseError = function (_ApiError) { | ||
_inherits(ApiResponseError, _ApiError); | ||
function ApiResponseError(message, response, responseBody) { | ||
_classCallCheck(this, ApiResponseError); | ||
var _this2 = _possibleConstructorReturn(this, (ApiResponseError.__proto__ || Object.getPrototypeOf(ApiResponseError)).call(this, message, null)); | ||
_this2.response = response; | ||
_this2.responseBody = responseBody; | ||
return _this2; | ||
} | ||
return ApiResponseError; | ||
}(ApiError); | ||
var ApiNetworkError = exports.ApiNetworkError = function (_ApiError2) { | ||
_inherits(ApiNetworkError, _ApiError2); | ||
function ApiNetworkError() { | ||
_classCallCheck(this, ApiNetworkError); | ||
return _possibleConstructorReturn(this, (ApiNetworkError.__proto__ || Object.getPrototypeOf(ApiNetworkError)).apply(this, arguments)); | ||
} | ||
return ApiNetworkError; | ||
}(ApiError); | ||
var ApiResponse = exports.ApiResponse = function () { | ||
function ApiResponse(response, responseBody) { | ||
_classCallCheck(this, ApiResponse); | ||
this.response = response; | ||
this.responseBody = responseBody; | ||
} | ||
_createClass(ApiResponse, [{ | ||
key: 'getData', | ||
value: function getData() { | ||
try { | ||
return JSON.parse(this.responseBody); | ||
} catch (error) { | ||
return this.responseBody; | ||
} | ||
} | ||
}, { | ||
key: 'data', | ||
get: function get() { | ||
try { | ||
return JSON.parse(this.responseBody); | ||
} catch (error) { | ||
return this.responseBody; | ||
} | ||
} | ||
}]); | ||
return ApiResponse; | ||
}(); | ||
function createModule(configStorage) { | ||
var tokenRequest = void 0; // TODO make app-wide persitent (ie. extract outside of the SDK) | ||
var handleUnauthorized = function () { | ||
var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(originalUrl, originalSettings) { | ||
var _enrichSettingWithCus, url, settings, response, responseBody; | ||
return regeneratorRuntime.wrap(function _callee2$(_context2) { | ||
while (1) { | ||
switch (_context2.prev = _context2.next) { | ||
case 0: | ||
if (!tokenRequest) { | ||
_context2.next = 2; | ||
break; | ||
} | ||
return _context2.abrupt('return', continueAfterTokenRequest(originalUrl, originalSettings)); | ||
case 2: | ||
_enrichSettingWithCus = enrichSettingWithCustomDomain('/gdc/account/token', createRequestSettings({}), configStorage.domain), url = _enrichSettingWithCus.url, settings = _enrichSettingWithCus.settings; | ||
tokenRequest = (0, _fetch2.default)(url, settings); | ||
_context2.next = 6; | ||
return tokenRequest; | ||
case 6: | ||
response = _context2.sent; | ||
_context2.next = 9; | ||
return response.text(); | ||
case 9: | ||
responseBody = _context2.sent; | ||
tokenRequest = null; | ||
// TODO jquery compat - allow to attach unauthorized callback and call it if attached | ||
// if ((xhrObj.status === 401) && (isFunction(req.unauthorized))) { | ||
// req.unauthorized(xhrObj, textStatus, err, deferred); | ||
// return; | ||
// } | ||
// unauthorized handler is not defined or not http 401 | ||
// unauthorized when retrieving token -> not logged | ||
if (!(response.status === 401)) { | ||
_context2.next = 13; | ||
break; | ||
} | ||
throw new ApiResponseError('Unauthorized', response, responseBody); | ||
case 13: | ||
return _context2.abrupt('return', new ApiResponse(response, responseBody)); | ||
case 14: | ||
case 'end': | ||
return _context2.stop(); | ||
} | ||
} | ||
}, _callee2, this); | ||
})); | ||
return function handleUnauthorized(_x2, _x3) { | ||
return _ref3.apply(this, arguments); | ||
}; | ||
}(); | ||
var ajax = function () { | ||
var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(originalUrl) { | ||
var customSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
var firstSettings, _enrichSettingWithCus2, url, settings, response, responseBody, finalUrl, finalSettings; | ||
return regeneratorRuntime.wrap(function _callee3$(_context3) { | ||
while (1) { | ||
switch (_context3.prev = _context3.next) { | ||
case 0: | ||
// TODO refactor to: getRequestParams(originalUrl, customSettings); | ||
firstSettings = createRequestSettings(customSettings); | ||
_enrichSettingWithCus2 = enrichSettingWithCustomDomain(originalUrl, firstSettings, configStorage.domain), url = _enrichSettingWithCus2.url, settings = _enrichSettingWithCus2.settings; | ||
simulateBeforeSend(url, settings); // mutates `settings` param | ||
if (!tokenRequest) { | ||
_context3.next = 5; | ||
break; | ||
} | ||
return _context3.abrupt('return', continueAfterTokenRequest(url, settings)); | ||
case 5: | ||
response = void 0; | ||
_context3.prev = 6; | ||
_context3.next = 9; | ||
return (0, _fetch2.default)(url, settings); | ||
case 9: | ||
response = _context3.sent; | ||
_context3.next = 15; | ||
break; | ||
case 12: | ||
_context3.prev = 12; | ||
_context3.t0 = _context3['catch'](6); | ||
throw new ApiNetworkError(_context3.t0.message, _context3.t0); | ||
case 15: | ||
_context3.next = 17; | ||
return response.text(); | ||
case 17: | ||
responseBody = _context3.sent; | ||
if (!(response.status === 401)) { | ||
_context3.next = 22; | ||
break; | ||
} | ||
if (!(url.indexOf('/gdc/account/login') !== -1)) { | ||
_context3.next = 21; | ||
break; | ||
} | ||
throw new ApiResponseError('Unauthorized', response, responseBody); | ||
case 21: | ||
return _context3.abrupt('return', handleUnauthorized(url, settings)); | ||
case 22: | ||
if (!(response.status === 202 && !settings.dontPollOnResult)) { | ||
_context3.next = 30; | ||
break; | ||
} | ||
// poll on new provided url, fallback to the original one | ||
// (for example validElements returns 303 first with new url which may then return 202 to poll on) | ||
finalUrl = response.url || url; | ||
finalSettings = settings; | ||
// if the response is 202 and Location header is not empty, let's poll on the new Location | ||
if (response.headers.has('Location')) { | ||
finalUrl = response.headers.get('Location'); | ||
} | ||
finalSettings.method = 'GET'; | ||
delete finalSettings.data; | ||
delete finalSettings.body; | ||
return _context3.abrupt('return', handlePolling(finalUrl, finalSettings, ajax)); | ||
case 30: | ||
if (!(response.status >= 200 && response.status <= 399)) { | ||
_context3.next = 32; | ||
break; | ||
} | ||
return _context3.abrupt('return', new ApiResponse(response, responseBody)); | ||
case 32: | ||
throw new ApiResponseError(response.statusText, response, responseBody); | ||
case 33: | ||
case 'end': | ||
return _context3.stop(); | ||
} | ||
} | ||
}, _callee3, this, [[6, 12]]); | ||
})); | ||
return function ajax(_x4) { | ||
return _ref4.apply(this, arguments); | ||
}; | ||
}(); | ||
var tokenRequest = void 0; // TODO make app-wide persistent (ie. extract outside of the SDK) | ||
(0, _lodash.defaults)(configStorage, { xhrSettings: {} }); | ||
@@ -158,110 +383,42 @@ | ||
function continueAfterTokenRequest(url, settings) { | ||
return tokenRequest.then(function (response) { | ||
if (!response.ok) { | ||
var err = new Error('Unauthorized'); | ||
err.response = response; | ||
throw err; | ||
} | ||
tokenRequest = null; | ||
var _this4 = this; | ||
return ajax(url, settings); // eslint-disable-line no-use-before-define | ||
}, function (reason) { | ||
tokenRequest = null; | ||
return reason; | ||
}); | ||
} | ||
return tokenRequest.then(function () { | ||
var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(response) { | ||
return regeneratorRuntime.wrap(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
if (response.ok) { | ||
_context.next = 2; | ||
break; | ||
} | ||
function handleUnauthorized(originalUrl, originalSettings) { | ||
if (!tokenRequest) { | ||
// Create only single token request for any number of waiting request. | ||
// If token request exist, just listen for it's end. | ||
var _enrichSettingWithCus = enrichSettingWithCustomDomain('/gdc/account/token', createRequestSettings({}), configStorage.domain), | ||
url = _enrichSettingWithCus.url, | ||
settings = _enrichSettingWithCus.settings; | ||
throw new ApiResponseError('Unauthorized', response, null); | ||
tokenRequest = (0, _fetch2.default)(url, settings).then(function (response) { | ||
// tokenRequest = null; | ||
// TODO jquery compat - allow to attach unauthorized callback and call it if attached | ||
// if ((xhrObj.status === 401) && (isFunction(req.unauthorized))) { | ||
// req.unauthorized(xhrObj, textStatus, err, deferred); | ||
// return; | ||
// } | ||
// unauthorized handler is not defined or not http 401 | ||
// unauthorized when retrieving token -> not logged | ||
if (response.status === 401) { | ||
var err = new Error('Unauthorized'); | ||
err.response = response; | ||
throw err; | ||
} | ||
case 2: | ||
tokenRequest = null; | ||
return response; | ||
}); | ||
} | ||
return continueAfterTokenRequest(originalUrl, originalSettings); | ||
} | ||
return _context.abrupt('return', ajax(url, settings)); | ||
function ajax(originalUrl) { | ||
var customSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
case 4: | ||
case 'end': | ||
return _context.stop(); | ||
} | ||
} | ||
}, _callee, _this4); | ||
})); | ||
// TODO refactor to: getRequestParams(originalUrl, customSettings); | ||
var firstSettings = createRequestSettings(customSettings); | ||
var _enrichSettingWithCus2 = enrichSettingWithCustomDomain(originalUrl, firstSettings, configStorage.domain), | ||
url = _enrichSettingWithCus2.url, | ||
settings = _enrichSettingWithCus2.settings; | ||
simulateBeforeSend(settings, url); // mutates `settings` param | ||
if (tokenRequest) { | ||
return continueAfterTokenRequest(url, settings); | ||
} | ||
return (0, _fetch2.default)(url, settings).then(function (response) { | ||
// If response.status id 401 and it was a login request there is no need | ||
// to cycle back for token - login does not need token and this meant you | ||
// are not authorized | ||
if (response.status === 401) { | ||
if (isLoginRequest(url)) { | ||
var err = new Error('Unauthorized'); | ||
err.response = response; | ||
throw err; | ||
} | ||
return handleUnauthorized(url, settings); | ||
} | ||
if (response.status === 202 && !settings.dontPollOnResult) { | ||
// poll on new provided url, fallback to the original one | ||
// (for example validElements returns 303 first with new url which may then return 202 to poll on) | ||
var finalUrl = response.url || url; | ||
var finalSettings = settings; | ||
// if the response is 202 and Location header is not empty, let's poll on the new Location | ||
if (response.headers.has('Location')) { | ||
finalUrl = response.headers.get('Location'); | ||
} | ||
finalSettings.method = 'GET'; | ||
delete finalSettings.data; | ||
delete finalSettings.body; | ||
return handlePolling(finalUrl, finalSettings, ajax); | ||
} | ||
return response; | ||
}).then(checkStatus); | ||
return function (_x) { | ||
return _ref2.apply(this, arguments); | ||
}; | ||
}(), function (reason) { | ||
tokenRequest = null; | ||
return reason; | ||
}); | ||
} | ||
/** | ||
* Wrapper for xhr.ajax method GET | ||
* @method get | ||
*/ | ||
var get = function get(url, settings) { | ||
var opts = (0, _lodash.merge)({ method: 'GET' }, settings); | ||
return ajax(url, opts).then(parseJSON); | ||
}; | ||
function xhrMethod(method) { | ||
return function methodFn(url, settings) { | ||
return function xhrMethodFn(url, settings) { | ||
var opts = (0, _lodash.merge)({ method: method }, settings); | ||
return ajax(url, opts); | ||
@@ -272,2 +429,8 @@ }; | ||
/** | ||
* Wrapper for xhr.ajax method GET | ||
* @method get | ||
*/ | ||
var get = xhrMethod('GET'); | ||
/** | ||
* Wrapper for xhr.ajax method POST | ||
@@ -296,5 +459,4 @@ * @method post | ||
ajax: ajax, | ||
ajaxSetup: ajaxSetup, | ||
parseJSON: parseJSON | ||
ajaxSetup: ajaxSetup | ||
}; | ||
} |
{ | ||
"name": "gooddata", | ||
"version": "6.0.0-alpha2", | ||
"version": "6.0.0-lhorak-pzb-650-apierror-2018-03-19T13-08-13-400Z", | ||
"author": "GoodData", | ||
@@ -5,0 +5,0 @@ "description": "GoodData JavaScript SDK", |
@@ -34,3 +34,4 @@ import * as routes from './routes'; | ||
return xhr.get(uri).then(result => transformClient(result)); | ||
return xhr | ||
.get(uri).then(r => r.getData()).then(result => transformClient(result)); | ||
}; | ||
@@ -49,6 +50,8 @@ | ||
if (uri) { | ||
return xhr.get(uri).then(result => ({ | ||
items: result.clients.items.map(transformClient), | ||
paging: result.clients.paging | ||
})); | ||
return xhr.get(uri) | ||
.then(r => r.getData()) | ||
.then(result => ({ | ||
items: result.clients.items.map(transformClient), | ||
paging: result.clients.paging | ||
})); | ||
} | ||
@@ -72,6 +75,8 @@ | ||
return xhr.get(uri).then(result => ({ | ||
...result.clientUsers, | ||
items: result.clientUsers.items.map(transformClientUser) | ||
})); | ||
return xhr.get(uri) | ||
.then((r => r.getData())) | ||
.then(result => ({ | ||
...result.clientUsers, | ||
items: result.clientUsers.items.map(transformClientUser) | ||
})); | ||
}; | ||
@@ -78,0 +83,0 @@ |
import * as routes from './routes'; | ||
export function createModule(xhr) { | ||
const getUserContracts = () => xhr.get(routes.CONTRACTS).then(data => ({ | ||
items: data.contracts.items.map(item => item.contract), | ||
paging: data.contracts.paging | ||
})); | ||
const getUserContracts = () => xhr.get(routes.CONTRACTS) | ||
.then((r => r.getData())) | ||
.then(data => ({ | ||
items: data.contracts.items.map(item => item.contract), | ||
paging: data.contracts.paging | ||
})); | ||
@@ -9,0 +11,0 @@ return { |
@@ -27,2 +27,3 @@ import * as routes from './routes'; | ||
xhr.get(routes.interpolate(routes.CONTRACT_DATA_PRODUCTS, { contractId }, include && { include })) | ||
.then((r => r.getData())) | ||
.then(data => ({ | ||
@@ -37,2 +38,3 @@ items: data.dataProducts.items.map(transformDataProduct) | ||
)) | ||
.then((r => r.getData())) | ||
.then(data => transformDataProduct(data)); | ||
@@ -39,0 +41,0 @@ |
@@ -18,2 +18,3 @@ import * as routes from './routes'; | ||
xhr.get(routes.interpolate(routes.CONTRACT_DATA_PRODUCT_DOMAIN_DATA_PRODUCTS, { contractId, dataProductId })) | ||
.then((r => r.getData())) | ||
.then(({ domainDataProducts: { items }, status }) => ({ | ||
@@ -20,0 +21,0 @@ items: items.map(transformDomainDataProduct), |
@@ -26,3 +26,5 @@ import * as routes from './routes'; | ||
return xhr.get(uri).then(transformDomain); | ||
return xhr.get(uri) | ||
.then((r => r.getData())) | ||
.then(transformDomain); | ||
}; | ||
@@ -32,2 +34,3 @@ | ||
return xhr.get(routes.interpolate(routes.CONTRACT_DOMAINS, { contractId }, query)) | ||
.then((r => r.getData())) | ||
.then(result => ({ items: result.domains.items.map(transformDomain) })); // TODO: paging? | ||
@@ -44,6 +47,8 @@ }; | ||
return xhr.get(uri).then(result => ({ | ||
...result.domainUsers, | ||
items: result.domainUsers.items.map(transformDomainUser) | ||
})); | ||
return xhr.get(uri) | ||
.then((r => r.getData())) | ||
.then(result => ({ | ||
...result.domainUsers, | ||
items: result.domainUsers.items.map(transformDomainUser) | ||
})); | ||
}; | ||
@@ -63,6 +68,8 @@ | ||
return xhr.get(uri).then(result => ({ | ||
...result.domainProjects, | ||
items: result.domainProjects.items.map(item => item.project) | ||
})); | ||
return xhr.get(uri) | ||
.then((r => r.getData())) | ||
.then(result => ({ | ||
...result.domainProjects, | ||
items: result.domainProjects.items.map(item => item.project) | ||
})); | ||
}; | ||
@@ -69,0 +76,0 @@ |
@@ -25,2 +25,3 @@ import { omit } from 'lodash'; | ||
)) | ||
.then((r => r.getData())) | ||
.then(result => ({ items: result.domainSegments.items.map(transformDomainSegment) })); | ||
@@ -35,2 +36,3 @@ }; | ||
)) | ||
.then((r => r.getData())) | ||
.then(result => transformDomainSegment(result)); | ||
@@ -37,0 +39,0 @@ }; |
@@ -10,3 +10,5 @@ import * as routes from './routes'; | ||
segmentId | ||
})).then(data => data.logs.map(item => item.log)); | ||
})) | ||
.then((r => r.getData())) | ||
.then(data => data.logs.map(item => item.log)); | ||
@@ -13,0 +15,0 @@ return { |
@@ -25,2 +25,3 @@ import * as routes from './routes'; | ||
xhr.get(routes.interpolate(routes.CONTRACT_DATA_PRODUCT_SEGMENTS, { contractId, dataProductId })) | ||
.then((r => r.getData())) | ||
.then(data => ({ | ||
@@ -27,0 +28,0 @@ items: data.segments.items.map(transformSegment), |
@@ -70,3 +70,3 @@ import { get, find, omit, cloneDeep } from 'lodash'; | ||
return xhr.post(uri, { data: { catalogRequest } }) | ||
.then(xhr.parseJSON) | ||
.then((r => r.getData())) | ||
.then(data => data.catalogResponse); | ||
@@ -105,3 +105,3 @@ } | ||
return xhr.post(uri, { data: { dateDataSetsRequest } }) | ||
.then(xhr.parseJSON) | ||
.then((r => r.getData())) | ||
.then(data => data.dateDataSetsResponse); | ||
@@ -108,0 +108,0 @@ } |
@@ -75,6 +75,6 @@ // Copyright (C) 2007-2014, GoodData(R) Corporation. All rights reserved. | ||
return xhr.ajax(finalPollingUri, { method: 'GET' }).then((r) => { | ||
if (r.status === 204) { | ||
if (r.response.status === 204) { | ||
return null; | ||
} | ||
return r.json(); | ||
return r.getData(); | ||
}); | ||
@@ -113,3 +113,3 @@ } | ||
return xhr.post(`/gdc/app/projects/${projectId}/executeAfm`, { body: JSON.stringify(execution) }) | ||
.then(xhr.parseJSON) | ||
.then((r => r.getData())) | ||
.then((executionResponse) => { | ||
@@ -116,0 +116,0 @@ const offset = Array(dimensionality).fill(0); // offset holds information on dimensionality |
@@ -488,5 +488,7 @@ // Copyright (C) 2007-2014, GoodData(R) Corporation. All rights reserved. | ||
.then((r) => { | ||
if (r.status === 204) { | ||
const { response } = r; | ||
if (response.status === 204) { | ||
return { | ||
status: r.status, | ||
status: response.status, | ||
result: '' | ||
@@ -496,8 +498,6 @@ }; | ||
return r.json().then((result) => { | ||
return { | ||
status: r.status, | ||
result | ||
}; | ||
}); | ||
return { | ||
status: response.status, | ||
result: r.getData() | ||
}; | ||
}) | ||
@@ -577,9 +577,9 @@ .then(({ status, result }) => { | ||
}) | ||
.then(xhr.parseJSON) | ||
.then((result) => { | ||
.then((r => r.getData())) | ||
.then((response) => { | ||
executedReport.headers = wrapMeasureIndexesFromMappings( | ||
get(executionConfiguration, 'metricMappings'), get(result, ['executionResult', 'headers'], [])); | ||
get(executionConfiguration, 'metricMappings'), get(response, ['executionResult', 'headers'], [])); | ||
// Start polling on url returned in the executionResult for tabularData | ||
return loadExtendedDataResults(result.executionResult.extendedTabularDataResult, settings); | ||
return loadExtendedDataResults(response.executionResult.extendedTabularDataResult, settings); | ||
}) | ||
@@ -586,0 +586,0 @@ .then((r) => { |
@@ -10,2 +10,3 @@ // Copyright (C) 2007-2014, GoodData(R) Corporation. All rights reserved. | ||
import { getIn, handlePolling, queryString } from './util'; | ||
import { ApiResponseError } from './xhr'; | ||
@@ -44,9 +45,7 @@ /** | ||
}).then((r) => { | ||
if (!r.ok) { | ||
const err = new Error(r.statusText); | ||
err.response = r; | ||
throw err; | ||
if (!r.response.ok) { | ||
throw new ApiResponseError(r.response.statusText, r.response, r.responseBody); | ||
} | ||
return r.json(); | ||
return r.getData(); | ||
}).then(result => _get(result, ['objects', 'items'])); | ||
@@ -73,2 +72,3 @@ }); | ||
return xhr.get(uri) | ||
.then((r => r.getData())) | ||
.then(({ objects }) => { | ||
@@ -114,9 +114,9 @@ items.push(...objects.items); | ||
}).then((r) => { | ||
if (!r.ok) { | ||
const err = new Error(r.statusText); | ||
err.response = r; | ||
if (!r.response.ok) { | ||
const err = new Error(r.response.statusText); | ||
err.response = r.response; | ||
throw err; | ||
} | ||
return r.json(); | ||
return r.getData(); | ||
}).then(result => result.entries); | ||
@@ -153,9 +153,9 @@ } | ||
}).then((r) => { | ||
if (!r.ok) { | ||
const err = new Error(r.statusText); | ||
err.response = r; | ||
if (!r.response.ok) { | ||
const err = new Error(r.response.statusText); | ||
err.response = r.response; | ||
throw err; | ||
} | ||
return r.json(); | ||
return r.getData(); | ||
}).then(result => result.useMany); | ||
@@ -172,3 +172,5 @@ } | ||
function getVisualizations(projectId) { | ||
return xhr.get(`/gdc/md/${projectId}/query/visualizations`).then(r => (r.ok ? r.json() : r)).then(getIn('query.entries')); | ||
return xhr.get(`/gdc/md/${projectId}/query/visualizations`) | ||
.then(apiResponse => (apiResponse.response.ok ? apiResponse.getData() : apiResponse.response)) | ||
.then(getIn('query.entries')); | ||
} | ||
@@ -184,3 +186,5 @@ | ||
function getAttributes(projectId) { | ||
return xhr.get(`/gdc/md/${projectId}/query/attributes`).then(r => (r.ok ? r.json() : r)).then(getIn('query.entries')); | ||
return xhr.get(`/gdc/md/${projectId}/query/attributes`) | ||
.then(apiResponse => (apiResponse.response.ok ? apiResponse.getData() : apiResponse.response)) | ||
.then(getIn('query.entries')); | ||
} | ||
@@ -197,3 +201,5 @@ | ||
function getDimensions(projectId) { | ||
return xhr.get(`/gdc/md/${projectId}/query/dimensions`).then(r => (r.ok ? r.json() : r)).then(getIn('query.entries')); | ||
return xhr.get(`/gdc/md/${projectId}/query/dimensions`) | ||
.then(apiResponse => (apiResponse.response.ok ? apiResponse.getData() : apiResponse.response)) | ||
.then(getIn('query.entries')); | ||
} | ||
@@ -214,3 +220,5 @@ | ||
return xhr.get(`/gdc/md/${pId}/query/folders${typeURL}`).then(getIn('query.entries')); | ||
return xhr.get(`/gdc/md/${pId}/query/folders${typeURL}`) | ||
.then((r => r.getData())) | ||
.then(getIn('query.entries')); | ||
} | ||
@@ -244,3 +252,5 @@ | ||
function getFacts(projectId) { | ||
return xhr.get(`/gdc/md/${projectId}/query/facts`).then(r => (r.ok ? r.json() : r)).then(getIn('query.entries')); | ||
return xhr.get(`/gdc/md/${projectId}/query/facts`) | ||
.then(apiResponse => (apiResponse.response.ok ? apiResponse.getData() : apiResponse.response)) | ||
.then(getIn('query.entries')); | ||
} | ||
@@ -256,3 +266,5 @@ | ||
function getMetrics(projectId) { | ||
return xhr.get(`/gdc/md/${projectId}/query/metrics`).then(r => (r.ok ? r.json() : r)).then(getIn('query.entries')); | ||
return xhr.get(`/gdc/md/${projectId}/query/metrics`) | ||
.then(apiResponse => (apiResponse.response.ok ? apiResponse.getData() : apiResponse.response)) | ||
.then(getIn('query.entries')); | ||
} | ||
@@ -275,3 +287,5 @@ | ||
data: JSON.stringify(attrs) | ||
}).then(r => (r.ok ? r.json() : r)).then(r => r.entries); | ||
}) | ||
.then(apiResponse => (apiResponse.response.ok ? apiResponse.getData() : apiResponse.response)) | ||
.then(data => data.entries); | ||
} | ||
@@ -294,3 +308,5 @@ | ||
body: JSON.stringify(metrics) | ||
}).then(r => (r.ok ? r.json() : r)).then(r => r.drillcrosspath.links); | ||
}) | ||
.then(apiResponse => (apiResponse.response.ok ? apiResponse.getData() : apiResponse.response)) | ||
.then(r => r.drillcrosspath.links); | ||
} | ||
@@ -313,3 +329,3 @@ | ||
data: JSON.stringify(items) | ||
}).then(r => (r.ok ? r.json() : r)).then(r => r.entries); | ||
}).then(r => (r.response.ok ? r.getData() : r.response)).then(r => r.entries); | ||
} | ||
@@ -325,3 +341,3 @@ | ||
function getObjectDetails(uri) { | ||
return xhr.get(uri); | ||
return xhr.get(uri).then((r => r.getData())); | ||
} | ||
@@ -506,8 +522,8 @@ | ||
function getObjectUri(projectId, identifier) { | ||
return xhr.ajax(`/gdc/md/${projectId}/identifiers`, { | ||
method: 'POST', | ||
return xhr.post(`/gdc/md/${projectId}/identifiers`, { | ||
body: { | ||
identifierToUri: [identifier] | ||
} | ||
}).then(xhr.parseJSON).then((data) => { | ||
}).then((r) => { | ||
const data = r.getData(); | ||
const found = data.identifiers.find(pair => pair.identifier === identifier); | ||
@@ -519,3 +535,3 @@ | ||
throw new Error(`Object with identifier ${identifier} not found in project ${projectId}`); | ||
throw new ApiResponseError(`Object with identifier ${identifier} not found in project ${projectId}`, r.response, r.responseBody); | ||
}); | ||
@@ -537,3 +553,3 @@ } | ||
} | ||
}).then(xhr.parseJSON).then((data) => { | ||
}).then((r => r.getData())).then((data) => { | ||
return data.identifiers; | ||
@@ -556,3 +572,3 @@ }); | ||
} | ||
}).then(xhr.parseJSON).then((data) => { | ||
}).then((r => r.getData())).then((data) => { | ||
return data.identifiers; | ||
@@ -582,3 +598,3 @@ }); | ||
} | ||
}).then(r => (r.ok ? r.json() : r)).then(r => _get(r, 'elementLabelUri')); | ||
}).then(r => (r.response.ok ? _get(r.getData(), 'elementLabelUri') : r.response)); | ||
} | ||
@@ -616,3 +632,3 @@ | ||
}) | ||
}).then(xhr.parseJSON); | ||
}).then((r => r.getData())); | ||
} | ||
@@ -642,3 +658,3 @@ | ||
data: JSON.stringify(obj) | ||
}).then(xhr.parseJSON); | ||
}).then((r => r.getData())); | ||
} | ||
@@ -673,3 +689,3 @@ | ||
}) | ||
.then(xhr.parseJSON) | ||
.then((r => r.getData())) | ||
.then((response) => { | ||
@@ -697,3 +713,3 @@ const manageStatusUri = response.entries[0].link; | ||
}) | ||
.then(xhr.parseJSON) | ||
.then((r => r.getData())) | ||
.then((response) => { | ||
@@ -700,0 +716,0 @@ const etlPullStatusUri = response.pull2Task.links.poll; |
@@ -47,11 +47,13 @@ // Copyright (C) 2007-2014, GoodData(R) Corporation. All rights reserved. | ||
function getCurrentProjectId() { | ||
return xhr.get('/gdc/app/account/bootstrap').then((result) => { | ||
const currentProject = result.bootstrapResource.current.project; | ||
// handle situation in which current project is missing (e.g. new user) | ||
if (!currentProject) { | ||
return null; | ||
} | ||
return xhr.get('/gdc/app/account/bootstrap') | ||
.then(r => r.getData()) | ||
.then((result) => { | ||
const currentProject = result.bootstrapResource.current.project; | ||
// handle situation in which current project is missing (e.g. new user) | ||
if (!currentProject) { | ||
return null; | ||
} | ||
return result.bootstrapResource.current.project.links.self.split('/').pop(); | ||
}); | ||
return result.bootstrapResource.current.project.links.self.split('/').pop(); | ||
}); | ||
} | ||
@@ -67,5 +69,7 @@ | ||
function getProjects(profileId) { | ||
return xhr.get(`/gdc/account/profile/${profileId}/projects`).then((r) => { | ||
return r.projects.map(p => p.project); | ||
}); | ||
return xhr.get(`/gdc/account/profile/${profileId}/projects`) | ||
.then(r => r.getData()) | ||
.then((r) => { | ||
return r.projects.map(p => p.project); | ||
}); | ||
} | ||
@@ -81,3 +85,5 @@ | ||
function getDatasets(projectId) { | ||
return xhr.get(`/gdc/md/${projectId}/query/datasets`).then(getIn('query.entries')); | ||
return xhr.get(`/gdc/md/${projectId}/query/datasets`) | ||
.then(r => r.getData()) | ||
.then(getIn('query.entries')); | ||
} | ||
@@ -95,17 +101,19 @@ | ||
function getColorPalette(projectId) { | ||
return xhr.get(`/gdc/projects/${projectId}/styleSettings`).then((result) => { | ||
return result.styleSettings.chartPalette.map((c) => { | ||
return { | ||
r: c.fill.r, | ||
g: c.fill.g, | ||
b: c.fill.b | ||
}; | ||
return xhr.get(`/gdc/projects/${projectId}/styleSettings`) | ||
.then(r => r.getData()) | ||
.then((result) => { | ||
return result.styleSettings.chartPalette.map((c) => { | ||
return { | ||
r: c.fill.r, | ||
g: c.fill.g, | ||
b: c.fill.b | ||
}; | ||
}); | ||
}, (err) => { | ||
if (err.status === 200) { | ||
return DEFAULT_PALETTE; | ||
} | ||
throw new Error(err.statusText); | ||
}); | ||
}, (err) => { | ||
if (err.status === 200) { | ||
return DEFAULT_PALETTE; | ||
} | ||
throw new Error(err.statusText); | ||
}); | ||
} | ||
@@ -148,5 +156,7 @@ | ||
return xhr.get(bootstrapUrl).then((result) => { | ||
return result.bootstrapResource.current.timezone; | ||
}); | ||
return xhr.get(bootstrapUrl) | ||
.then((r => r.getData())) | ||
.then((result) => { | ||
return result.bootstrapResource.current.timezone; | ||
}); | ||
} | ||
@@ -163,3 +173,3 @@ | ||
body: data | ||
}).then(xhr.parseJSON); | ||
}).then((r => r.getData())); | ||
} | ||
@@ -204,3 +214,3 @@ | ||
}) | ||
.then(xhr.parseJSON) | ||
.then((r => r.getData())) | ||
.then(project => | ||
@@ -207,0 +217,0 @@ handlePolling(xhr.get, project.uri, (response) => { |
@@ -12,6 +12,4 @@ // Copyright (C) 2007-2017, GoodData(R) Corporation. All rights reserved. | ||
return new Promise((resolve, reject) => { | ||
// cannot use get here directly - we need to access to response | ||
// not to responses JSON get returns | ||
xhr.ajax('/gdc/account/token', { method: 'GET' }).then((r) => { | ||
if (r.ok) { | ||
xhr.get('/gdc/account/token').then((r) => { | ||
if (r.response.ok) { | ||
resolve(true); | ||
@@ -51,3 +49,3 @@ } | ||
}) | ||
}).then(xhr.parseJSON); | ||
}).then((r => r.getData())); | ||
} | ||
@@ -65,4 +63,3 @@ | ||
function loginSso(sessionId, serverUrl, targetUrl) { | ||
// cannot use xhr.get, server doesn't respond with JSON | ||
return xhr.ajax(`/gdc/account/customerlogin?sessionId=${sessionId}&serverURL=${serverUrl}&targetURL=${targetUrl}`, { method: 'GET' }); | ||
return xhr.get(`/gdc/account/customerlogin?sessionId=${sessionId}&serverURL=${serverUrl}&targetURL=${targetUrl}`); | ||
} | ||
@@ -77,14 +74,15 @@ | ||
if (loggedIn) { | ||
return xhr.get('/gdc/app/account/bootstrap').then((result) => { | ||
const userUri = result.bootstrapResource.accountSetting.links.self; | ||
const userId = userUri.match(/([^\/]+)\/?$/)[1]; // eslint-disable-line no-useless-escape | ||
return xhr | ||
.get('/gdc/app/account/bootstrap') | ||
.then((result) => { | ||
const data = result.getData(); | ||
const userUri = data.bootstrapResource.accountSetting.links.self; | ||
const userId = userUri.match(/([^\/]+)\/?$/)[1]; // eslint-disable-line no-useless-escape | ||
return xhr.ajax(`/gdc/account/login/${userId}`, { | ||
method: 'delete' | ||
return xhr.del(`/gdc/account/login/${userId}`); | ||
}); | ||
}); | ||
} | ||
return Promise.resolve(); | ||
}); | ||
}, err => Promise.reject(err)); | ||
} | ||
@@ -111,10 +109,10 @@ | ||
.then((result) => { | ||
const br = result.bootstrapResource; | ||
const { bootstrapResource } = result.getData(); | ||
const accountInfo = { | ||
login: br.accountSetting.login, | ||
loginMD5: br.current.loginMD5, | ||
firstName: br.accountSetting.firstName, | ||
lastName: br.accountSetting.lastName, | ||
organizationName: br.settings.organizationName, | ||
profileUri: br.accountSetting.links.self | ||
login: bootstrapResource.accountSetting.login, | ||
loginMD5: bootstrapResource.current.loginMD5, | ||
firstName: bootstrapResource.accountSetting.firstName, | ||
lastName: bootstrapResource.accountSetting.lastName, | ||
organizationName: bootstrapResource.settings.organizationName, | ||
profileUri: bootstrapResource.accountSetting.links.self | ||
}; | ||
@@ -132,2 +130,3 @@ | ||
return xhr.get('/gdc/app/account/bootstrap') | ||
.then((r => r.getData())) | ||
.then(result => result.bootstrapResource.current.featureFlags); | ||
@@ -134,0 +133,0 @@ } |
@@ -45,15 +45,17 @@ // Copyright (C) 2007-2017, GoodData(R) Corporation. All rights reserved. | ||
return xhrGet(uri).then((response) => { | ||
if (attempts > maxAttempts) { | ||
return Promise.reject(new Error(response)); | ||
} | ||
return isPollingDone(response) ? | ||
Promise.resolve(response) : | ||
delay(pollStep).then(() => { | ||
return handlePolling(xhrGet, uri, isPollingDone, { | ||
...options, | ||
attempts: attempts + 1 | ||
return xhrGet(uri) | ||
.then(r => r.getData()) | ||
.then((response) => { | ||
if (attempts > maxAttempts) { | ||
return Promise.reject(new Error(response)); | ||
} | ||
return isPollingDone(response) ? | ||
Promise.resolve(response) : | ||
delay(pollStep).then(() => { | ||
return handlePolling(xhrGet, uri, isPollingDone, { | ||
...options, | ||
attempts: attempts + 1 | ||
}); | ||
}); | ||
}); | ||
}); | ||
}); | ||
}; | ||
@@ -60,0 +62,0 @@ |
214
src/xhr.js
@@ -5,3 +5,2 @@ // Copyright (C) 2007-2013, GoodData(R) Corporation. All rights reserved. | ||
isFunction, | ||
has, | ||
set as _set, | ||
@@ -30,3 +29,3 @@ defaults, | ||
function simulateBeforeSend(settings, url) { | ||
function simulateBeforeSend(url, settings) { | ||
const xhrMockInBeforeSend = { | ||
@@ -58,30 +57,2 @@ setRequestHeader(key, value) { | ||
function isLoginRequest(url) { | ||
return url.indexOf('/gdc/account/login') !== -1; | ||
} | ||
/** | ||
* @param {Response} response | ||
* @return {Promise} promise which resolves to result JSON () | ||
*/ | ||
export const parseJSON = response => response.json(); | ||
/** | ||
* @param {Response} response see https://developer.mozilla.org/en-US/docs/Web/API/Response | ||
* @return {Response} or {Error} | ||
*/ | ||
const checkStatus = (response) => { | ||
if (response.status >= 200 && response.status < 399) { | ||
return response; | ||
} | ||
if (response instanceof Error && has(response, 'response')) { | ||
throw response; | ||
} | ||
const error = new Error(response.statusText); | ||
error.response = response; | ||
throw error; | ||
}; | ||
export function handlePolling(url, settings, sendRequest) { | ||
@@ -102,4 +73,44 @@ const pollingDelay = result(settings, 'pollDelay'); | ||
export class ApiError extends Error { | ||
constructor(message, cause) { | ||
super(message); | ||
this.cause = cause; | ||
} | ||
} | ||
export class ApiResponseError extends ApiError { | ||
constructor(message, response, responseBody) { | ||
super(message, null); | ||
this.response = response; | ||
this.responseBody = responseBody; | ||
} | ||
} | ||
export class ApiNetworkError extends ApiError {} | ||
export class ApiResponse { | ||
constructor(response, responseBody) { | ||
this.response = response; | ||
this.responseBody = responseBody; | ||
} | ||
get data() { | ||
try { | ||
return JSON.parse(this.responseBody); | ||
} catch (error) { | ||
return this.responseBody; | ||
} | ||
} | ||
getData() { | ||
try { | ||
return JSON.parse(this.responseBody); | ||
} catch (error) { | ||
return this.responseBody; | ||
} | ||
} | ||
} | ||
export function createModule(configStorage) { | ||
let tokenRequest; // TODO make app-wide persitent (ie. extract outside of the SDK) | ||
let tokenRequest; // TODO make app-wide persistent (ie. extract outside of the SDK) | ||
@@ -147,7 +158,5 @@ defaults(configStorage, { xhrSettings: {} }); | ||
function continueAfterTokenRequest(url, settings) { | ||
return tokenRequest.then((response) => { | ||
return tokenRequest.then(async (response) => { | ||
if (!response.ok) { | ||
const err = new Error('Unauthorized'); | ||
err.response = response; | ||
throw err; | ||
throw new ApiResponseError('Unauthorized', response, null); | ||
} | ||
@@ -163,30 +172,31 @@ tokenRequest = null; | ||
function handleUnauthorized(originalUrl, originalSettings) { | ||
if (!tokenRequest) { | ||
// Create only single token request for any number of waiting request. | ||
// If token request exist, just listen for it's end. | ||
const { url, settings } = enrichSettingWithCustomDomain('/gdc/account/token', createRequestSettings({}), configStorage.domain); | ||
async function handleUnauthorized(originalUrl, originalSettings) { | ||
// Create only single token request for any number of waiting request. | ||
// If token request exist, just listen for it's end. | ||
if (tokenRequest) { | ||
return continueAfterTokenRequest(originalUrl, originalSettings); | ||
} | ||
tokenRequest = fetch(url, settings).then((response) => { | ||
// tokenRequest = null; | ||
// TODO jquery compat - allow to attach unauthorized callback and call it if attached | ||
// if ((xhrObj.status === 401) && (isFunction(req.unauthorized))) { | ||
// req.unauthorized(xhrObj, textStatus, err, deferred); | ||
// return; | ||
// } | ||
// unauthorized handler is not defined or not http 401 | ||
// unauthorized when retrieving token -> not logged | ||
if (response.status === 401) { | ||
const err = new Error('Unauthorized'); | ||
err.response = response; | ||
throw err; | ||
} | ||
const { url, settings } = enrichSettingWithCustomDomain('/gdc/account/token', createRequestSettings({}), configStorage.domain); | ||
return response; | ||
}); | ||
tokenRequest = fetch(url, settings); | ||
const response = await tokenRequest; | ||
const responseBody = await response.text(); | ||
tokenRequest = null; | ||
// TODO jquery compat - allow to attach unauthorized callback and call it if attached | ||
// if ((xhrObj.status === 401) && (isFunction(req.unauthorized))) { | ||
// req.unauthorized(xhrObj, textStatus, err, deferred); | ||
// return; | ||
// } | ||
// unauthorized handler is not defined or not http 401 | ||
// unauthorized when retrieving token -> not logged | ||
if (response.status === 401) { | ||
throw new ApiResponseError('Unauthorized', response, responseBody); | ||
} | ||
return continueAfterTokenRequest(originalUrl, originalSettings); | ||
return new ApiResponse(response, responseBody); | ||
} | ||
function ajax(originalUrl, customSettings = {}) { | ||
async function ajax(originalUrl, customSettings = {}) { | ||
// TODO refactor to: getRequestParams(originalUrl, customSettings); | ||
@@ -196,3 +206,3 @@ const firstSettings = createRequestSettings(customSettings); | ||
simulateBeforeSend(settings, url); // mutates `settings` param | ||
simulateBeforeSend(url, settings); // mutates `settings` param | ||
@@ -203,50 +213,51 @@ if (tokenRequest) { | ||
return fetch(url, settings).then((response) => { | ||
// If response.status id 401 and it was a login request there is no need | ||
// to cycle back for token - login does not need token and this meant you | ||
// are not authorized | ||
if (response.status === 401) { | ||
if (isLoginRequest(url)) { | ||
const err = new Error('Unauthorized'); | ||
err.response = response; | ||
throw err; | ||
} | ||
let response; | ||
try { | ||
response = await fetch(url, settings); | ||
} catch (e) { | ||
throw new ApiNetworkError(e.message, e); // TODO is it really necessary? couldn't we throw just Error? | ||
} | ||
return handleUnauthorized(url, settings); | ||
// Fetch URL and resolve body promise (if left unresolved, the body isn't even shown in chrome-dev-tools) | ||
const responseBody = await response.text(); | ||
if (response.status === 401) { | ||
// if 401 is in login-request, it means wrong user/password (we wont continue) | ||
if (url.indexOf('/gdc/account/login') !== -1) { | ||
throw new ApiResponseError('Unauthorized', response, responseBody); | ||
} | ||
return handleUnauthorized(url, settings); | ||
} | ||
if (response.status === 202 && !settings.dontPollOnResult) { | ||
// poll on new provided url, fallback to the original one | ||
// (for example validElements returns 303 first with new url which may then return 202 to poll on) | ||
let finalUrl = response.url || url; | ||
// Note: Fetch does redirects automagically for 301 (and maybe more .. TODO when?) | ||
// see https://fetch.spec.whatwg.org/#ref-for-concept-request%E2%91%A3%E2%91%A2 | ||
if (response.status === 202 && !settings.dontPollOnResult) { | ||
// poll on new provided url, fallback to the original one | ||
// (for example validElements returns 303 first with new url which may then return 202 to poll on) | ||
let finalUrl = response.url || url; | ||
const finalSettings = settings; | ||
const finalSettings = settings; | ||
// if the response is 202 and Location header is not empty, let's poll on the new Location | ||
if (response.headers.has('Location')) { | ||
finalUrl = response.headers.get('Location'); | ||
} | ||
finalSettings.method = 'GET'; | ||
delete finalSettings.data; | ||
delete finalSettings.body; | ||
// if the response is 202 and Location header is not empty, let's poll on the new Location | ||
if (response.headers.has('Location')) { | ||
finalUrl = response.headers.get('Location'); | ||
} | ||
finalSettings.method = 'GET'; | ||
delete finalSettings.data; | ||
delete finalSettings.body; | ||
return handlePolling(finalUrl, finalSettings, ajax); | ||
} | ||
return response; | ||
}).then(checkStatus); | ||
return handlePolling(finalUrl, finalSettings, ajax); | ||
} | ||
if (response.status >= 200 && response.status <= 399) { | ||
return new ApiResponse(response, responseBody); | ||
} | ||
// throws on 400, 500, etc. | ||
throw new ApiResponseError(response.statusText, response, responseBody); | ||
} | ||
/** | ||
* Wrapper for xhr.ajax method GET | ||
* @method get | ||
*/ | ||
const get = (url, settings) => { | ||
const opts = merge({ method: 'GET' }, settings); | ||
return ajax(url, opts).then(parseJSON); | ||
}; | ||
function xhrMethod(method) { | ||
return function methodFn(url, settings) { | ||
return function xhrMethodFn(url, settings) { | ||
const opts = merge({ method }, settings); | ||
return ajax(url, opts); | ||
@@ -257,2 +268,8 @@ }; | ||
/** | ||
* Wrapper for xhr.ajax method GET | ||
* @method get | ||
*/ | ||
const get = xhrMethod('GET'); | ||
/** | ||
* Wrapper for xhr.ajax method POST | ||
@@ -281,5 +298,4 @@ * @method post | ||
ajax, | ||
ajaxSetup, | ||
parseJSON | ||
ajaxSetup | ||
}; | ||
} |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
1214869
28120