forked from code-fiddle/turborepo-bootstrap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcats.ts
48 lines (43 loc) · 1.29 KB
/
cats.ts
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
import { flow, types } from 'mobx-state-tree'
import { SECOND } from '../../constants/duration.const'
import { request } from '../../helpers/api'
import { getRootStore } from '../helpers'
import { StateAndCacheKey } from './stateAndCache'
import { Cat } from 'mobxtypes'
import { CatRoute } from 'shared-types'
export const CATS_API_V1 = import.meta.env.VITE_CATS_API_V1
export const Cats = types
.model('Cats', {
cats: types.array(Cat),
cache: types.frozen<{ [key: string]: any }>(),
state: types.optional(
types.enumeration('State', ['pending', 'done', 'failure']),
'done',
),
lastSuccessfulFetch: types.optional(types.number, -Infinity),
})
.actions((self) => ({
search: flow(function* () {
const { api } = getRootStore(self)
const stateAndCacheKey: StateAndCacheKey = {
api: `cats`,
operation: `search`,
}
if (!api.stateAndCache.shouldFetch(stateAndCacheKey, true)) {
return
}
api.stateAndCache.updateToPending(stateAndCacheKey)
try {
const url = `${CATS_API_V1}/${CatRoute.IMAGES}/${CatRoute.SEARCH}`
self.cats = yield request({
url,
method: 'get',
})
api.stateAndCache.updateToDone(stateAndCacheKey, {
cacheTtl: 5 * SECOND,
})
} catch (error) {
api.stateAndCache.updateToFailure(stateAndCacheKey)
}
}),
}))