README
Download package
npm init -y
npm install tsnode-express --save
Configure tsconfig.json
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"declaration": true,
"strict": false,
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
}
}
Start application
Create index.ts file
;;;application.start
start
method is async
Notice the start
method pass to callback express and config provider
Compile code with ts-node
./node_modules/.bin/ts-node index.ts
You can install ts-node globally, connect nodemon or configure somehow else
Make first request
Expected result for GET http://localhost:3000/health
Write the Controller
Note: all classes should had written before appplication.start() had called
;
The "Controller" decorator accepts as argument base path to route
The "Get" decorator accepts as agrument additional path to route
Expected result fot the GET http://localhost:3000/some
Use dependency injections
The application support dependency injection mechanism
;
Modify your controller
;
Expected result fot the GET http://localhost:3000/some/service
You can also inject any class wich marked as Service() not only in controllers
Service injected in other service wil be works too
Use ConfigProvider as injection
Insert before applocation.start() function
application.useConfig;
useConfig
method can be async and used in chain
Notice the Modify your service or controller
;
Expected result fot the GET http://localhost:3000/some/service
Response
Working with request params and request query
;
Expected result fot the POST http://localhost:3000/some/echo/echoParam?echo=echoQuery
Request
Response
Use reuest`s Before and After hooks
Add hooks and route function to the controller
In afrer hook available result object wich collect data from original method
beforeWithHooksreq: IRequest, res: IResponse, next: Function withHooksargs: IRequestArguments afterWithHooksreq: IRequest, res: IResponse, next: Function
Expected result fot the GET http://localhost:3000/some/hooks
Response
Hooks are accepts in first argument method type wich you want define for hook GET, POST etc As second argument you should pass a path to route Hooks can works separately from original function if you don`t need it As example you can work with webhooks and use only @Before wook to validate headers or do with request something else
Example single hooks
singleBeforeHookreq: IRequest, res: IResponse, next: Function
Expected result fot the GET http://localhost:3000:3000/some/single-before-hook/someParam
Response
singleAfterHookreq: IRequest, res: IResponse, next: Function
Expected result fot the GET http://localhost:3000:3000/some/single-after-hook/someParam
Response
Afrer hook should always close response
AUTHORIZATION
Application contains the powerfull authorization interface
Write authorization provider
Verify function should terurns the promise
;
AuthProvider
application ConfigProvider
or any other service
You can inject in verify
you can get on request handler
Any object which you returns from AuthTarget
Example of AuthTarget {
controller: 'AuthController',
method: 'get',
basePath: '/auth',
path: '/me',
functionName: 'me',
role: 'default',
roles: [ 'default', 'admin', 'super' ],
fullPath: '/auth/me' }
Insert before applocation.start() function and define where and how you want to handle auth token
application.useAuthorizationProviderAuthProvider,
By defalult options looks like
AuthOptions {
authorizationHeader: 'authorization',
authorizationQueryParam: 'access_token',
authorizationBodyField: 'accessToken' }
Decorare your controller
Rigth now any request to /auth
will be sequre by AuthProvider verify
handler
Authorization oprions
@Authorization
decorator accept role/roles otions which will be inclured to AuthTarget
object
in AuthProvider
verify
handler
Authorization oppions in routes decorator
Route decorator also accept role/roles otions which will be inclured to AuthTarget
object
in AuthProvider
verify
handler
Also you can exclude some routes from authorization inside sequre controller This migth be helps when controller needs to be sequre but some routes should be public For example in case when you configure webhook with custom auth
Enabling internal logging
logLevels might contains array as described below
- info - logging the incoming request(path, target functions)
- success - runs once when server starts and display sucessfuly builded routes
- error - always print stactrace and display errors without statusCodes
- warning - display errors which was throwed mannualy and contains the statusCodes
printStack says to application is the print stack trace required on warnings.
These options by defaulf is empty
application.useConfig;
CORS and primary configuretion not includet to lib yet
Constructor of applications retunrs an express instance so you can configure it before application builds
Example how to configure CORS
;
express.use
and can be used in chain
Application has his own wrapper for ; application .usecors .use/** another handler */ .use/** another handler */});
Error Handling
The applications uses as error lib https://www.npmjs.com/package/ts-http-errors
So applications allows to override handleError
and handleNotFound
methods
which uses as express middleware
;app.handleError =
You can choose another way and extend your own class from application
;app.start;
Building from several files and folders
As the typescript import
is different with nodejs require
Application have a simple stub to keep code structural
Example:
- moduleA
- service.ts
- controller.ts
- index.ts
- moduleB
- controller.ts
- service.ts
- index.ts
- index.ts
;; ; application .registerModulemoduleA; .registerModulemoduleB;
External Injections
Application support external injections throuth
public injectname: string, cb: Function: Application;public injectinstance: T: Application;
So you can inject to application already creates instances or use factory to create incjection. Factory can be async
Exapmple
; ; ; application .injectinjectedService .inject'IInjectedService',
And after application start those can be available on services or controllers