2023-03-14 13:18:55 +00:00
|
|
|
/**
|
|
|
|
* Copyright (c) HashiCorp, Inc.
|
2023-08-11 13:12:13 +00:00
|
|
|
* SPDX-License-Identifier: BUSL-1.1
|
2023-03-14 13:18:55 +00:00
|
|
|
*/
|
|
|
|
|
2020-07-07 18:58:46 +00:00
|
|
|
import Service from '@ember/service';
|
|
|
|
|
|
|
|
import createHeaders from 'consul-ui/utils/http/create-headers';
|
|
|
|
import createXHR from 'consul-ui/utils/http/xhr';
|
|
|
|
import Request from 'consul-ui/utils/http/request';
|
|
|
|
import HTTPError from 'consul-ui/utils/http/error';
|
|
|
|
|
|
|
|
const xhr = createXHR(createHeaders());
|
|
|
|
|
2020-11-09 09:25:35 +00:00
|
|
|
export default class XhrService extends Service {
|
|
|
|
xhr(options) {
|
2020-07-07 18:58:46 +00:00
|
|
|
return xhr(options);
|
2020-11-09 09:25:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
request(params) {
|
2020-07-17 13:42:45 +00:00
|
|
|
const request = new Request(params.method, params.url, {
|
|
|
|
['x-request-id']: params.clientHeaders['x-request-id'],
|
|
|
|
body: params.data || {},
|
|
|
|
});
|
2020-07-07 18:58:46 +00:00
|
|
|
const options = {
|
|
|
|
...params,
|
2022-09-15 08:43:17 +00:00
|
|
|
beforeSend: function (xhr) {
|
2020-07-07 18:58:46 +00:00
|
|
|
request.open(xhr);
|
|
|
|
},
|
|
|
|
converters: {
|
2022-09-15 08:43:17 +00:00
|
|
|
'text json': function (response) {
|
2020-07-07 18:58:46 +00:00
|
|
|
try {
|
|
|
|
return JSON.parse(response);
|
|
|
|
} catch (e) {
|
|
|
|
return response;
|
|
|
|
}
|
|
|
|
},
|
|
|
|
},
|
2022-09-15 08:43:17 +00:00
|
|
|
success: function (headers, response, status, statusText) {
|
2020-07-07 18:58:46 +00:00
|
|
|
// Response-ish
|
|
|
|
request.respond({
|
|
|
|
headers: headers,
|
|
|
|
response: response,
|
|
|
|
status: status,
|
|
|
|
statusText: statusText,
|
|
|
|
});
|
|
|
|
},
|
2022-09-15 08:43:17 +00:00
|
|
|
error: function (headers, response, status, statusText, err) {
|
2020-07-07 18:58:46 +00:00
|
|
|
let error;
|
|
|
|
if (err instanceof Error) {
|
|
|
|
error = err;
|
|
|
|
} else {
|
|
|
|
error = new HTTPError(status, response);
|
|
|
|
}
|
|
|
|
request.error(error);
|
|
|
|
},
|
2022-09-15 08:43:17 +00:00
|
|
|
complete: function (status) {
|
2020-07-07 18:58:46 +00:00
|
|
|
request.close();
|
|
|
|
},
|
|
|
|
};
|
|
|
|
request.fetch = () => {
|
|
|
|
this.xhr(options);
|
2020-07-17 13:42:45 +00:00
|
|
|
return request;
|
2020-07-07 18:58:46 +00:00
|
|
|
};
|
|
|
|
return request;
|
2020-11-09 09:25:35 +00:00
|
|
|
}
|
|
|
|
}
|