-
Notifications
You must be signed in to change notification settings - Fork 0
01. Getting Started
wai-lin edited this page Aug 26, 2022
·
12 revisions
mkdir <your-project-name>cd <your-project-name>npm init- add
"type": "module"insidepackage.jsonfile - add scripts
"dev": "nodemon index.js""start": "node index.js"
npm install express zod cross-fetch turtle-express
npm install -D nodemon @types/node @types/expressTypescript projects also need to install:
npm install -D ts-node typescriptChange scripts for typescripts.
{
"scripts": {
"dev": "nodemon index.ts",
"start": "node dist/index.js",
"build": "tsc"
}
}NOTE:
zodandcross-fetchis required as peer dependencies.You can also use
tsxinstead ofnodemon.
import express, { Router } from 'express'
import { z } from 'zod'
import { createRouter, errorHandler } from 'turtle-express'
const port = 8080
const app = express()
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
const router = createRouter(Router())
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(),
}),
),
},
resolver() {
return {
200: [
{
name: 'John',
email: 'john@gmail.com',
age: 24,
},
],
}
},
})
const usersId = users.path('/:id')
usersId.handler({
id: 'FindOneUserById',
method: 'get',
request: {
params: z.object({
id: z.string().transform((v) => Number(v)),
}),
},
response: {
200: z.string(),
},
resolver({ ctx }) {
const { id } = ctx.params
return {
200: `Your request id is ${id}`,
}
},
})
router.setup(app, {
paths: [users, usersId],
})
// must define at the last, so the all the errors will catch to this.
app.use(errorHandler)
app.listen(port, () => {
console.log(`Server started at ${port}`)
})Finally run npm run dev.