1.0.0 • Published 4 years ago
@brielov/metal v1.0.0
Metal
Metal is a simple, minimal and type-safe router to use with node's http
module.
It is written in typescript
and it's main feature is incomming data validation.
Here is how it works:
// server.ts
import http from 'http'
import metal from '@brielov/metal'
import * as yup from 'yup'
// create a new instance
const app = metal()
// create a validation schema for the json body
const postSchema = yup
.object()
.shape({
title: yup.string().trim().required(),
excerpt: yup.string().trim().min(30).max(60).required(),
})
.required()
app.post('/posts', async (ctx) => {
const data = await ctx.body(postSchema)
// save to database
return {
status: 201,
body: data,
}
})
// pass it to the http server
http.createServer(app).listen(4000, () => console.log(`Listening on port 4000`))
If you use an editor with autocompletion features like vscode and you pass a schema to the body function,
it will infer the type for you, and if the validation fails, metal will respond automatically with 422
status code and a list of validation error messages.
Of course, you can do the same with query parameters, like so:
const paramsSchema = yup
.object()
.shape({
page: yup.number().positive().default(1),
limit: yup.number().min(1).max(50).default(10),
})
.required()
router.get('/posts', async (ctx) => {
const { page, limit } = await ctx.params(paramsSchema)
// find posts
return {
body: [...] // posts
}
})
Dynamic route params are merged with the incoming query string
router.get('/posts/:id', async (ctx) => {
const { id } = await ctx.params()
// find single post
return {
body: { ...post },
}
})