@crubn/indisi-common
v1.0.3
Published
Common components for Indisi microservices
Downloads
6
Readme
Indisi common
#
Repository for all the components that are to be used by various microservices in the Indisi project. The aim of this is to reduce redundancies across microservices. This repository will be published as an npm packages which should be imported in the microservices.
Components
How to use
Add .npmrc
file inside root directory of your project, .npmrc
should contain:
@crubn:registry=https://npm.pkg.github.com/
//npm.pkg.github.com/:_authToken=PKG_TOKEN
PKG_TOKEN
is a GitHub access token that has at least read:packages
permission. Tutorial for creating a access token.
0. Configuration
To use modules such as mongo, redis, etc. that need configuration (host, port, etc.) to run, in the main project file, do the following
import {configure} from '@crubn/indisi-common';
// Configure the indisi common module
configure(config.get('common'));
The configuration should be as following, along with other project specific config.
{
"common": {
"logger": {
"level": "LOG_LEVEL",
"dir": "LOG_DIR",
"mail": {
"recipients": "LOG_MAIL_RECIPIENTS",
"sender": "LOG_MAIL_SENDER",
"smtp": {
"host": "LOG_MAIL_SMTP_HOST",
"port": "LOG_MAIL_SMTP_PORT",
"username": "LOG_MAIL_SMTP_USERNAME",
"password": "LOG_MAIL_SMTP_PASSWORD"
}
}
},
"mongo": {
"host": "MONGO_HOST",
"port": "MONGO_PORT",
"username": "MONGO_USERNAME",
"password": "MONGO_PASSWORD",
"defaultDatabase":"MONGO_DEFAULT_DB"
},
"redis": {
"host": "REDIS_HOST",
"port": "REDIS_PORT",
"password": "REDIS_PASSWORD",
"streamThreshold": "REDIS_STREAM_THRESHOLD"
}
}
}
1. Helpers
import {Constants, Messages} from '@crubn/indisi-common'
2. Logger
import {Logger} from '@crubn/indisi-common';
const logger = Logger.getInstance();
logger.fatal('The universe is a cruel, uncaring void. The key to being happy isn't to search for meaning. It's to just keep yourself busy with unimportant nonsense, and eventually, you'll be dead.');
All standard log levels are supported
3. Middlewares
import {AuthenticationMiddleware, AuthorizationMiddleware, ValidationMiddleware, RequestProperty} from '@crubn/indisi-common'
// Use as express middlware
// Authentication
app.use(`/some-path`, AuthenticationMiddleware.authenticate);
// Authorization
// To check if org is active
app.use(`/some-path`, AuthorizationMiddleware.isOrgActive);
// To check if user is super admin
app.use(`/some-path`, AuthorizationMiddleware.isSuperAdmin);
// Validation
// validate request structure - body, path or query params
ValidationMiddleware.validateDto(RequestProperty.BODY ,CreateProofTemplateDto)
4. Mongo
import {Mongo} from '@crubn/indisi-common';
Mongo.connect();
5. Redis (stream)
import {Redis} from '@crubn/indisi-common';
Redis.connect().then(()=>{
// read streams here
this.readStreams();
});
private readStreams = () => {
Redis.readStream(config.get('redisStream.consumerGroupName'),
config.get('redisStream.consumerName'),
config.get('redisStream.names'),
(streamName, stream, done)=>{
// Do something
logger.debug(`Received stream messages - ${streamName} - ${JSON.stringify(stream.messages)}`);
this.streamReaders.forEach((reader) => {
reader(streamName, stream, done);
});
});
};
done()
should be invoked to acknowledge that the message has been successfully processed by the reader.
6. WebApi
import {WebApiResponse, WebApi} from '@crubn/indisi-common';
const result = await this.proofTemplateService.createProofTemplate(orgId, proofTemplate);
const responseData: WebApiResponse = WebApiResponse.successResponse(result);
response.status(httpStatusCodes.CREATED).json(responseData);
.
.
.
const response = await WebApi.instance.execute({
httpMethod: 'POST',
url: url,
headers: {
'Authorization': `Bearer ${orgWalletToken}`,
'X-API-Key': config.get('cloudAgent.apiKey'),
},
body: requestBody,
});
7. Error Handler
Pass all the errors to the error handler
import {ErrorHandler} from '@crubn/indisi-common';
// index.ts
process.on('uncaughtException', (error:Error) => {
ErrorHandler.handleError(error);
});
process.on('unhandledRejection', (reason: string) => {
ErrorHandler.handleError(new Error(reason));
});
// app.ts
// Error handling middleware, we delegate the handling to the centralized error handler
// eslint-disable-next-line @typescript-eslint/no-unused-vars
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
ErrorHandler.handleError(err, res);
});
8. Http Error
import {HttpError, Messages} from '@crubn/indisi-common';
// throw error when needed in the service
throw new HttpError(httpStatusCodes.NOT_FOUND, Messages.resourceNotFound);