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

+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,
}
}