-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror-responses.ts
More file actions
86 lines (72 loc) · 1.82 KB
/
Copy patherror-responses.ts
File metadata and controls
86 lines (72 loc) · 1.82 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import {
$error,
$type,
createClient,
createRouter,
toFetchHandler,
} from 'rouzer'
import * as http from 'rouzer/http'
type User = {
id: string
name: string
}
type AuthError = {
code: 'UNAUTHORIZED'
message: string
}
type NotFoundError = {
code: 'NOT_FOUND'
message: string
}
export const getUser = http.get('users/:id', {
response: {
200: $type<User>(),
201: $type<User>(),
401: $error<AuthError>(),
404: $error<NotFoundError>(),
},
})
export const routes = { getUser }
function createLocalFetch(
handler: ReturnType<typeof createRouter>
): typeof fetch {
const fetchHandler = toFetchHandler(handler)
return (input, init) => fetchHandler(new Request(input, init))
}
export async function runErrorResponsesExample() {
const users = new Map([['42', { id: '42', name: 'Ada' }]])
const handler = createRouter({ basePath: 'api/' }).use(routes, {
getUser(ctx) {
if (ctx.path.id === 'unauthorized') {
return ctx.error(401, {
code: 'UNAUTHORIZED',
message: 'Login required',
})
}
if (ctx.path.id === 'created') {
return ctx.success(201, {
id: 'created',
name: 'Grace',
})
}
const user = users.get(ctx.path.id)
if (!user) {
return ctx.error(404, {
code: 'NOT_FOUND',
message: 'User not found',
})
}
return user
},
})
const client = createClient({
baseURL: 'https://example.test/api/',
routes,
fetch: createLocalFetch(handler),
})
const found = await client.getUser({ id: '42' })
const created = await client.getUser({ id: 'created' })
const missing = await client.getUser({ id: 'missing' })
const unauthorized = await client.getUser({ id: 'unauthorized' })
return { found, created, missing, unauthorized }
}