Farmbot-Web-App/frontend/interceptor_support.ts

51 lines
1.5 KiB
TypeScript
Raw Permalink Normal View History

import { DataChangeType, Dictionary } from "farmbot/dist";
2017-06-29 12:54:02 -06:00
import { box } from "boxed_value";
2019-02-04 07:32:26 -07:00
import { isNumber, isNaN } from "lodash";
2017-06-29 12:54:02 -06:00
export const METHOD_MAP: Dictionary<DataChangeType> = {
2017-06-29 12:54:02 -06:00
"post": "add",
"put": "update",
"patch": "update",
"delete": "remove"
};
export const METHODS = ["post", "put", "patch", "delete"];
2017-06-29 12:54:02 -06:00
/** More nasty hacks until we have time to implement proper API push state
* notifications. */
2017-12-29 16:41:45 -07:00
export function inferUpdateId(url: string) {
2017-06-29 12:54:02 -06:00
try {
const ids = url
2017-06-29 12:54:02 -06:00
.split("/")
2017-07-20 12:26:44 -06:00
.filter(x => !x.includes(",")) // Don't allow batch endpoints to participate.
2017-06-29 12:54:02 -06:00
.map(x => parseInt(x, 10))
2019-02-04 07:32:26 -07:00
.filter(x => !isNaN(x));
const id: number | undefined = ids[0];
2019-02-04 07:32:26 -07:00
const isNum = isNumber(id);
const onlyOne = ids.length === 1;
2017-06-29 12:54:02 -06:00
return (isNum && onlyOne) ? ("" + id) : "*";
2017-07-20 12:26:44 -06:00
} catch (error) { // Don't crash - just keep moving along. This is a temp patch.
2017-06-29 12:54:02 -06:00
return "*";
}
}
/** The input of an axios error interceptor is an "any" type.
* Sometimes it will be a real Axios error, other times it will not be.
*/
export interface SafeError {
2018-03-29 08:54:37 -06:00
request: {
responseURL: string;
},
2017-06-29 12:54:02 -06:00
response: {
status: number;
};
}
/** Prevents hard-to-find NPEs and type errors inside of interceptors. */
// tslint:disable-next-line:no-any
2017-06-29 12:54:02 -06:00
export function isSafeError(x: SafeError | any): x is SafeError {
return !!(
(box(x).kind === "object") &&
(box(x.response).kind === "object") &&
(box(x.response.status).kind === "number"));
}