@sfd-br/util

SFD Utils

Usage no npm install needed!

<script type="module">
  import sfdBrUtil from 'https://cdn.skypack.dev/@sfd-br/util';
</script>

README

Installing

npm install @sfd-br/util

Error Messages

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.

Example

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.

Configuration

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 }
});

YAML Error Messages Options

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.

Log Options

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.

API

Config

This module is responsible to start the configuration for standard Error Message and Log.

const { Config } = require('@sfd-br/util');

Error Message

Config.setup({
    yaml: { filePath: <YAML_FILE_PATH>.yaml }
});

Log

Config.setup({
    logger: { name: 'ServiceName', level: 'debug', module: module, jsonFormat: false }
});

Logger

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');

Constants

Logger module has a few constants, and the values are:

  • Logger.LOG_LEVEL.TRACE = 'trace'
  • 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'

Methods

Logger module has a few methods, like:

log

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

trace

Logger.trace('Trace text message.')
Logger.trace('Trace','text','message.') // Many string arguments
Parameter Description (Optional)
message (...string) Message No

debug

Logger.debug('Debug text message.')
Logger.debug('Debug','text','message.') // Many string arguments
Parameter Description (Optional)
message (...string) Message No

info

Logger.info('Info text message.')
Logger.info('Info','text','message.') // Many string arguments
Parameter Description (Optional)
message (...string) Message No

warn

Logger.warn('Warn text message.')
Logger.warn('Warn','text','message.') // Many string arguments
Parameter Description (Optional)
message (...string) Message No

error

Logger.error('Error text message.')
Logger.error('Error','text','message.') // Many string arguments
Parameter Description (Optional)
message (...string) Message No

fatal

Logger.fatal('Fatal text message.')
Logger.fatal('Fatal','text','message.') // Many string arguments
Parameter Description (Optional)
message (...string) Message No

Error

This module provide 2 modules: ResponseError and Err.

ResponseError

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

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.

Methods

throwError

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
throwInternalError

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

HTTP

This module provide an infrastructure to HttpRequest and HttpResponse.

Request

This module represents a HttpRequest.

const { Request } = require('@sfd-br/util');

Constants

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'

Methods

configParams

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
makeRequest

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
get

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
post

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
put

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
delete

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
patch

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

Response

This module represents a HttpResponse.

const { Response } = require('@sfd-br/util');

Constants

Response module has a few constants, and the values are:

Status Code
  • 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
Content Type
  • Response.TYPE.JSON = 'JSON'
  • Response.TYPE.TEXT = 'TEXT'

Methods

success

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
successPlain

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
created

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
noContent

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
error

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
fromError

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

Tracing

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');

Constants

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'

Methods

Tracing module has a few methods, like:

setupTracer

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

initSpanMiddleware

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)
Options
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. 'header'

finishSpanMiddleware

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)