added api setup

This commit is contained in:
ari committed 2021-12-30 12:37:30 -05:00
1 parent 787716ccba
commit 4a08956e1a
21 files changed
+12292 -12527

No files matched your search

+5 -1
View File
@@ -19,7 +19,11 @@
"env": {
"CI": "true"
},
"disableOptimisticBPs": true
"disableOptimisticBPs": true,
"jasmineExplorer.nodeArgv": [
"-r",
"ts-node/register"
]
}
]
}
+2 -1
View File
@@ -66,6 +66,7 @@
"@storybook/preset-create-react-app": "^3.2.0",
"@storybook/react": "^6.3.12",
"@types/chroma-js": "^2.1.3",
"@types/js-yaml": "^4.0.5"
"@types/js-yaml": "^4.0.5",
"ts-node": "^10.4.0"
}
}
+3 -1
View File
@@ -1,13 +1,15 @@
import './App.css';
import { Routes, Route, BrowserRouter } from "react-router-dom";
import { AutomationRoute } from 'routes/automation';
import { useConnectedApiService } from 'apiService';
function App() {
const api = useConnectedApiService();
return (
<div className="app">
<BrowserRouter>
<Routes>
<Route path="*" element={<AutomationRoute />} />
<Route path="*" element={<AutomationRoute api={api} />} />
</Routes>
</BrowserRouter>
</div>
+39
View File
@@ -0,0 +1,39 @@
import { AutomationData } from "types/automations";
import { API } from "./base";
import { ListData, ListParams } from "./types";
import { AUTOMTAION_LIST, AUTOMTAION_ROOT } 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,
}
});
console.log({ list: data });
return data;
},
async update({index, auto}: {index: number, auto: AutomationData}) {
return await api.makeCall({
path: AUTOMTAION_ROOT,
data: {
index,
data: auto
},
})
},
async remove({index}: {index: number}) {
return await api.makeCall({
method: "DELETE",
path: AUTOMTAION_ROOT,
data: {
index,
}
})
}
});
export type AutomationAPI = ReturnType<typeof makeAutomationAPI>;
+27
View File
@@ -0,0 +1,27 @@
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={}
}) {
const reply = await fetch(baseURL + "/" + path, {
method,
body: JSON.stringify(data),
});
if (reply.status === 200) {
return {
ok: true,
data: await reply.json(),
}
}
return {
ok: false,
error: await reply.text(),
}
}
})
+24
View File
@@ -0,0 +1,24 @@
import { useEffect } from 'react';
import { useDefaultApiState, makeReloadAutomations } from './util';
import { AutomationAPI } from './automations';
export type ApiService = ReturnType<typeof useAPIService>;
export const useAPIService = (
automationAPI: AutomationAPI
) => {
// state
const [state, setState] = useDefaultApiState();
const {reload, wrapCall} = makeReloadAutomations(automationAPI, state, setState);
// initial load of autos
useEffect(() => {
reload();
}, []);
return {
state,
removeAutomation: wrapCall(automationAPI.remove),
updateAutomation: wrapCall(automationAPI.update),
}
}
+12
View File
@@ -0,0 +1,12 @@
import { AutomationData } from 'types/automations';
import { makeAutomationAPI } from './automations';
import { makeRemoteAPI } from "./base";
import { useAPIService } from './core';
import {useMockAPI} from "./mock";
export const useConnectedApiService = () => useAPIService(
makeAutomationAPI(makeRemoteAPI("/api/v1"))
);
export const useMockApiService = (initialAutos: AutomationData[]) => useAPIService(
makeAutomationAPI(useMockAPI(initialAutos))
);
+57
View File
@@ -0,0 +1,57 @@
import { useMockAPI } from "./mock"
import { makeAutomationAPI } from "./automations";
import { createMockAuto } from '../utils/mocks';
const fakeUseRef = (a: any) => ({ current: a });
test('mock api uses initial autos for initial population -- empty', async () => {
const mockApi = makeAutomationAPI(useMockAPI([], 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(useMockAPI(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(useMockAPI([], fakeUseRef as any));
await mockApi.update({index: 0, auto: 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.update({index: 1, auto: 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(useMockAPI([
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.metadata.alias = "Bob is my uncle";
await mockApi.update({index: 0, auto: toBeEdited})
data = (await mockApi.list({ limit: 10, offset: 0 }) as any).data.data;
expect(data[0].metadata.alias).toEqual("Bob is my uncle");
await mockApi.remove({index: 0})
data = (await mockApi.list({ limit: 10, offset: 0 }) as any).data.data;
expect(data[0].metadata.alias === "Bob is my uncle").toEqual(false);
})
+63
View File
@@ -0,0 +1,63 @@
import { useRef } from 'react';
import { AutomationData } from 'types/automations';
import { API } from './base';
import { AUTOMTAION_LIST, AUTOMTAION_ROOT } from './paths';
export const useMockAPI = (
initialAutos: AutomationData[] = [],
makeRef = useRef,
): API => {
const automationsRef = makeRef(initialAutos);
return {
async makeCall({
path,
method = "POST",
data = {}
}) {
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_ROOT) {
if (method === 'POST') {
const { index, data: auto } = data as any;
if (index >= automationsRef.current.length) {
automationsRef.current = [...automationsRef.current, auto];
} else {
automationsRef.current = [
...automationsRef.current.slice(0, index),
auto,
...automationsRef.current.slice(index + 1)
];
}
return {
ok: true,
data: {}
}
} else if (method === "DELETE") {
const { index } = data as any;
automationsRef.current = [
...automationsRef.current.slice(0, index),
...automationsRef.current.slice(index + 1)
];
return {
ok: true,
data: {}
}
}
}
return {
ok: false,
error: "PATH NOT FOUND " + method + ": " + path,
}
}
}
}
+4
View File
@@ -0,0 +1,4 @@
export const AUTOMTAION_ROOT = '/automations' as const;
export const AUTOMTAION_LIST = `${AUTOMTAION_ROOT}/list` as const;
+32
View File
@@ -0,0 +1,32 @@
import { AutomationData } from "types/automations";
export interface ListParams {
offset: number;
limit: number;
}
export type APIRequest<D> = {
path: string;
method?: "POST" | "DELETE",
data?: D;
};
export type APIResponse<D> = {
ok: true;
data: D;
} | {
ok: false;
error: string;
}
export type Errorable<D> = ({ ready: true } & APIResponse<D>) | {
ready: false;
}
export interface ListData<D> {
params: ListParams;
totalItems: number;
data: D[];
}
export interface ApiState {
automations: Errorable<ListData<AutomationData>>;
}
+42
View File
@@ -0,0 +1,42 @@
import { useState } from "react";
import { ApiState } from "./types";
import { AutomationAPI } from './automations';
export const useDefaultApiState = () => useState<ApiState>({
automations: {ready: false},
});
export const makeReloadAutomations = (
automationAPI: AutomationAPI,
state: ApiState,
setState: (s: ApiState) => void,
) => {
const reload = async () => {
let params = { offset: 0, limit: 100 };
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]): Promise<ReturnType<Call>> => {
const resp = await fcn(args);
await reload();
return resp;
}
}
return {
reload,
wrapCall,
}
}
@@ -0,0 +1,55 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { usePageTheme } from "styles/page";
import { ConnectedAutmationList } from ".";
import { NODE_HEIGHT, NODE_WIDTH, ADD_HEIGHT, ADD_WIDTH, CIRCLE_SIZE, DISTANCE_FACTOR } from 'components/DAGSvgs/constants';
import { createMockAuto } from "utils/mocks";
import { useMockApiService } from "apiService";
export default {
title: 'App/ConnectedAutmationList',
component: ConnectedAutmationList,
parameters: { actions: { argTypesRegex: '^on.*' } },
args: {
dims: {
nodeHeight: NODE_HEIGHT,
nodeWidth: NODE_WIDTH,
addHeight: ADD_HEIGHT,
addWidth: ADD_WIDTH,
circleSize: CIRCLE_SIZE,
distanceFactor: DISTANCE_FACTOR,
},
initialAutomations: [],
}
} as ComponentMeta<typeof ConnectedAutmationList>;
const Template: ComponentStory<any> = args => {
const { classes } = usePageTheme({});
const api = useMockApiService(args.initialAutomations);
return <div className={classes.page}>
<ConnectedAutmationList
{...args}
api={api}
/>
</div>
}
export const EmptyStart = Template.bind({})
export const FewAutos = Template.bind({})
FewAutos.args = {
...FewAutos.args,
initialAutomations: [
createMockAuto(),
createMockAuto(),
createMockAuto(),
createMockAuto(),
createMockAuto(),
createMockAuto(),
createMockAuto(),
createMockAuto(),
createMockAuto(),
createMockAuto(),
],
}
+42 -7
View File
@@ -8,9 +8,10 @@ import { defaultAutomation } from '../../utils/defaults';
import { ArrowIcon, TrashIcon } from "components/Icons";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import { useSearchParams } from "react-router-dom";
import { ApiService } from "apiService/core";
interface Props {
interface AutomationListParams {
automations: AutomationData[];
onUpdate: (i: number, auto: AutomationData) => void;
onAdd: (auto: AutomationData) => void;
@@ -18,20 +19,21 @@ interface Props {
dims: DAGBoardElmDims;
}
export const AutomationList: FC<Props> = ({
export const AutomationList: FC<AutomationListParams> = ({
automations,
onUpdate,
onAdd,
onRemove,
dims,
children,
}) => {
// state
const [searchParams, setSearchParams] = useSearchParams();
// const [current, setCurrent] = useState(0);
// const [searchParams, setSearchParams] = useSearchParams();
const [hideList, setHideList] = useState(false);
const [current, setCurrent] = useState(0);
// alias
const current = Number(searchParams.get("current") ?? "0");
const setCurrent = (i: number) => setSearchParams({ current: String(i) });
// const current = Number(searchParams.get("current") ?? "0");
// const setCurrent = (i: number) => setSearchParams({ current: String(i) });
const currentAuto = automations.length > 0 ? automations[current] : null;
const automationListListCls = "automation-list--list" + (hideList ? " hide" : " show")
// render
@@ -47,7 +49,10 @@ export const AutomationList: FC<Props> = ({
</Button>
</div>
)}
<Button onClick={() => onAdd(defaultAutomation(`shortu-${automations.length}`))}>Add</Button>
<Button onClick={() => {
onAdd(defaultAutomation(`shortu-${automations.length}`));
setCurrent(automations.length)
}}>Add</Button>
</div>
<ButtonIcon
onClick={() => setHideList(!hideList)}
@@ -63,5 +68,35 @@ export const AutomationList: FC<Props> = ({
dims={dims}
/> : <></>}
</div>
{children}
</div>
}
interface ConnectedAutmationListParams {
dims: DAGBoardElmDims;
api: ApiService;
}
export const ConnectedAutmationList: FC<ConnectedAutmationListParams> = ({
api: {
state: {
automations,
},
removeAutomation,
updateAutomation,
},
dims
}) => {
if (!automations.ready) {
return <span>Loading...</span>
}
if (!automations.ok) {
return <span>Error {automations.error}</span>
}
return <AutomationList
dims={dims}
automations={automations.data.data}
onAdd={auto => updateAutomation({ auto, index: automations.data.totalItems + 1 })}
onRemove={index => removeAutomation({ index })}
onUpdate={(index, auto) => updateAutomation({ index, auto })}
/>
}
@@ -1,10 +0,0 @@
import { computeNodesEdgesPos } from "./positions"
test('empty nodes', () => {
const onChange = () => {}
const openModal = () => { }
const out = Array.from(computeNodesEdgesPos([0, 0], [], onChange, openModal));
expect(out).toHaveLength(0)
})
+8 -17
View File
@@ -1,29 +1,20 @@
import { AutomationList } from "components/AutomationList";
import { ApiService } from 'apiService/core';
import { ConnectedAutmationList } from "components/AutomationList";
import { DEFAULT_DIMS } from "components/DAGSvgs/constants";
import { FC, useState } from "react";
import { FC } from "react";
import { usePageTheme } from "styles/page";
import { AutomationData } from "types/automations";
export const AutomationRoute: FC = () => {
export const AutomationRoute: FC<{ api: ApiService }> = ({
api
}) => {
const { classes } = usePageTheme({});
const [automations, setAutos] = useState<AutomationData[]>([]);
return <div className={classes.page}>
<AutomationList
<ConnectedAutmationList
dims={DEFAULT_DIMS}
automations={automations}
onUpdate={(i, auto) => setAutos([
...automations.slice(0, i),
auto,
...automations.slice(i + 1)
])}
onAdd={auto => setAutos([...automations, auto])}
onRemove={i => setAutos([
...automations.slice(0, i),
...automations.slice(i + 1)
])}
api={api}
/>
</div>
}
-17
View File
@@ -1,17 +0,0 @@
import { AutomationData } from "types/automations";
import { API } from "./base";
export const makeAutomationAPI = (api: API) => ({
async list(offset: number, limit: number) {
return await api.makeCall<AutomationData[]>({
path: "/automations/list",
data: {
offset, limit,
}
});
}
})
export type AutomationAPI = ReturnType<typeof makeAutomationAPI>;
-33
View File
@@ -1,33 +0,0 @@
export interface API {
makeCall: <Res = {}, Req = {}>(req: APIRequest<Req>) => Promise<APIResponse<Res>>;
}
export type APIRequest<D> = {
path: string;
data: D;
};
export type APIResponse<D> = {
ok: true;
data: D;
} | {
ok: false;
error: string;
}
export const makeRemoteAPI = (baseURL: string): API => ({
async makeCall (req) {
const reply = await fetch(baseURL + "/" + req.path, {
method: "POST",
body: JSON.stringify(req.data),
});
if (reply.status === 200) {
return {
ok: true,
data: await reply.json(),
}
}
return {
ok: false,
error: await reply.text(),
}
}
})
-5
View File
@@ -1,5 +0,0 @@
import { makeAutomationAPI, AutomationAPI } from './automations';
import { makeRemoteAPI } from "./base";
const api = makeRemoteAPI("/api/v1");
export const automationAPI: AutomationAPI = makeAutomationAPI(api);
+11877 -12435
View File
File diff suppressed because it is too large. Load diff