Apoyo - Express
HTTP server utilities for express.
THIS PACKAGE IS NOT READY TO BE USED!
Features
- Better async support for handlers
const getHealth = Request.reply(async () => {
return Http.Ok({
message: 'Everything is alright'
})
})
- Dependency injection integration with
@apoyo/ioc
const listTodos = Request.reply(
TodoService.$findAll,
async (req, findTodos) => {
const todos = await findTodos()
return Http.Ok(todos)
})
- Validation with
@apoyo/decoders
const TodoCreateDto = ObjectDecoder.struct({
title: TextDecoder.string,
completed: BooleanDecoder.boolean
})
const createTodo = Request.reply(
TodoService.$createTodo,
(req, createTodo) => {
const dto = Request.validate(req.body, TodoCreateDto)
const saved = await createTodo(body)
return Http.Created(saved)
})
- Easier routing configuration:
const todoRoutes = Route.group('/todos', {
children: [
Route.get('/', listTodos),
Route.get('/:id', getTodo),
Route.post('/', createTodo)
]
})
const routes = Route.group({
middlewares: [],
children: [
Route.get('/health', getHealth),
todoRoutes
]
})
- Easier error catching and handling:
const catchAll =
Request.catch(
[$logger],
async (err, logger) => {
logger.error('An internal error occured while executing HTTP request', err)
throw err
}
)
const routes = Route.group({
middlewares: [],
children: [
Route.get('/health', GetHealth),
todoRoutes
],
catch: [
catchAll
]
})
- Exception filtering can be done via error catchers
const catchCustomErrors = Request.catch((err) => {
if (err instanceof AccessException) {
throw Http.Forbidden({
message: err.message
})
}
throw err
})
const todoRoutes = Route.group('/todos', {
children: [
Route.get('/', ListTodos),
Route.get('/:id', GetTodo),
Route.post('/', CreateTodo)
],
catch: [
catchCustomErrors
]
})
- Easy to setup from scratch:
const $router = Express.createRouter(routes)
const $config = Injectable.of({
port: 3000
})
const $app = Injectable.define([$router], (router) => {
const app = express()
...
app.use(router)
return app
})
const $server = Express.createServer($app, $config)
async function main () {
const container = Container.create()
await container.get($server)
}
main()
- Easy to integrate in existing applications: you only need a
Container
instance to create the router middleware
const app = express()
...
const $router = Express.createRouter(routes)
const container = Container.create()
const router = await container.get($router)
app.use(router)
...
app.listen(3000)
Installation
Install express:
npm install express @types/express
Install peer dependencies:
npm install @apoyo/std @apoyo/decoders @apoyo/ioc
Install package:
npm install @apoyo/express
Documentation
Please visit the documentation for more information.
License
This project is licensed under the MIT License - see the LICENSE file for details.