86 lines
2.8 KiB
TypeScript
86 lines
2.8 KiB
TypeScript
import { ItemType, Store, StoreEntry } from "./types"
|
|
|
|
|
|
const defaultEndpoint = "http://slateport:4444"
|
|
|
|
export type APIEndPoint = {
|
|
write: (json: string) => Promise<void>,
|
|
read: () => Promise<Store>,
|
|
};
|
|
|
|
const makeEndpoint = (key: string, method: string, endPointOverride?: string): string => {
|
|
return `${endPointOverride ?? defaultEndpoint}\/${method}\/${key}\/`;
|
|
}
|
|
|
|
|
|
export const getAPI = (key: string, endPointOverride?: string): APIEndPoint => ({
|
|
write: async (json: string) => {
|
|
const rawResponse = await fetch(makeEndpoint(key, "write", endPointOverride), {
|
|
method: 'POST',
|
|
headers: {
|
|
},
|
|
body: json,
|
|
});
|
|
const resp = await rawResponse.text();
|
|
return;
|
|
},
|
|
read: async () => {
|
|
const rawResponse = await fetch(makeEndpoint(key, "read", endPointOverride), {
|
|
method: 'POST'
|
|
});
|
|
const respText = await rawResponse.text();
|
|
return JSON.parse(respText, ) as Store;
|
|
}
|
|
});
|
|
|
|
export const ensureToday = (store: Store): Store => {
|
|
const today : Date = new Date();
|
|
const storeEntry = store.index.find(([key, dateString]) => {
|
|
const date = new Date(dateString);
|
|
const [y, m, d] = [today.getFullYear(), today.getMonth(), today.getDay()];
|
|
return (date.getFullYear() === y && date.getMonth() === m && date.getDay() == d);
|
|
});
|
|
|
|
if (storeEntry !== undefined) return store;
|
|
|
|
const indexKey = today.getDay() + today.getMonth() * 100 + today.getFullYear() * 10000;
|
|
const entries = store.entries;
|
|
const newEntry : StoreEntry = {
|
|
items: [],
|
|
}
|
|
entries[indexKey] = newEntry;
|
|
|
|
return {
|
|
entries: entries,
|
|
index: [[indexKey, today.toString()], ...store.index ],
|
|
version: store.version,
|
|
};
|
|
}
|
|
|
|
export const addEntry = (store: Store, entry: ItemType): Store => {
|
|
const [storeIndex, dateString] = getToday(ensureToday(store))!;
|
|
const today = store.entries[storeIndex];
|
|
today.items = [...today.items, entry];
|
|
store.entries[storeIndex] = today;
|
|
return store;
|
|
}
|
|
|
|
export const removeEntry = (store: Store, entry: ItemType): Store => {
|
|
const [storeIndex, dateString] = getToday(ensureToday(store))!;
|
|
const today = store.entries[storeIndex];
|
|
today.items = today.items.filter((item) => JSON.stringify(item) !== JSON.stringify(entry));
|
|
store.entries[storeIndex] = today;
|
|
return store;
|
|
}
|
|
|
|
export const getToday = (store: Store) => {
|
|
if (!store) return;
|
|
const today : Date = new Date();
|
|
const storeEntry = store.index.find(([key, dateString]) => {
|
|
const date = new Date(dateString);
|
|
const [y, m, d] = [today.getFullYear(), today.getMonth(), today.getDay()];
|
|
return (date.getFullYear() === y && date.getMonth() === m && date.getDay() == d);
|
|
});
|
|
return storeEntry;
|
|
};
|