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

contacts.js

92 lines2.4 KB

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