Issue
Мне нужно загрузить результаты запроса с конечной точки путем потоковой передачи результатов в файл CSV. Это делается для того, чтобы поддерживать огромные ResultSets, отправляемые через браузер одновременно.
Есть ли способ выполнить sh это с помощью Ax ios в контексте приложения React?
Я видел fetch () и знаю, что он имеет следующие характеристики:
- возвращает ReadableStream
- НЕ поддерживается IE11
- НЕ позволяет перехватывать запросы
- Статус ответа относится к самому запросу, а не к HTTP-состоянию
- Это означает, что единственный способ получить ошибку - значит иметь что-то go неправильно с преждевременным завершением потока
- Это точно не будет работать для меня, так как у меня есть пользовательская обработка ошибок, связанная с разрешениями пользователя
Кроме типа ответа ReadableStream
остальные перечисленные характеристики недопустимы. Мне нужно будет поддерживать IE11 и разрешить перехват запросов / чтение статуса HTTP, чтобы определить, как обрабатывать трафик c.
Пример с fetch
:
// The promise returned by `fetch` rejects if the fetch was unable to make HTTP-request
// e.g. network problems, or there’s no such site.
// Abnormal HTTP-statuses, such as 404 or 500 do not cause an error.
const results = await fetch(`${URL}/data`, {
method: 'post', // HTTP POST to send query to server
headers: {
Accept: 'application/json, text/plain, */*', // indicates which files we are able to understand
'Content-Type': 'application/json', // indicates what the server actually sent
},
body: JSON.stringify(query), // server is expecting JSON
credentials: 'include', // sends the JSESSIONID cookie with the address
}).then(res => res.json()) // turn the ReadableStream response back into JSON
.then((res) => {
if (res.ok) {
// boolean, true if the HTTP status code is 200-299.
console.log('response.ok!');
} else if (res.status === 401) {
throw Error(`You are not authenticated. Please login.`);
} else if (res.status === 403) {
throw Error(`You are not authorized to access this data.`);
} else {
throw Error(`Request rejected with status ${res.status}`);
}
})
.catch((error) => {
// catches error case and if fetch itself rejects
error.response = {
status: 0,
statusText:
'Cannot connect. Please make sure you are connected to internet.',
};
throw error;
});
console.log(results);
Пример с axios
(без потоковой передачи)
Ax ios экземпляр
import ...
const Api = axios.create({
baseURL: `${URL}`,
withCredentials: true,
});
// attach interceptors to requests and responses
// these are defined elsewhere and imported
Api.interceptors.request.use((request) => requestHandler(request));
Api.interceptors.response.use((response) => successHandler(response), (error) => errorHandler(error));
export default Api;
Топор ios запрос
const query = {"selections":{"TABLE_A":["COLUMN1"]},"filters":[{"predicates":[]}],"joins":[],"sorts":[],"limit":100,"offset":0}
const response = await Api.post('/data', query);
// further transformations to response to get formatted csv results required
Вопросы о топоре ios
- Возможно ли иметь
ReadableStream
в топоре ios такой же, как fetch
? - Возможна ли потоковая передача в Ax ios только в том случае, если предполагается, что она будет поддерживаться Node в настройках только на стороне сервера?
- Такие сайты, как этот , похоже, говорят, что использование
responseType: 'stream'
- это не то, что можно сделать в браузере, только с Node.js с использованием fs
- Можно ли использовать
fetch
или что-то еще в сочетании с Ax ios?