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

mockTodos.ts

174 lines4.7 KB

1import axios from 'redaxios'
2import { produce } from 'immer'
3import { actionDelayFn, loaderDelayFn, shuffle } from './utils'
4​
5type PickAsRequired<TValue, TKey extends keyof TValue> = Omit<TValue, TKey> &
6 Required<Pick<TValue, TKey>>
7​
8export type Invoice = {
9 id: number
10 title: string
11 body: string
13​
14export interface User {
15 id: number
16 name: string
17 username: string
18 email: string
19 address: Address
20 phone: string
21 website: string
22 company: Company
24​
25export interface Address {
26 street: string
27 suite: string
28 city: string
29 zipcode: string
30 geo: Geo
32​
33export interface Geo {
34 lat: string
35 lng: string
37​
38export interface Company {
39 name: string
40 catchPhrase: string
41 bs: string
43​
44let invoices: Array<Invoice> = null!
45let users: Array<User> = null!
46​
47let invoicesPromise: Promise<void> | undefined = undefined
48let usersPromise: Promise<void> | undefined = undefined
49​
50const ensureInvoices = async () => {
51 if (!invoicesPromise) {
52 invoicesPromise = Promise.resolve().then(async () => {
53 const { data } = await axios.get(
54 'https://jsonplaceholder.typicode.com/posts',
55 )
56 invoices = data.slice(0, 10)
57 })
58 }
59​
60 await invoicesPromise
62​
63const ensureUsers = async () => {
64 if (!usersPromise) {
65 usersPromise = Promise.resolve().then(async () => {
66 const { data } = await axios.get(
67 'https://jsonplaceholder.typicode.com/users',
68 )
69 users = data.slice(0, 10)
70 })
71 }
72​
73 await usersPromise
75​
76export async function fetchInvoices() {
77 return loaderDelayFn(() => ensureInvoices().then(() => invoices))
79​
80export async function fetchInvoiceById(id: number) {
81 return loaderDelayFn(() =>
82 ensureInvoices().then(() => {
83 const invoice = invoices.find((d) => d.id === id)
84 if (!invoice) {
85 throw new Error('Invoice not found')
86 }
87 return invoice
88 }),
89 )
91​
92export async function postInvoice(partialInvoice: Partial<Invoice>) {
93 return actionDelayFn(() => {
94 if (partialInvoice.title?.includes('error')) {
95 console.error('error')
96 throw new Error('Ouch!')
97 }
98 const invoice = {
99 id: invoices.length + 1,
100 title:
101 partialInvoice.title ?? `New Invoice ${String(Date.now()).slice(0, 5)}`,
102 body:
103 partialInvoice.body ??
104 shuffle(
105 `Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
106 Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante.
107 Vestibulum sapien. Proin quam. Etiam ultrices. Suspendisse in justo eu magna luctus suscipit. Sed lectus. Integer euismod lacus luctus magna. Integer id quam. Morbi mi. Quisque nisl felis, venenatis tristique, dignissim in, ultrices sit amet, augue. Proin sodales libero eget ante.
108 `.split(' '),
109 ).join(' '),
110 }
111 invoices = [...invoices, invoice]
112 return invoice
113 })
115​
116export async function patchInvoice({
117 id,
118 ...updatedInvoice
119}: PickAsRequired<Partial<Invoice>, 'id'>) {
120 return actionDelayFn(() => {
121 invoices = produce(invoices, (draft) => {
122 const invoice = draft.find((d) => d.id === id)
123 if (!invoice) {
124 throw new Error('Invoice not found.')
125 }
126 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
127 if (updatedInvoice.title?.toLocaleLowerCase()?.includes('error')) {
128 throw new Error('Ouch!')
129 }
130 Object.assign(invoice, updatedInvoice)
131 })
132​
133 return invoices.find((d) => d.id === id)
134 })
136​
137export type UsersSortBy = 'name' | 'id' | 'email'
138​
139export async function fetchUsers({
140 filterBy,
141 sortBy,
142}: { filterBy?: string; sortBy?: UsersSortBy } = {}) {
143 return loaderDelayFn(() =>
144 ensureUsers().then(() => {
145 let usersDraft = users
146​
147 if (filterBy) {
148 usersDraft = usersDraft.filter((d) =>
149 d.name.toLowerCase().includes(filterBy.toLowerCase()),
150 )
151 }
152​
153 if (sortBy) {
154 usersDraft = [...usersDraft].sort((a, b) => {
155 return a[sortBy] > b[sortBy] ? 1 : -1
156 })
157 }
158​
159 return usersDraft
160 }),
161 )
163​
164export async function fetchUserById(id: number) {
165 return loaderDelayFn(() =>
166 ensureUsers().then(() => users.find((d) => d.id === id)),
167 )
169​
170export async function fetchRandomNumber() {
171 return loaderDelayFn(() => {
172 return Math.random()
173 })