x-api-sdk-ts
Version:
TypeScript Library for the X (ex-twitter) API V2
49 lines • 1.99 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AxiosAdapter = void 0;
class AxiosAdapter {
constructor(axios, config) {
this.axios = axios;
this.axiosInstance = axios.create(config);
}
async fetch(url, options) {
const axiosConfig = {
method: (options === null || options === void 0 ? void 0 : options.method) || 'GET',
headers: options === null || options === void 0 ? void 0 : options.headers,
data: options === null || options === void 0 ? void 0 : options.body,
signal: (options === null || options === void 0 ? void 0 : options.signal) || undefined,
};
try {
const response = await this.axiosInstance(url, axiosConfig);
return this.parseResponse(response);
}
catch (error) {
if (this.axios.isAxiosError(error) && error.response) {
return this.parseResponse(error.response);
}
throw error;
}
}
parseResponse(response) {
return {
ok: response.status >= 200 && response.status < 300,
status: response.status,
headers: this.parseHeaders(response.headers),
json: () => Promise.resolve(response === null || response === void 0 ? void 0 : response.data),
text: () => Promise.resolve(typeof (response === null || response === void 0 ? void 0 : response.data) === 'string'
? response.data
: JSON.stringify(response === null || response === void 0 ? void 0 : response.data)),
};
}
parseHeaders(headers) {
const stdHeaders = new Headers();
Object.entries(headers).forEach(([key, value]) => {
if (value !== undefined) {
stdHeaders.append(key, value);
}
});
return stdHeaders;
}
}
exports.AxiosAdapter = AxiosAdapter;
//# sourceMappingURL=axios-adapter.js.map