Skip to content

01. Getting Started

wai-lin edited this page Aug 26, 2022 · 12 revisions

Initializing Project

  1. mkdir <your-project-name>
  2. cd <your-project-name>
  3. npm init
  4. add "type": "module" inside package.json file
  5. add scripts
    • "dev": "nodemon index.js"
    • "start": "node index.js"

Installing

npm install express zod cross-fetch turtle-express

npm install -D nodemon @types/node @types/express

Typescript

Typescript projects also need to install:

npm install -D ts-node typescript

Change scripts for typescripts.

{
	"scripts": {
		"dev": "nodemon index.ts",
		"start": "node dist/index.js",
		"build": "tsc"
	}
}

NOTE:

zod and cross-fetch is required as peer dependencies.

You can also use tsx instead of nodemon.


Usage

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.

Clone this wiki locally