UNPKG

local-fake-api

Version:

A simple async local mock API without backend.

50 lines (49 loc) 1.66 kB
import { delay, clearStoredItems, getStoredItems, setStoredItems } from "../utils/fakeStore"; export function createFakeApi(nameSpace) { async function list() { await delay(100); return getStoredItems(nameSpace); } async function get(keyValue, key) { const existingItems = await list(); const searchKey = (key || "id"); const item = existingItems.find((item) => String(item[searchKey]) === keyValue); 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, }; }