Farmbot-Web-App/webpack/interceptors.ts

76 lines
2.4 KiB
TypeScript
Raw Normal View History

2017-06-29 12:54:02 -06:00
import { t } from "i18next";
import { error } from "farmbot-toastr";
import {
METHODS,
notifyBotOfChanges,
METHOD_MAP,
SafeError,
isSafeError
} from "./interceptor_support";
2017-06-29 12:54:02 -06:00
import { API } from "./api/index";
import { AuthState } from "./auth/interfaces";
import * as _ from "lodash";
2017-08-02 09:14:08 -06:00
import { AxiosRequestConfig, AxiosResponse } from "axios";
import { Content } from "./constants";
import { dispatchNetworkUp, dispatchNetworkDown } from "./connectivity/index";
2017-12-22 08:19:30 -07:00
import { Dictionary } from "farmbot";
2017-06-29 12:54:02 -06:00
2017-07-05 14:42:41 -06:00
export function responseFulfilled(input: AxiosResponse): AxiosResponse {
const method = input.config.method;
2017-09-29 13:46:08 -06:00
dispatchNetworkUp("user.api");
2017-11-14 11:56:37 -07:00
if (method && METHODS.includes(method)) {
const uuid = input.headers["x-request-id"] || "NONE";
notifyBotOfChanges(input.config.url, METHOD_MAP[method], uuid);
}
2017-06-29 12:54:02 -06:00
return input;
}
export function responseRejected(x: SafeError | undefined) {
if (x && isSafeError(x)) {
2017-09-29 13:46:08 -06:00
dispatchNetworkUp("user.api");
const a = ![451, 401, 422].includes(x.response.status);
const b = x.response.status > 399;
2017-06-29 12:54:02 -06:00
// Openfarm API was sending too many 404's.
const c = !_.get(x, "response.config.url", "").includes("openfarm.cc/");
2017-06-29 12:54:02 -06:00
if (a && b && c) {
setTimeout(() => {
// Explicitly throw error so error reporting tool will save it.
const msg = `Bad response: ${x.response.status} ${JSON.stringify(x.response)}`;
2017-06-29 12:54:02 -06:00
throw new Error(msg);
}, 1);
}
switch (x.response.status) {
case 404:
// Log 404's, but don't generate any noise for the user.
break;
case 500:
error(t("Unexpected error occurred, we've been notified of the problem."));
break;
case 451:
// DONT REFACTOR: I want to use alert() because it's blocking.
alert(t(Content.TOS_UPDATE));
2017-08-10 08:21:11 -06:00
window.location.href = "/tos_update";
2017-06-29 12:54:02 -06:00
break;
}
return Promise.reject(x);
} else {
2017-09-29 13:46:08 -06:00
dispatchNetworkDown("user.api");
2017-06-29 12:54:02 -06:00
return Promise.reject(x);
}
}
export function requestFulfilled(auth: AuthState) {
return (config: AxiosRequestConfig) => {
const req = config.url || "";
const isAPIRequest = req.includes(API.current.baseUrl);
2017-06-29 12:54:02 -06:00
if (isAPIRequest) {
config.headers = config.headers || {};
2017-12-22 08:19:30 -07:00
const headers: Dictionary<string> = config.headers;
headers.Authorization = auth.token.encoded || "CANT_FIND_TOKEN";
2017-06-29 12:54:02 -06:00
}
return config;
};
}