-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror-responses.ts
More file actions
98 lines (83 loc) · 2.23 KB
/
error-responses.ts
File metadata and controls
98 lines (83 loc) · 2.23 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
87
88
89
90
91
92
93
94
95
96
97
98
import type { HattipHandler } from '@hattip/core'
import { $error, $type, createClient, createRouter } 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 }
/**
* Tiny Hattip adapter used only to keep this example self-contained. Real apps
* mount the handler with a Hattip adapter for their runtime.
*/
function createLocalFetch(handler: HattipHandler): typeof fetch {
return async (input, init) => {
const request = new Request(input, init)
const response = await handler({
request,
ip: '127.0.0.1',
platform: undefined,
env() {
return undefined
},
passThrough() {},
waitUntil(promise) {
void promise
},
})
return response ?? new Response(null, { status: 404 })
}
}
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 }
}