This commit is contained in:
ari committed 2022-09-05 15:09:41 -04:00
1 parent a9b2bdb775
commit a4a607768a
53 files changed
+44 -44

No files matched your search

+59
View File
@@ -0,0 +1,59 @@
import { AutomationData, BareAutomationData } from "types/automations";
import { API } from "./base";
import { ListData, ListParams } from "./types";
import {
AUTOMTAION_LIST,
AUTOMTAION_ITEM,
AUTOMTAION_ITEM_TAGS,
} from "./paths";
export const makeAutomationAPI = (api: API) => ({
async list({ offset, limit }: ListParams) {
const data = await api.makeCall<ListData<AutomationData>, ListParams>({
path: AUTOMTAION_LIST,
data: {
offset,
limit,
},
});
return data;
},
async update(auto: AutomationData) {
return await api.makeCall({
method: "PUT",
path: AUTOMTAION_ITEM,
data: auto,
});
},
async create(auto: BareAutomationData) {
return await api.makeCall({
method: "POST",
path: AUTOMTAION_ITEM,
data: auto,
});
},
async updateTags({
automation_id,
tags,
}: {
automation_id: string;
tags: Record<string, string>;
}) {
return await api.makeCall({
path: AUTOMTAION_ITEM_TAGS,
data: {
automation_id,
tags,
},
});
},
async remove(auto: AutomationData) {
return await api.makeCall({
method: "DELETE",
path: AUTOMTAION_ITEM,
data: auto,
});
},
});
export type AutomationAPI = ReturnType<typeof makeAutomationAPI>;
+43
View File
@@ -0,0 +1,43 @@
import { APIRequest, APIResponse } from "./types";
export interface API {
makeCall: <Res = any, Req = any>(
req: APIRequest<Req>
) => Promise<APIResponse<Res>>;
}
export const makeRemoteAPI = (baseURL: string): API => ({
async makeCall({ path, method = "POST", data = {} }) {
try {
const payload: RequestInit = {
method,
headers: {
"Content-Type": "application/json",
},
};
if (method !== "GET") {
payload["body"] = JSON.stringify(data);
}
const reply = await fetch(baseURL + path, payload);
let response: APIResponse<any>;
if (reply.status === 200) {
response = {
ok: true,
data: await reply.json(),
};
} else {
response = {
ok: false,
error: await reply.text(),
};
console.error(response);
}
return response;
} catch (err) {
console.error(err);
return {
ok: false,
error: `Server error: ${method} ${path}`,
};
}
},
});
+55
View File
@@ -0,0 +1,55 @@
import { useEffect } from "react";
import {
useDefaultApiState,
makeReloadAutomations,
makeProfileManager,
} from "./util";
import { AutomationAPI } from "./automations";
import { UserProfileAPI } from "./profile";
export type ApiService = ReturnType<typeof useAPIService>;
export const useAPIService = (
automationAPI: AutomationAPI,
userProfileAPI: UserProfileAPI
) => {
// state
const [state, setState] = useDefaultApiState();
const autoManager = makeReloadAutomations(automationAPI, state, setState);
const userProfileManager = makeProfileManager(
userProfileAPI,
state,
setState
);
// initial load of autos
useEffect(() => {
if (state.automations.ready === undefined) {
autoManager.reload();
}
}, [state.automations.ready, autoManager]);
// initial load of profile
useEffect(() => {
if (state.userProfile.ready === undefined) {
userProfileManager.reload();
}
}, [state.userProfile.ready, userProfileManager]);
return {
state: {
...state,
get theme(): "dark" | "light" {
if (state.userProfile.ready && state.userProfile.ok) {
if (["dark", "light"].includes(state.userProfile.data.theme)) {
return state.userProfile.data.theme as any;
}
}
return "dark";
},
},
removeAutomation: autoManager.wrapCall(automationAPI.remove),
updateAutomation: autoManager.wrapCall(automationAPI.update),
createAutomation: autoManager.wrapCall(automationAPI.create),
updateTags: autoManager.wrapCall(automationAPI.updateTags),
setProfile: userProfileManager.update,
};
};
+35
View File
@@ -0,0 +1,35 @@
import { AutomationData } from "types/automations";
import { makeAutomationAPI } from "./automations";
import { makeRemoteAPI } from "./base";
import { useAPIService } from "./core";
import { useAutoMockAPI, useProfileMockAPI } from "./mock";
import { createContext, useContext, useRef } from "react";
import { makeProfileAPI } from "./profile";
import { ApiState } from "./types";
const locationPrefixWeb = window.location.pathname.match(/(\/.+\/)web/i);
const baseURL = new URL(
process.env.NODE_ENV === "development"
? `http://${window.location.hostname}:8000`
: window.location.origin + (!locationPrefixWeb ? "" : locationPrefixWeb[1])
);
export const wsURL = baseURL + "socket";
export const remoteAutoAPI = makeRemoteAPI(baseURL + "automations");
export const detailsAPI = makeRemoteAPI(baseURL + "details");
export const useConnectedApiService = () =>
useAPIService(makeAutomationAPI(remoteAutoAPI), makeProfileAPI(detailsAPI));
export const useMockApiService = (
initialAutos: AutomationData[],
returnErrors: boolean = false
) =>
useAPIService(
makeAutomationAPI(useAutoMockAPI(initialAutos, useRef, returnErrors)),
makeProfileAPI(useProfileMockAPI())
);
const ApiStateContext = createContext<ApiState>({
automations: { ready: false },
userProfile: { ready: false },
});
export const ApiStateProvider = ApiStateContext.Provider;
export const useApiState = () => useContext(ApiStateContext);
+95
View File
@@ -0,0 +1,95 @@
import { useAutoMockAPI } from "./mock";
import { makeAutomationAPI } from "./automations";
import { createMockAuto } from "utils/mocks";
import { AutomationData } from "types/automations";
const fakeUseRef = (a: any) => ({ current: a });
test("mock api uses initial autos for initial population -- empty", async () => {
const mockApi = makeAutomationAPI(useAutoMockAPI([], fakeUseRef as any));
const data = await mockApi.list({ limit: 10, offset: 0 });
expect(data.ok).toBe(true);
expect((data as any).data.data).toHaveLength(0);
expect((data as any).data.totalItems).toBe(0);
});
test("mock api uses initial autos for initial population -- some data", async () => {
const initials = [createMockAuto(), createMockAuto()];
const mockApi = makeAutomationAPI(
useAutoMockAPI(initials, fakeUseRef as any)
);
const data = await mockApi.list({ limit: 10, offset: 0 });
expect(data.ok).toBe(true);
expect((data as any).data.data).toHaveLength(2);
expect((data as any).data.totalItems).toBe(2);
});
test("populate mock api with some data", async () => {
const mockApi = makeAutomationAPI(useAutoMockAPI([], fakeUseRef as any));
await mockApi.create(createMockAuto());
let data = await mockApi.list({ limit: 10, offset: 0 });
expect(data.ok).toBe(true);
expect((data as any).data.data).toHaveLength(1);
expect((data as any).data.totalItems).toBe(1);
await mockApi.create(createMockAuto());
data = await mockApi.list({ limit: 10, offset: 0 });
expect((data as any).data.data).toHaveLength(2);
expect((data as any).data.totalItems).toBe(2);
});
test("delete/update data from mock api", async () => {
const mockApi = makeAutomationAPI(
useAutoMockAPI(
[
createMockAuto(),
createMockAuto(),
createMockAuto(),
createMockAuto(),
createMockAuto(),
],
fakeUseRef as any
)
);
let data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data.data;
const toBeEdited = data[0];
toBeEdited.alias = "Bob is my uncle";
await mockApi.update(toBeEdited);
data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data.data;
expect(data[0].alias).toEqual("Bob is my uncle");
await mockApi.remove(data[0]);
data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data.data;
expect(data[0].alias === "Bob is my uncle").toEqual(false);
});
test("update tags from mock api", async () => {
const mockApi = makeAutomationAPI(
useAutoMockAPI(
[
createMockAuto(),
createMockAuto(),
createMockAuto(),
createMockAuto(),
createMockAuto(),
],
fakeUseRef as any
)
);
let data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data
.data as AutomationData[];
const autoId = data[0].id as string;
expect(data[0].tags).toStrictEqual({});
mockApi.updateTags({
automation_id: autoId,
tags: {
room: "bathroom",
type: "popup",
},
});
data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data
.data as AutomationData[];
expect(data[0].id).toEqual(autoId);
expect(data[0].tags).toStrictEqual({
room: "bathroom",
type: "popup",
});
});
+145
View File
@@ -0,0 +1,145 @@
import { useRef } from "react";
import { AutomationData, BareAutomationData } from "types/automations";
import { API } from "./base";
import { UserProfile } from "./types";
import {
AUTOMTAION_LIST,
AUTOMTAION_ITEM,
AUTOMTAION_ITEM_TAGS,
USER_PROFILE_ROOT,
} from "./paths";
export const useAutoMockAPI = (
initialAutos: AutomationData[] = [],
makeRef = useRef,
returnErrors: boolean = false
): API => {
const automationsRef = makeRef(initialAutos);
return {
async makeCall({ path, method = "POST", data = {} }) {
if (returnErrors) {
return {
ok: false,
error: "Test Error",
};
}
// console.debug("[[mockCall]]", method, path, data);
if (path === AUTOMTAION_LIST) {
return {
ok: true,
data: JSON.parse(
JSON.stringify({
totalItems: automationsRef.current.length,
params: { offset: 0, limit: 100 },
data: automationsRef.current,
})
),
} as any;
}
if (path === AUTOMTAION_ITEM) {
if (method === "PUT") {
const auto = data as AutomationData;
const index = automationsRef.current.findIndex(
({ id }) => auto.id === id
);
if (index < 0) {
return {
ok: false,
error: "Not Found",
};
} else {
automationsRef.current = [
...automationsRef.current.slice(0, index),
auto,
...automationsRef.current.slice(index + 1),
];
}
return {
ok: true,
data: {},
};
} else if (method === "DELETE") {
const auto = data as AutomationData;
automationsRef.current = automationsRef.current.filter(
({ id }) => id !== auto.id
);
return {
ok: true,
data: {},
};
} else if (method === "POST") {
const auto = data as BareAutomationData;
automationsRef.current = [
...automationsRef.current,
{
...auto,
source_file: "automation.yaml",
source_file_type: "list",
configuration_key: ["automation"],
},
];
return {
ok: true,
data: {},
};
}
}
if (path === AUTOMTAION_ITEM_TAGS) {
if (method === "POST") {
const { automation_id, tags } = data as any;
for (let i = 0; i < automationsRef.current.length; i++) {
const auto = automationsRef.current[i];
if (auto.id === automation_id) {
automationsRef.current[i].tags = JSON.parse(JSON.stringify(tags));
break;
}
}
return {
ok: true,
data: {},
};
}
}
return {
ok: false,
error: "PATH NOT FOUND " + method + ": " + path,
};
},
};
};
export const useProfileMockAPI = (
initialProfile: UserProfile = {
lang: "eng",
theme: "dark",
},
makeRef = useRef,
returnErrors: boolean = false
): API => {
const profileRef = makeRef(initialProfile);
return {
async makeCall({ path, method = "POST", data = {} }) {
if (returnErrors) {
return {
ok: false,
error: "Test Error",
};
}
if (path === USER_PROFILE_ROOT) {
if (method === "GET") {
return {
ok: true,
data: JSON.parse(JSON.stringify(profileRef.current)),
} as any;
} else if (method === "PUT") {
profileRef.current = data as any;
return { saved: "" };
}
}
return {
ok: false,
error: "PATH NOT FOUND " + method + ": " + path,
};
},
};
};
+6
View File
@@ -0,0 +1,6 @@
export const AUTOMTAION_ROOT = "/" as const;
export const AUTOMTAION_LIST = `${AUTOMTAION_ROOT}list` as const;
export const AUTOMTAION_ITEM = `${AUTOMTAION_ROOT}item` as const;
export const AUTOMTAION_ITEM_TAGS = `${AUTOMTAION_ITEM}/tags` as const;
export const USER_PROFILE_ROOT = "/profile" as const;
+22
View File
@@ -0,0 +1,22 @@
import { API } from "./base";
import { UserProfile } from "./types";
import { USER_PROFILE_ROOT } from "./paths";
export const makeProfileAPI = (api: API) => ({
async get() {
const data = await api.makeCall<UserProfile>({
method: "GET",
path: USER_PROFILE_ROOT,
});
return data;
},
async update(data: UserProfile) {
return await api.makeCall({
method: "PUT",
path: USER_PROFILE_ROOT,
data,
});
},
});
export type UserProfileAPI = ReturnType<typeof makeProfileAPI>;
+42
View File
@@ -0,0 +1,42 @@
import { AutomationData } from "types/automations";
export interface ListParams {
offset: number;
limit: number;
}
export type APIRequest<D> = {
path: string;
method?: "POST" | "DELETE" | "GET" | "PUT";
data?: D;
};
export type APIResponse<D> =
| {
ok: true;
data: D;
}
| {
ok: false;
error: string;
};
export type Waitable<D> =
| { ready: undefined }
| ({ ready: true } & APIResponse<D>)
| {
ready: false;
};
export interface ListData<D> {
params: ListParams;
totalItems: number;
data: D[];
}
export interface ApiState {
automations: Waitable<ListData<AutomationData>>;
userProfile: Waitable<UserProfile>;
}
export type UserProfile = {
theme: string;
lang: string;
};
+90
View File
@@ -0,0 +1,90 @@
import { useState } from "react";
import { ApiState } from "./types";
import { AutomationAPI } from "./automations";
import { UserProfileAPI } from "./profile";
import { UserProfile } from "services/api/types";
export const useDefaultApiState = () =>
useState<ApiState>({
automations: { ready: undefined },
userProfile: { ready: undefined },
});
export const makeReloadAutomations = (
automationAPI: AutomationAPI,
state: ApiState,
setState: (s: ApiState) => void
) => {
const reload = async () => {
let params = { offset: 0, limit: 10000 };
if (state.automations.ready && state.automations.ok) {
params = state.automations.data.params;
}
const resp = await automationAPI.list(params);
setState({
...state,
automations: {
ready: true,
...resp,
},
});
};
const wrapCall = <Call extends (a: any) => Promise<any>>(fcn: Call) => {
return async (args: Parameters<Call>[0]) => {
const resp = await fcn(args);
await reload();
return resp as ReturnType<Call>;
};
};
return {
reload,
wrapCall,
};
};
export const makeProfileManager = (
userProfileAPI: UserProfileAPI,
state: ApiState,
setState: (s: ApiState) => void
) => {
const reload = () =>
userProfileAPI
.get()
.then((data) => {
setState({
...state,
userProfile: {
ready: true,
...data,
},
});
})
.catch((error) =>
setState({
...state,
userProfile: {
ready: true,
ok: false,
error: JSON.stringify(error),
},
})
);
return {
reload,
update: (data: UserProfile) =>
userProfileAPI
.update(data)
.then(() => reload())
.catch((err) =>
setState({
...state,
userProfile: {
ok: false,
error: String(err),
ready: true,
},
})
),
};
};