npm install @sfd-br/util
In most Rest Services projects, error messages are not handled with adequate standardization. To do this, the library provides an RFC-based error message standardization mechanism RFC-7807.
The message file needs to be a YAML File like:
types:
- transfer:
type_code: 1000
type: <URI>
title: Transfer Error
instances:
- insufficient_funds:
instance_code: 1
instance: <URI>#insufficient_funds
detail: You attempted to make a ${value} transfer, but your balance is ${balance}
- blocked_account:
instance_code: 2
instance: <URI>#blocked_account
detail: Your account ${account} is locked
- Your file need to start with the
types (array) key and the child elements
- You can give a name for any type of your preference. In our example the name is
transfer
- Inside the type
transfer you must declare a few attributes like:
type_code (number): It represents a global error specifically about the type. In our example every transfer error.
type (string): It represents the type URI.
title (string): Error title.
instances (array): Instances are the problems with a high granularity. Each instance have a name of your preference. In our example the names are insufficient_funds and blocked_account. Instances have a few attributes like:
instance_code (number): It represents a specific error.
instance (string): It represents the instance URI. This URI is specific for each detailed problem.
detail (string): Detailed message.
The configuration is provided by the Config Object, setup method. This method accept some options in JSON format.
For example:
const { Config } = require('@sfd-br/util');
Config.setup({
yaml: { filePath: <YAML_FILE_PATH>.yaml },
logger: { name: 'ServiceName', level: 'debug', module: module }
});
If you need to standardlize your error messages, you should use and initialize the configuration with the following parameters:
filePath: YAML File Path that define the error messages.
If you need to standardlize your error messages, you should use and initialize the configuration with the following parameters:
level: Log level.
name: Service name for the log.
This module is responsible to start the configuration for standard Error Message and Log.
const { Config } = require('@sfd-br/util');
Config.setup({
yaml: { filePath: <YAML_FILE_PATH>.yaml }
});
Config.setup({
logger: { name: 'ServiceName', level: 'debug', module: module, jsonFormat: false }
});
This module provide the Log methods.
If you don't pass options configuration for LOG in the Config.setup, the module Logger will be started with Log level: 'error', name: 'service', module: undefined and jsonFormat: false.
const { Logger } = require('@sfd-br/util');
Logger module has a few constants, and the values are:
Logger.LOG_LEVEL.TRACE = 'verbose'
Logger.LOG_LEVEL.DEBUG = 'debug'
Logger.LOG_LEVEL.INFO = 'info'
Logger.LOG_LEVEL.WARN = 'warn'
Logger.LOG_LEVEL.ERROR = 'error'
Logger.LOG_LEVEL.FATAL = 'fatal'
Logger module has a few methods, like:
Logger.log(Logger.LOG_LEVEL.INFO, 'Info text message.')
Logger.log(Logger.LOG_LEVEL.INFO, 'Info','text','message.') // Many string arguments
| Parameter |
Description |
(Optional) |
level (string) |
Log level |
No |
message (...string) |
Message |
No |
Logger.trace('Trace text message.')
Logger.trace('Trace','text','message.') // Many string arguments
| Parameter |
Description |
(Optional) |
message (...string) |
Message |
No |
Logger.debug('Debug text message.')
Logger.debug('Debug','text','message.') // Many string arguments
| Parameter |
Description |
(Optional) |
message (...string) |
Message |
No |
Logger.info('Info text message.')
Logger.info('Info','text','message.') // Many string arguments
| Parameter |
Description |
(Optional) |
message (...string) |
Message |
No |
Logger.warn('Warn text message.')
Logger.warn('Warn','text','message.') // Many string arguments
| Parameter |
Description |
(Optional) |
message (...string) |
Message |
No |
Logger.error('Error text message.')
Logger.error('Error','text','message.') // Many string arguments
| Parameter |
Description |
(Optional) |
message (...string) |
Message |
No |
Logger.fatal('Fatal text message.')
Logger.fatal('Fatal','text','message.') // Many string arguments
| Parameter |
Description |
(Optional) |
message (...string) |
Message |
No |
This module provide 2 modules: ResponseError and Err.
ResponseError is a class that encapsulate an error based in the RFC-7807
| Attribute |
Description |
statusCode (number) |
Http status code |
typeCode (number) |
Message code |
type (string) |
Message URI |
title (string) |
Message title |
instanceCode (number) |
Message detail code |
instance (string) |
Message detail URI |
detail (string) |
Message detail |
params (Object) |
JSON Response Parameters |
Err is a module that provides 2 methods for throw ResponseError.
If you don't pass options configuration for YAML in the Config.setup, the throwError method will fail. It happens because YAML File wasn't specified.
This method throw a ResponseError based in YAML Message File.
Err.throwError(statusCode, typeCode, instanceCode, params);
| Parameter |
Description |
(Optional) |
statusCode (number) |
Http status code |
No |
typeCode (number) |
Message code |
No |
instanceCode (string) |
Instance code |
Yes |
params (Object) |
JSON message parameters |
Yes |
This method throw a ResponseError with statusCode: 500 based any type of error.
Err.throwInternalError(err);
| Parameter |
Description |
(Optional) |
error (Error) |
Any type of error |
No |
This module provide an infrastructure to HttpRequest and HttpResponse.
This module represents a HttpRequest.
const { Request } = require('@sfd-br/util');
Request module has a few constants, and the values are:
Request.HTTP_METHOD.GET = 'GET'
Request.HTTP_METHOD.POST = 'POST'
Request.HTTP_METHOD.PUT = 'PUT'
Request.HTTP_METHOD.PATCH = 'PATCH'
Request.HTTP_METHOD.DELETE = 'DELETE'
This method build query parameters in a JSON format.
Request.configParams(params);
| Parameter |
Description |
(Optional) |
params (Object) |
Http query parameteres in JSON format |
NO |
| Returns |
Description |
string |
Query parameters in a string format |
This method make a http request.
Request.makeRequest(method, url, header, body);
| Parameter |
Description |
(Optional) |
method (string) |
Http method (GET, POST, PUT, DELETE, PATCH) |
NO |
url (string) |
Http Request URI |
NO |
body (Object) |
Http Body |
YES |
header (Object) |
Http headers |
YES |
| Returns |
Description |
Promise |
Return a Http Request promise |
This method make a GET http request.
async Request.get(url, header);
| Parameter |
Description |
(Optional) |
url (string) |
Http Request URI |
NO |
header (Object) |
Http headers |
YES |
| Returns |
Description |
Object |
Return a Http Response |
This method make a POST http request.
async Request.post(url, body, header);
| Parameter |
Description |
(Optional) |
url (string) |
Http Request URI |
NO |
body (Object) |
Http Body |
NO |
header (Object) |
Http headers |
YES |
| Returns |
Description |
Object |
Return Http Response |
This method make a PUT http request.
async Request.put(url, body, header);
| Parameter |
Description |
(Optional) |
url (string) |
Http Request URI |
NO |
body (Object) |
Http Body |
NO |
header (Object) |
Http headers |
YES |
| Returns |
Description |
Object |
Return Http Response |
This method make a DELETE http request.
async Request.del(url, body, header);
| Parameter |
Description |
(Optional) |
url (string) |
Http Request URI |
NO |
body (Object) |
Http Body |
NO |
header (Object) |
Http headers |
YES |
| Returns |
Description |
Object |
Return Http Response |
This method make a PATCH http request.
async Request.patch(url, body, header);
| Parameter |
Description |
(Optional) |
url (string) |
Http Request URI |
NO |
body (Object) |
Http Body |
NO |
header (Object) |
Http headers |
YES |
| Returns |
Description |
Object |
Return Http Response |
This module represents a HttpResponse.
const { Response } = require('@sfd-br/util');
Response module has a few constants, and the values are:
Response.HTTP_STATUS.OK = 200
Response.HTTP_STATUS.CREATED = 201
Response.HTTP_STATUS.NO_CONTENT = 204
Response.HTTP_STATUS.BAD_REQUEST = 400
Response.HTTP_STATUS.UNAUTHORIZED = 401
Response.HTTP_STATUS.FORBIDDEN = 403
Response.HTTP_STATUS.NOT_FOUND = 404
Response.HTTP_STATUS.UNPROCESSABLE = 422
Response.HTTP_STATUS.INTERNAL_SERVER_ERROR = 500
Response.TYPE.JSON = 'JSON'
Response.TYPE.TEXT = 'TEXT'
This method send a success response in JSON format.
Response.success(res, result);
| Parameter |
Description |
(Optional) |
res (Object) |
Express Http Response |
NO |
result (Object) |
Response result |
NO |
| Returns |
Description |
Http status code - number |
200 |
This method send a success response in TEXT format.
Response.successPlain(res, text);
| Parameter |
Description |
(Optional) |
res (Object) |
Express Http Response |
NO |
text (string) |
Response result text |
NO |
| Returns |
Description |
Http status code - number |
200 |
This method send a created response in JSON format.
Response.created(res, result);
| Parameter |
Description |
(Optional) |
res (Object) |
Express Http Response |
NO |
result (string) |
Response result |
NO |
| Returns |
Description |
Http status code - number |
201 |
This method send a no content response.
Response.noContent(res);
| Parameter |
Description |
(Optional) |
res (Object) |
Express Http Response |
NO |
| Returns |
Description |
Http status code - number |
204 |
This method send an error response in JSON format from YAML File.
Response.error(res, statusCode, typeCode, instanceCode, params);
| Parameter |
Description |
(Optional) |
res (Object) |
Express Http Response |
No |
statusCode (number) |
Http status code |
No |
typeCode (number) |
Message code |
No |
instanceCode (string) |
Instance code |
Yes |
params (Object) |
JSON message parameters |
Yes |
| Returns |
Description |
Http status code - number |
statusCode of the ResponseError |
This method send an error response in JSON format.
Response.fromError(res, error);
| Parameter |
Description |
(Optional) |
res (Object) |
Express Http Response |
NO |
error (string) |
Error type |
NO |
| Returns |
Description |
Http status code - number |
statusCode of the ResponseError |
This module provide Tracing methods to map the requests among the microservices.
If you don't pass options configuration for LOG in the Config.setup, the module Logger will be started with Log level: 'error', name: 'service', module: undefined and jsonFormat: false.
const { Tracing } = require('@sfd-br/util');
Tracing module has a few constants, and the values are:
Tracing.TRACE.ACTIVATION_TYPE.YES = true
Tracing.TRACE.ACTIVATION_TYPE.NO = false
Tracing.TRACE.ACTIVATION_TYPE.HEADER = 'header'
Tracing module has a few methods, like:
Use this method to pass as an argument an implementation instance of the opentracing specification.
Under you can see an example using the jaeger-client.
const { Tracing, Logger } = require('@sfd-br/util');
const { initTracer } = require('jaeger-client');
const config = {
serviceName: 'Service1',
logging: true,
sampler: {
type: 'const',
param: 1,
},
reporter: {
collectorEndpoint: 'http://localhost:14268/api/traces',
logSpans: true
}
};
const options = {
tags: {
'service.version': '1.0.0',
},
logger: {
info: Logger.info,
error: Logger.error
},
};
const tracer = Tracing.setupTracer(initTracer(config, options));
| Parameter |
Description |
(Optional) |
trace (object) |
Tracer Instance |
No |
| Returns |
Description |
trace - (object) |
A wrapper of the tracer |
Use this ExpressJS middleware method to init a Span in your service or to get some parent SpanContext and associate with your new Span. You have to pass as an argument the tracer returned in the Tracing.setupTracer method and there are some options to pass as argument if you want.
Under you can see an example using the jaeger-client.
const express = require('express');
const { Tracing, Logger } = require('@sfd-br/util');
const { initTracer } = require('jaeger-client');
const app = express();
// ...
const tracer = Tracing.setupTracer(initTracer(config, options));
// ...
app.use(Tracing.initSpanMiddleware(tracer, {
serviceName: 'service1',
namespace: 'sfd',
extract: [],
tracingEnabled: Tracing.TRACE.ACTIVATION_TYPE.HEADER
}));
| Parameter |
Description |
(Optional) |
trace (object) |
Tracer Instance |
No |
options (object) |
Options |
Yes |
| Returns |
Description |
Express Middleware - (function) |
A function containing the arguments (req, res, next) |
| Option |
Description |
Default Value |
serviceName (string) |
The name of your service |
'service' |
namespace (string) |
The namespace for content variables |
'sfd' |
extract (array) |
Makes possible to extract data from objects deep using the dot notation |
[] |
| `tracingEnabled (boolean |
string)` |
Makes possible to enable/disable the tracing. The default value is 'header', it means that you have to pass a http header called sfd-tracing equal true or false to enable or disable it in the http request. Another options are true or false to enable or disable independent of http header. See Tracing Constants in this section to see the available values. |
Use this ExpressJS middleware method to finish a Span started when you used the Tracing.initSpanMiddleware method in your service. You have to pass as an argument the tracer returned in the Tracing.setupTracer method.
Under you can see an example using the jaeger-client.
const express = require('express');
const { Tracing, Logger } = require('@sfd-br/util');
const { initTracer } = require('jaeger-client');
const app = express();
// ...
const tracer = Tracing.setupTracer(initTracer(config, options));
// ...
app.use(Tracing.finishSpan(tracer));
| Parameter |
Description |
(Optional) |
trace (object) |
Tracer Instance |
No |
| Returns |
Description |
Express Middleware - (function) |
A function containing the arguments (req, res, next) |