Skip to content

Repository files navigation

Http 📶

Simple http server for any NodeJS Project

GitHub followersGitHub stars

Buy Me A Coffee

GitHub language countRepository sizeLicenseCommitizen

The intention behind this repository is to always maintain a Http package to any NodeJS project.

Installation

To use the high potential from this package you need to install first this other packages from SecJS, it keeps as dev dependency because one day @secjs/core will install everything once.

npm install @secjs/ioc @secjs/env @secjs/utils @secjs/exceptions

Then you can install the package using:

npm install @secjs/http

Usage

Http

Use Http class to create the http server and map all your routes

import{Http,ContextContract}from'@secjs/http'constserver=newHttp()// Middlewareserver.use((ctx: ContextContract)=>ctx.data.param='param')server.get('/',({ response })=>{response.status(200).send({hello: 'world!',param: ctx.data.param})})server.listen().then(address=>`Server running on address ${address}`)

Router

Use Router class to map all the groups, resources and normal routes of the application

import{TestController}from'./TestController'import{TestMiddleware}from'./TestMiddleware'import{Http,Router,ContextContract}from'@secjs/http'// With router class you can map your routes inside groups and create resourcesconsthttp=newHttp()// First you need to create the Http serverconstRoute=newRouter(http)// Create a route group to set the API version as prefixRoute.group(()=>{Route.get('posts',(ctx: ContextContract)=>{ctx.response.status(200).send({hello: 'world',userId: ctx.data.userId,postId: ctx.data.postId})}).middleware((ctx: ContextContract)=>{ctx.data.postId=1ctx.next()})// You can create a Resource route to create all the Http methods (index, store, show, update and delete)Route.resource('tests',newTestController()).except(['show'])// You can use except to create all minus show method}).prefix('/api/v1')// You can how many middlewares you want using builder pattern, .middleware, .middleware, .middleware .....middleware((ctx: ContextContract)=>{ctx.data.userId=1ctx.next()})// You can also use middlewares // You need to call register method in the end to register all the routes in the Http serverRoute.register()http.listen()

Registering routes like this could be a little difficult, so you can use the global Container from @secjs/ioc to register controllers and middlewares in the container

import'@secjs/ioc/src/utils/global'// Will load the class Container in global runtime and in TS typesContainer.singleton(TestController,'TestController')Container.singleton(// Named middlewares{// Is extremelly important that middleware implement MiddlewareContract from @secjs/http'test.auth': newTestMiddleware(),'test.hello': newTestMiddleware()},'Middlewares',)// Now you can start using string names in routesRoute.group(()=>{Route.resource('posts','TestController').only(['index','store']).middleware('test.auth')}).prefix('/api/v2').middleware('test.hello')Route.register()http.listen()

Creating a Middleware

With Http you can define three different execution times for one middleware

import{Router,MiddlewareContract,HandleContextContract,InterceptContextContract,TerminateContextContract}from'@secjs/http'exportclassMiddlewareimplementsMiddlewareContract{// Handle method will be executed before the controller method handler// This is the normal middlewareasynchandle(ctx: HandleContextContract){ctx.data.userId='1'ctx.next()}// Intercept method will be executed before the response goes to clientasyncintercept(ctx: InterceptContextContract){// You can use intercept to rewrite or add some information to the responsectx.body.intercepted=truectx.response.status(304)// Exampleif('intercept method logic changes the body'){// In intercept method, next function needs to receive the new body payload as parameter.ctx.next({hello: 'intercepted', ...ctx.body})}else{// If your logic does not change the body you can just do like thisctx.next(ctx.body)}}// Terminate method will be executed after the response goes to clientasyncterminate(ctx: TerminateContextContract){// You can use terminate to save metrics of the request in an Elastic for exampleconsole.log('Terminate middleware executed!')ctx.next()}}

Now we can use Router to set the middleware in some route

Container.singleton({'middleware': newMiddleware(),},'Middlewares',)// If you use named middlewares in Router, he will register all the three methods of Middleware class.Route.get('middlewares','TestController.index').middleware('middleware')// But you can instantiate the middleware and will register all the three methodsRoute// You can use controller method to set the default controller of Router.controller(newTestController()).get('middlewares','index').middleware(newMiddleware())// Or you can set only the method and as second parameter the middleware typeRoute.get('middlewares',newTestController().index).middleware(newMiddleware().intercept,'intercept')

License

Made with 🖤 by jlenon7 👋

Releases

Sponsor this project

Packages

Used by

Contributors

Languages