Spaces:
Sleeping
Sleeping
File size: 1,938 Bytes
750887b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
import localforage from "localforage";
import { matchSorter } from "match-sorter";
import sortBy from "sort-by";
export async function getContacts(query) {
await fakeNetwork(`getContacts:${query}`);
let contacts = await localforage.getItem("contacts");
if (!contacts) contacts = [];
if (query) {
contacts = matchSorter(contacts, query, { keys: ["first", "last"] });
}
return contacts.sort(sortBy("last", "createdAt"));
}
export async function createContact() {
await fakeNetwork();
let id = Math.random().toString(36).substring(2, 9);
let contact = { id, createdAt: Date.now() };
let contacts = await getContacts();
contacts.unshift(contact);
await set(contacts);
return contact;
}
export async function getContact(id) {
await fakeNetwork(`contact:${id}`);
let contacts = await localforage.getItem("contacts");
let contact = contacts.find((contact) => contact.id === id);
return contact ?? null;
}
export async function updateContact(id, updates) {
await fakeNetwork();
let contacts = await localforage.getItem("contacts");
let contact = contacts.find((contact) => contact.id === id);
if (!contact) throw new Error("No contact found for", id);
Object.assign(contact, updates);
await set(contacts);
return contact;
}
export async function deleteContact(id) {
let contacts = await localforage.getItem("contacts");
let index = contacts.findIndex((contact) => contact.id === id);
if (index > -1) {
contacts.splice(index, 1);
await set(contacts);
return true;
}
return false;
}
function set(contacts) {
return localforage.setItem("contacts", contacts);
}
// fake a cache so we don't slow down stuff we've already seen
let fakeCache = {};
async function fakeNetwork(key) {
if (!key) {
fakeCache = {};
}
if (fakeCache[key]) {
return;
}
fakeCache[key] = true;
return new Promise((res) => {
setTimeout(res, Math.random() * 800);
});
}
|