TachiJS
Highly testable dead simple web server written in Typescript
- 🏁 Highly testable. (all props in
req
andres
are injectable so you don't have to mock at all.) - 🔧 Highly customizable.
- 💉 Simple dependency injection.
- ⚡️
async/await
request handler. (like Koa without any configurations.) - 🏭 Based on expressjs. (You can benefit from using this mature library)
- ✅ Built-in request body validator.
- 📐 Written in Typescript.
Why?
Nest.js
looks nice. But its learning curve is too stiff.(TBH, I still don't know how to redirect dynamically.) Most of people probably do not need to know how Interceptor
, Pipe
and other things work. It might be good for some enterprize level projects.
But using raw expressjs
is also quite painful. To test express apps, you have to use supertest
or chai-http
things. If you use them, you will lose debugging and error stack while testing because they send actual http request internally. Otherwise, you have to mock up all params, req
, res
and next
, of RequestHandler of express.js.
To deal with the testing problem, inversify-express-utils
could be a solution. But it does not support many decorators. To render with view engine like pug, we need to use res.render
method. But the only solution is using @response
decorator. It means you have to mock up Response
in your test. So technically it is super hard to test routes rendering view engine.
Luckily, TachiJS tackles those problems. If you have other ideas, please create an issue!!
How to use
Install tachijs
npm i tachijs
Enable experimentalDecorators
of compilerOptions
to tsconfig.json
.
Quick start
// Register `HomeController` // `app` is just an express application instanceapp.listen8000
Now you can access http://localhost:8000/.
For other http methods, tachijs provides @httpPost
, @httpPut
, @httpPatch
, @httpDelete
, @httpOptions
, @httpHead
and @httpAll
.
Configuring express app(Middleware)
There are lots of ways to implement express middleware.
before
and after
options
Use app.listen8000
before
or after
options
Without Identically same to the above example.
app.usebodyParser tachijs app.use'*', app.useerrorHandler app.listen8000
Apply middleware to controllers and methods
Sometimes, you might want to apply middleware to several methods only.
// Apply `cors()` to controller. Now all methods will use the middleware.
Configure router options
Tachijs will create and register a router for each controller.
So you can provide router options via @controller
decorator.
req.params
, req.query
and req.body
via decorators
Access You can access them via @reqParams
, @reqQuery
and @reqBody
.
(Don't forget to apply body-parser
middleware)
We also provide reqHeaders
, reqCookies
and reqSession
for req.headers
, req.cookies
and req.session
. To know more, see our api documentation below.
Body validation
It has been deprecated from v1. We'll provide this feature as a separated module.
Custom parameter decorators!
If you're using passport
, you should want to access user data from req.user
.
@handlerParam
decorator make it possible. The decorator gets a selector which accepts express's req
, res
and next
. So all you need to do is decide what to return from thoes three parameters.
If you want reusable code, please try like the below.
req
or res
before exposing
Bind methods of You can also pass methods of req
or res
which are augmented by express module.
Some of them might need the context of them.
So please bind methods before exposing like the below example.
meta.paramType
If you are using reflect-metadata
, tachijs exposes paramType
to the forth argument, meta
, of handlerParam
from design:paramtypes
. With this feature, you could access argument types on runtime. The below example is validating and transforming query with DTO class by class-validator.
// Validator class
To enable it, you have to install reflect-metadata
and to apply emitDecoratorMetadata
of compilerOptions
to tsconfig.json
.
npm i reflect-metadata
To know more, see @handlerParam
api documentation below.
Redirection, Rendering via pug and others...
Techinically, you don't have to access res
to response data.
But, if you want to redirect or render page via pug, you need to access res.redirect
or res.render
.
Sadly, if you do, you have make mockup for res
.
But, with tachijs, you can tackle this problem.
Now, you can test your controller like the below example.
describe'HomeController#redirectToHome',
There are other results too, EndResult
, JSONResult
, RenderResult
, SendFileResult
, SendResult
, and SendStatusResult
. Please see our api documentation below.
BaseController
If you need to use many types of result, you probably want BaseController
.
Just import it once, and your controller can instantiate results easily.
// You have to extend your controller from `BaseController`
BaseController
has methods for all build-in results, Please see our api documentation below.
BaseController#context
You may want to share some common methods via your own base controller. But, sadly, it is not possible to use decorators to get objects from req
or res
and services provided by @inject
.
To make it possible, we introduce context
. Which expose req
, res
and inject
method via context
if your controller is extended from BaseController
.
Customize result
If you want to have customized result behavior, you can do it with BaseResult
.
BaseResult
is an abstract class which coerce you to define how to end the route by providing execute
method.
(Every built-in result is extended from BaseResult
.)
Let's see our implementation of RedirectResult
.
Dependency injection
To make controllers more testable, tachijs provides dependency injection.
Let's think we have some mailing service, MailerService
.
While developing or testing, we probably don't want our server to send real e-mail everytime.
// Create enum for service types // Abstract class coerce MailerService must have `sendEmail` method. // Mockup service for development and testing. // Swapping container depends on the current environment. ? :
So you can test HomeController#sendEmail
like the below example.
describe'HomeController#sendEmail',
Now we don't have to worry that our controller sending e-mail for each testing.
Furthermore, you can inject other services to your service as long as they exist in the container.
tachijs
DI without When some testing or just writing scripts using services, you might want to use DI without tachijs
function.
So we exposed Injector
class which is used by tachijs
.
// Create injector // Instantiate by a key// Instantiate by a constructor
Bad practices
Please check this section too to keep your controllers testable.
res.send
or next
inside of controllers or @handlerParam
Execute Please don't do that. It just make your controller untestable. If you want some special behaviors after your methods are executed, please try to implement them with BaseResult
.
Do
Don't
BaseController#context
in your descendant controllers
Access It is designed to be used inside of your base controller to make unit testing easy.
Do
Don't
APIs
tachijs(options: TachiJSOptions): express.Application
Create and configure an express app.
TachiJSOptions
app
Optional. If you provide this option, tachijs will use it rather than creating new one.before
Optional. You can configure express app before registering controllers for applying middleware.after
Optional. You can configure express app before registering controllers for error handling.controllers
Optional. Array of controller classes.container
Optional. A place for registered services. If you want to use DI, you have to register services to here first.
@controller(path: string, middleware: MiddlewareParams | RequestHandler[] = {}, routerOptions: RouterOptions = {})
It marks class as a controller.
path
Target path.middleware
Optional.MiddlewareParams
or Array of middleware. If it provided as array, tachijs will set the middleware before controller method.routerOptions
Optional. Express router options.
MiddlewareParams
@httpMethod(method: string, path: string, middleware: MiddlewareParams | RequestHandler[] = {})
It marks method as a request handler.
method
Target http methods,'get'
,'post'
,'put'
,'patch'
,'delete'
,'options'
,'head'
or'all'
are available. ('all'
means any methods.)path
Target path.middleware
Optional.MiddlewareParams
or Array of middleware. If it provided as array, tachijs will set the middleware before controller method.
tachijs also provides shortcuts for @httpMethod
.
@httpGet(path: string, middleware: MiddlewareParams | RequestHandler[] = {})
@httpPost(path: string, middleware: MiddlewareParams | RequestHandler[] = {})
@httpPut(path: string, middleware: MiddlewareParams | RequestHandler[] = {})
@httpPatch(path: string, middleware: MiddlewareParams | RequestHandler[] = {})
@httpDelete(path: string, middleware: MiddlewareParams | RequestHandler[] = {})
@httpOptions(path: string, middleware: MiddlewareParams | RequestHandler[] = {})
@httpHead(path: string, middleware: MiddlewareParams | RequestHandler[] = {})
@httpAll(path: string, middleware: MiddlewareParams | RequestHandler[] = {})
@handlerParam<T>(selector: HandlerParamSelector<T>)
selector
selects a property fromreq
,res
,next
or even ourmeta
index
Number index of the parameter.selector
Its selector.paramType
metadata fromdesign:paramtypes
.
@reqBody()
Inject req.body
.
@reqParams(paramName?: string)
Inject req.params
or its property.
paramName
If it is given,req.params[paramName]
will be injected.
@reqQuery(paramName?: string)
Inject req.query
or its property.
paramName
If it is given,req.query[paramName]
will be injected.
@reqHeaders(paramName?: string)
Inject req.headers
or its property.
paramName
If it is given,req.headers[paramName]
will be injected.
@reqCookies(paramName?: string)
Inject req.cookies
or its property.
paramName
If it is given,req.cookies[paramName]
will be injected.
@reqSignedCookies(paramName?: string)
Inject req.signedCookies
or its property.
paramName
If it is given,req.signedCookies[paramName]
will be injected.
@cookieSetter()
Inject res.cookie
method to set cookie.
@cookieClearer()
Inject res.clearCookie
method to clear cookie.
@reqSession(paramName?: string)
Inject req.session
.
BaseController
A base for controller which have lots of helper methods for returning built-in results. Also, it allows another way to access properties of req
, res
and inject
without any decorators.
#context
tachijs will setreq
,res
andinject
method to this property. So, when unit testing, it is not defined.#context.req
Raw express request instance#context.req
Raw express response instance#inject<S>(key: string): S
A method to access a registered service by the given key. It is almost same to@inject
decorator. (@inject<ServiceTypes.SomeService> someService: SomeService
=>const someService = this.inject<SomeService>(ServiceTypes.SomeService)
)
#end(data: any, encoding?: string, status?: number): EndResult
#json(data: any, status?: number): JSONResult
#redirect(location: string, status?: number): RedirectResult
#render(view: string, locals?: any, callback?: RenderResultCallback, status?: number): RenderResult
#sendFile(filePath: string, options?: any, callback?: SendFileResultCallback, status?: number): SendFileResult
#send(data: any, status?: number): SendResult
#sendStatus(status: number): SendStatusResult
Results
BaseResult
All of result classes must be extended from BaseResult
because tachijs can recognize results by instanceof BaseResult
.
It has only one abstract method which must be defined by descendant classes.
execute(req: express.Request, res: express.Response, next: express.NextFunction): Promise<any>
tachijs will use this method to finalize response.
new EndResult(data: any, encoding?: string, status: number = 200)
tachijs will finalize response with res.status(status).end(data, encoding)
.
new JSONResult(data: any, status: number = 200)
tachijs will finalize response with res.status(status).json(data)
.
new NextResult(error?: any)
tachijs will finalize response with next(error)
.
new RedirectResult(location: string, status?: number)
tachijs will finalize response with res.redirect(location)
(or res.redirect(status, location)
if the status is given).
new RenderResult(view: string, locals?: any, callback?: RenderResultCallback, status: number = 200)
tachijs will finalize response with res.status(status).render(view, locals, (error, html) => callback(error, html, req, res, next))
new SendFileResult(filePath: string, options: any, callback?: SendFileResultCallback, status: number = 200)
tachijs will finalize response with res.status(status).sendFile(filePath, options, (error) => callback(error, req, res, next))
new SendResult(data: any, status: number = 200)
tachijs will finalize response with res.status(status).send(data)
.
new SendStatusResult(status: number)
tachijs will finalize response with res.sendStatus(status)
.
@inject(key: string)
Inject a registered service in container by the given key
.
class Injector
new Injector<C>(container: C)
Instantiate an injector with container
#instantiate(Constructor: any): any
Instantiate a service constructor. If the constructor has injected services, this method instantiate and inject them by #inject
method.
#inject<S = any>(key: string): S
Instantiate a service by a key from Container. If there is no service for the given key, it will throws an error.
License
MIT © Junyoung Choi