ts-service
ts-service is a TypeScript library for validation and logging.
It depends on joi (validator) and bunyan (logger)
Installation
npm i ts-service
Features
- Input logging (input parameters):
myService: ENTER methodName: {param1: 'foo', param2: 'bar'}
- Output logging (sync and async):
myService: EXIT methodName: {result: 'foobar', anotherProp: 'bar'}
- Error logging with input parameters (see example below).
- Input validation and normalization (example: string type
"2"
to number type2
).
add @schemaJoi.number.required a: number,
- Validation with inline annotation.
sendEmail @schemaJoi.string.email.required email: string
- Validation with class annotation.
sendEmailvalues: SendEmailValues
Example usage (inline annotation)
file services/CalcService.ts
;; // create your service;
use service
; calcService.add1, 3; // returns 4calcService.add'5' as any, '6' as any; // returns 11, input parameters are converted to number typescalcService.add'1' as any, as any; // logs and throws an error// NOTE: you shouldn't use casting `as any` in your code. It's used only for a demonstration purpose.// The service is expected to be called with unknown input (for example: req.body).
See example under examples/example1.ts
. Run it using npm run example1
.
Async example usage (class annotation)
file services/UserService.ts
;; // create your service;
use service
; await userService.createUser; // okawait userService.createUser; // throws an error
See example under examples/example2.ts
. Run it using npm run example2
.
Removing security information
By default properties password
, token
, accessToken
are removed from logging.
Additionally you can annotated method with @removeOutput
to remove the method result.
Example:
file services/SecurityService.ts
;; // create your service;
use service
; securityService.hashPassword'secret-password';
See example under examples/example3.ts
. Run it using npm run example3
.
Configuration
; configure
You must configure it, before creating any service.
Special properties
if the parameter name is req
it's assumed that the object is an express request.
Only properties are logged: method
, url
, headers
, remoteAddress
, remotePort
.
if the parameter name is res
it's assumed that the object is an express response.
Only properties are logged: statusCode
, header
.
MIT License