Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

contacts.ts

100 lines2.6 KB

1import localforage from 'localforage'
2import { matchSorter } from 'match-sorter'
3import sortBy from 'sort-by'
4​
5const initialData = [
6 {
7 avatar: 'https://avatars.githubusercontent.com/u/5580297?v=4',
8 createdAt: 1660978713047,
9 favorite: false,
10 first: 'Tanner',
11 id: 'usupkc1',
12 last: 'Linsley',
13 notes: 'Created React Query',
14 twitter: '@tannerlinsley',
15 },
16 {
17 avatar: 'https://avatars.githubusercontent.com/u/1021430',
18 createdAt: 1660979124264,
19 favorite: false,
20 first: 'Dominik',
21 id: 'kvvztl7',
22 last: 'D',
23 notes: 'Maintains React Query',
24 twitter: '@tkdodo',
25 },
27​
28export type Contact = (typeof initialData)[number]
29​
30const seed = async () => {
31 const contacts = await localforage.getItem<Contact[]>('contacts')
32 if (!contacts) {
33 set(initialData)
34 }
36​
37seed()
38​
39export async function getContacts(query?: string) {
40 await fakeNetwork()
41 let contacts = await localforage.getItem<Contact[]>('contacts')
42 if (!contacts) contacts = []
43 if (query) {
44 contacts = matchSorter(contacts, query, { keys: ['first', 'last'] })
45 }
46 return contacts.sort(sortBy('last', 'createdAt'))
48​
49export async function createContact(
50 data: Pick<Contact, 'first' | 'last' | 'twitter' | 'avatar' | 'notes'>,
51) {
52 await fakeNetwork()
53 let id = Math.random().toString(36).substring(2, 9)
54 let contact = { ...data, id, createdAt: Date.now(), favorite: false }
55 let contacts = await getContacts()
56 contacts.unshift(contact)
57 await set(contacts)
58 return contact
60​
61export async function getContact(id: string) {
62 await fakeNetwork()
63 let contacts = await localforage.getItem<Contact[]>('contacts')
64 if (!contacts) return null
65 let contact = contacts.find((contact) => contact.id === id)
66 return contact ?? null
68​
69export async function updateContact(id: string, updates: Partial<Contact>) {
70 await fakeNetwork()
71 let contacts = await localforage.getItem<Contact[]>('contacts')
72 if (!contacts) return false
73 let contact = contacts.find((contact) => contact.id === id)
74 if (!contact) throw new Error(`No contact found for ${id}`)
75 Object.assign(contact, updates)
76 await set(contacts)
77 return contact
79​
80export async function deleteContact(id: string) {
81 let contacts = await localforage.getItem<Contact[]>('contacts')
82 if (!contacts) return false
83 let index = contacts.findIndex((contact) => contact.id === id)
84 if (index > -1) {
85 contacts.splice(index, 1)
86 await set(contacts)
87 return true
88 }
89 return false
91​
92function set(contacts: Contact[]) {
93 return localforage.setItem('contacts', contacts)
95​
96async function fakeNetwork() {
97 return new Promise((res) => {
98 setTimeout(res, Math.random() * 800)
99 })