RESTyped Express Wrapper
Express route wrappers for declaring type-safe APIs with RESTyped. Also supports async
route functions.
Usage
npm install restyped-express-async
It's just like normal express, except you'll need to provide a RESTyped API definition file for the API you want to use, and return a Promise with your response value in order to activate type-checking.
import RestypedRouter from 'restyped-express-async'
import {MyAPI} from './MyAPI'
import * as express from 'express'
const app = express()
const router = RestypedRouter<MyAPI>(app)
router.post('/login', async req => {
const {username, password, twoFactorPin} = req.body
const accessToken = await User.login(username, password, twoFactorPin)
return accessToken
})
Error handling and status codes
Error handling
You can throw
from inside your async
function and your thrown error will be passed to next(err)
.
Status codes
Use express directly to send responses with status codes. Don't forget to return
after you res.send()
.
router.post('/login', async (req, res) => {
const {username, password, twoFactorPin} = req.body
const accessToken = await User.login(username, password, twoFactorPin)
if (!accessToken) {
res.status(401).send()
return
}
return accessToken
})