-
Notifications
You must be signed in to change notification settings - Fork 0
02. Examples
wai-lin edited this page Aug 23, 2022
·
3 revisions
const router = createRouter(Router(), { basePath: '/api' })
const users = router.path('/users')
users.handler({
id: 'FindAllUsers',
method: 'get',
response: {
200: z.array(
z.object({
name: z.string(),
email: z.string().email(),
age: z.number(),
}),
),
},
async resolver() {
const users = await db.users.find()
return {
200: users,
}
},
})
IMPORTANT:
Request
params
andquery
are alwaysstring
type since you can only get them from the request url. So, when you definingrequest.params
andrequest.query
schemas, you always need to definedz.string()
. After that, you can type cast the parsed string as you wanted.
const users = router.path('/users')
const usersId = users.path('/:id')
usersId.handler({
id: 'FindOneUserById',
method: 'get',
request: {
params: z.object({
id: z
.string()
.min(1, { message: 'Id is required.' })
.regex(/^\d+$/g, { message: 'Id should only be numeric.' })
.transform((v) => Number(v)),
}),
},
response: {
200: z.object({
name: z.string(),
email: z.string().email(),
}),
},
async resolver({ ctx }) {
const { id } = ctx.params
const user = await db.users.findOne(id)
return {
200: user,
}
},
})
const users = router.path('/users')
users.handler({
id: 'FindAllUsers',
method: 'get',
request: {
query: z.object({
limit: z
.string()
.default('10')
.transform((v) => Number(v)),
offset: z
.string()
.default('0')
.transform((v) => Number(v)),
}),
},
response: {
200: z.array(
z.object({
name: z.string(),
email: z.string().email(),
}),
),
},
async resolver({ ctx }) {
const { limit, offset } = ctx.query
const users = await db.users.find({ take: limit, skip: offset })
return {
200: users,
}
},
})
const users = router.path('/users')
users.handler({
id: 'CreateNewUser',
method: 'post',
request: {
body: z.object({
name: z.string().min(1, { message: 'name is required.' }),
email: z.string().email({ message: 'wrong email format.' }),
}),
},
response: {
200: z.object({
name: z.string(),
email: z.string().email(),
}),
},
async resolver({ ctx }) {
const { name, email } = ctx.body
const user = await db.users.create({ name, email })
return {
200: user,
}
},
})