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

api.ts

93 lines2.5 KB

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