Farmbot-Web-App/frontend/resources/in_use.ts

58 lines
2.3 KiB
TypeScript
Raw Normal View History

2018-11-14 10:05:01 -07:00
import { UUID } from "./interfaces";
2018-11-25 15:54:49 -07:00
/** Used for fast lookups of unique UUIDs. */
type UUIDSet = Record<UUID, boolean>;
2019-09-23 12:56:35 -06:00
/** The key side of the Record<UUID, >
* represents the resource that cannot be deleted (the "in use resource").
* The value represents a set of resources that make it unsafe to delete the
2018-11-25 15:54:49 -07:00
* "in use resource". */
export type UsageMap = Record<UUID, UUIDSet>;
/** A directory of all `inUse` data that the frontend cares about. */
export type UsageIndex = Record<UsageKind, UsageMap>;
/** A String denoting relationships the inUse tracker must know about.
* Format:
* 1. Name of a resource that cannot be safely deleted.
* 2. A single period (".")
* 3. Name of the resource that has a "hold" on the resource listed in (1) */
2018-11-14 10:05:01 -07:00
export type UsageKind =
| "Regimen.FarmEvent"
| "Sequence.Regimen"
| "Sequence.FarmEvent"
| "Sequence.Sequence"
2019-12-20 16:48:56 -07:00
| "Sequence.PinBinding"
2019-09-19 07:37:05 -06:00
| "Sequence.FbosConfig";
2018-11-14 10:05:01 -07:00
2018-11-25 15:54:49 -07:00
/** This variable ensures that `EVERY_USAGE_KIND` does not have typos and is
* up-to-date all `UsageKind`s */
const values: Record<UsageKind, UsageKind> = {
"Regimen.FarmEvent": "Regimen.FarmEvent",
"Sequence.Regimen": "Sequence.Regimen",
"Sequence.FarmEvent": "Sequence.FarmEvent",
"Sequence.Sequence": "Sequence.Sequence",
2019-12-20 16:48:56 -07:00
"Sequence.PinBinding": "Sequence.PinBinding",
2019-09-19 07:37:05 -06:00
"Sequence.FbosConfig": "Sequence.FbosConfig"
2018-11-25 15:54:49 -07:00
};
2018-11-14 10:05:01 -07:00
2018-11-25 15:54:49 -07:00
/** Array that contains every `UsageKind` token for easy runtime iteration. */
export const EVERY_USAGE_KIND = Object.values(values);
2018-11-14 10:05:01 -07:00
2018-11-25 15:54:49 -07:00
const EMPTY_LOOKUP: Readonly<Record<UUID, boolean>> = {};
2018-11-14 10:05:01 -07:00
2018-11-25 15:54:49 -07:00
/** SCENARIO: You need a lookup table of resources that are *not* safe to
* delete.
* PROBLEM: `UsageIndex` is highly nested and cumbersome to traverse. An array
* requires iteration (slow) and you need to be able to look up usage
* stats quickly for an individual UUID.
* SOLUTION: Merge resources into single `Record<T, U>` lookup set.
* Use `Object.keys` for iteration if required. */
2018-11-14 10:05:01 -07:00
export const resourceUsageList =
(usageIndex: UsageIndex): Record<UUID, boolean> => {
2018-11-14 13:24:54 -07:00
return EVERY_USAGE_KIND
2018-11-14 10:05:01 -07:00
.map(key => Object.keys(usageIndex[key]))
.reduce<string[]>((acc, item) => acc.concat(item), [])
2018-11-25 15:54:49 -07:00
.reduce((acc, item) => ({ ...acc, [item]: true }), EMPTY_LOOKUP);
2018-11-14 10:05:01 -07:00
};