UNPKG

local-fake-api

Version:

A simple async local mock API without backend.

49 lines (48 loc) 1.57 kB
import { delay, clearStoredItems, getStoredItems, setStoredItems } from "./utils"; export function createApi(nameSpace) { async function list() { await delay(100); return getStoredItems(nameSpace); } async function get(id) { const existingItems = await list(); const item = existingItems.find((item) => item.id === id); return item !== null && item !== void 0 ? item : null; } async function add(item) { const newItem = { ...item, id: Date.now().toString() }; const existingItems = await list(); await delay(100); setStoredItems(nameSpace, [...existingItems, newItem]); return newItem; } async function del(id) { const existingItems = await list(); const updatedItems = existingItems.filter((item) => item.id !== id); await delay(100); setStoredItems(nameSpace, updatedItems); } async function update(id, updates) { const existingItems = await list(); const index = existingItems.findIndex((item) => item.id === id); if (index === -1) return null; const updatedItem = { ...existingItems[index], ...updates }; existingItems[index] = updatedItem; await delay(100); setStoredItems(nameSpace, existingItems); return updatedItem; } async function clearAll() { await delay(100); clearStoredItems(nameSpace); } return { list, get, add, delete: del, update, clearAll, }; }