Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
example from my blog post "Typesafe express routes"
import * as t from 'io-ts'
import bodyParser from 'body-parser'
import express from 'express'
import { Route, Response, Parser, route, router } from 'typera-express'
import { Option, some, none, isNone } from 'fp-ts/lib/Option'
const users: Route<Response.Ok<User[]>> = route
.get('/users')
.handler(async () => Response.ok(await usersRepo.all()))
const user: Route<Response.Ok<User> | Response.NotFound> = route
.get('/users/:id(int)')
.handler(async ({ routeParams: { id } }) => {
const userM = await usersRepo.findById(id)
if (isNone(userM)) return Response.notFound()
return Response.ok(userM.value)
})
const createUser: Route<Response.Ok | Response.BadRequest<string>> = route
.post('/users')
.use(Parser.body(t.type({ name: t.string })))
.handler(async ({ body: { name } }) => {
await usersRepo.create(name)
return Response.ok()
})
const updateUser: Route<
Response.Ok<User> | Response.NotFound | Response.BadRequest<string>
> = route
.put('/users/:id(int)')
.use(Parser.body(t.type({ name: t.string })))
.handler(async ({ body, routeParams: { id } }) => {
const updatedM = await usersRepo.update(id, body)
if (isNone(updatedM)) return Response.notFound()
return Response.ok(updatedM.value)
})
const app = express()
app.use(bodyParser.json())
app.use(router(users, user, createUser, updateUser).handler())
app.listen(3002, () => console.log('Listening on port 3002'))
// --- users "db"
export type Id = number
export type User = {
id: Id
name: string
}
const testUsers: User[] = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
]
interface UsersRepo {
all: () => Promise<User[]>
findById: (id: number) => Promise<Option<User>>
create: (name: string) => Promise<Id>
update: (id: Id, update: { name: string }) => Promise<Option<User>>
}
export const usersRepo: UsersRepo = {
all: () => Promise.resolve(testUsers),
findById: (id: number) => {
const user = testUsers.find((u) => u.id === id)
return Promise.resolve(user ? some(user) : none)
},
create: (name: string) => {
const id = testUsers.length + 1
testUsers.push({ id, name })
return Promise.resolve(id)
},
update: (id: Id, update: { name: string }) => {
const user = testUsers.find((u) => u.id === id)
if (!user) return Promise.resolve(none)
const updated: User = { ...user, name: update.name }
testUsers[testUsers.indexOf(user)] = updated
return Promise.resolve(some(updated))
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment