/
api.js
69 lines (60 loc) · 1.69 KB
/
api.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { useEffect } from 'react'
import pSCFetch, { subscribe, unsubscribe } from 'psc-fetch'
export const API_HOST = 'jsonplaceholder.typicode.com'
export const EXPIRY = 10000
export const useFetchApiSubscription = callbacks =>
_buildSubscription({ hostMatcher: API_HOST, callbacks })
export function fetchPost(postId) {
return getFromPlaceholder(`/posts/${postId}`)
}
export const useFetchPostSubscription = callbacks =>
_buildSubscription({
hostMatcher: API_HOST,
pathnameMatcher: /posts\/\d/,
callbacks
})
export function fetchPosts() {
return getFromPlaceholder(`/posts`)
}
export const useFetchPostsSubscription = callbacks => {
_buildSubscription({
hostMatcher: API_HOST,
pathnameMatcher: /posts/,
callbacks
})
}
export function fetchUser(userId) {
return getFromPlaceholder(`/users/${userId}`)
}
export const useFetchUserSubscription = callbacks =>
_buildSubscription({
hostMatcher: API_HOST,
pathnameMatcher: /users\/\d/,
callbacks
})
export function fetchUsers() {
return getFromPlaceholder(`/users`)
}
export const useFetchUsersSubscription = callbacks =>
_buildSubscription({
hostMatcher: API_HOST,
pathnameMatcher: /users/,
callbacks
})
async function getFromPlaceholder(pathname) {
const response = await pSCFetch(`https://${API_HOST}${pathname}`, {
expiry: EXPIRY
})
if (response.status !== 200) {
throw new Error('Error ' + response.status)
}
return response.json()
}
const _buildSubscription = ({ hostMatcher, pathnameMatcher, callbacks }) => {
useEffect(() => {
const token = subscribe({ hostMatcher, pathnameMatcher }, callbacks)
return () => {
unsubscribe(token, callbacks)
}
}, [])
}