1.1.20 • Published 1 year ago

@sfd-br/util v1.1.20

Weekly downloads
52
License
ISC
Repository
-
Last release
1 year ago

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 = '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'

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
ParameterDescription(Optional)
level (string)Log levelNo
message (...string)MessageNo

trace

Logger.trace('Trace text message.')
Logger.trace('Trace','text','message.') // Many string arguments
ParameterDescription(Optional)
message (...string)MessageNo

debug

Logger.debug('Debug text message.')
Logger.debug('Debug','text','message.') // Many string arguments
ParameterDescription(Optional)
message (...string)MessageNo

info

Logger.info('Info text message.')
Logger.info('Info','text','message.') // Many string arguments
ParameterDescription(Optional)
message (...string)MessageNo

warn

Logger.warn('Warn text message.')
Logger.warn('Warn','text','message.') // Many string arguments
ParameterDescription(Optional)
message (...string)MessageNo

error

Logger.error('Error text message.')
Logger.error('Error','text','message.') // Many string arguments
ParameterDescription(Optional)
message (...string)MessageNo

fatal

Logger.fatal('Fatal text message.')
Logger.fatal('Fatal','text','message.') // Many string arguments
ParameterDescription(Optional)
message (...string)MessageNo

Error

This module provide 2 modules: ResponseError and Err.

ResponseError

ResponseError is a class that encapsulate an error based in the RFC-7807

AttributeDescription
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);
ParameterDescription(Optional)
statusCode (number)Http status codeNo
typeCode (number)Message codeNo
instanceCode (string)Instance codeYes
params (Object)JSON message parametersYes
throwInternalError

This method throw a ResponseError with statusCode: 500 based any type of error.

Err.throwInternalError(err);
ParameterDescription(Optional)
error (Error)Any type of errorNo

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);
ParameterDescription(Optional)
params (Object)Http query parameteres in JSON formatNO
ReturnsDescription
stringQuery parameters in a string format
makeRequest

This method make a http request.

Request.makeRequest(method, url, header, body);
ParameterDescription(Optional)
method (string)Http method (GET, POST, PUT, DELETE, PATCH)NO
url (string)Http Request URINO
body (Object)Http BodyYES
header (Object)Http headersYES
ReturnsDescription
PromiseReturn a Http Request promise
get

This method make a GET http request.

async Request.get(url, header);
ParameterDescription(Optional)
url (string)Http Request URINO
header (Object)Http headersYES
ReturnsDescription
ObjectReturn a Http Response
post

This method make a POST http request.

async Request.post(url, body, header);
ParameterDescription(Optional)
url (string)Http Request URINO
body (Object)Http BodyNO
header (Object)Http headersYES
ReturnsDescription
ObjectReturn Http Response
put

This method make a PUT http request.

async Request.put(url, body, header);
ParameterDescription(Optional)
url (string)Http Request URINO
body (Object)Http BodyNO
header (Object)Http headersYES
ReturnsDescription
ObjectReturn Http Response
delete

This method make a DELETE http request.

async Request.del(url, body, header);
ParameterDescription(Optional)
url (string)Http Request URINO
body (Object)Http BodyNO
header (Object)Http headersYES
ReturnsDescription
ObjectReturn Http Response
patch

This method make a PATCH http request.

async Request.patch(url, body, header);
ParameterDescription(Optional)
url (string)Http Request URINO
body (Object)Http BodyNO
header (Object)Http headersYES
ReturnsDescription
ObjectReturn 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);
ParameterDescription(Optional)
res (Object)Express Http ResponseNO
result (Object)Response resultNO
ReturnsDescription
Http status code - number200
successPlain

This method send a success response in TEXT format.

Response.successPlain(res, text);
ParameterDescription(Optional)
res (Object)Express Http ResponseNO
text (string)Response result textNO
ReturnsDescription
Http status code - number200
created

This method send a created response in JSON format.

Response.created(res, result);
ParameterDescription(Optional)
res (Object)Express Http ResponseNO
result (string)Response resultNO
ReturnsDescription
Http status code - number201
noContent

This method send a no content response.

Response.noContent(res);
ParameterDescription(Optional)
res (Object)Express Http ResponseNO
ReturnsDescription
Http status code - number204
error

This method send an error response in JSON format from YAML File.

Response.error(res, statusCode, typeCode, instanceCode, params);
ParameterDescription(Optional)
res (Object)Express Http ResponseNo
statusCode (number)Http status codeNo
typeCode (number)Message codeNo
instanceCode (string)Instance codeYes
params (Object)JSON message parametersYes
ReturnsDescription
Http status code - numberstatusCode of the ResponseError
fromError

This method send an error response in JSON format.

Response.fromError(res, error);
ParameterDescription(Optional)
res (Object)Express Http ResponseNO
error (string)Error typeNO
ReturnsDescription
Http status code - numberstatusCode 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));
ParameterDescription(Optional)
trace (object)Tracer InstanceNo
ReturnsDescription
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
}));
ParameterDescription(Optional)
trace (object)Tracer InstanceNo
options (object)OptionsYes
ReturnsDescription
Express Middleware - (function)A function containing the arguments (req, res, next)
Options
OptionDescriptionDefault 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));
ParameterDescription(Optional)
trace (object)Tracer InstanceNo
ReturnsDescription
Express Middleware - (function)A function containing the arguments (req, res, next)
1.1.20

1 year ago

1.1.19

2 years ago

1.1.18

2 years ago

1.1.17

3 years ago

1.1.16

4 years ago

1.1.15

4 years ago

1.1.14

5 years ago

1.1.13

5 years ago

1.1.12

5 years ago

1.1.11

5 years ago

1.1.10

5 years ago

1.1.9

5 years ago

1.1.8

5 years ago

1.1.7

5 years ago

1.1.6

5 years ago

1.1.5

5 years ago

1.1.4

5 years ago

1.1.3

5 years ago

1.1.2

5 years ago

1.1.1

5 years ago

1.1.0

5 years ago

0.0.33

5 years ago

0.0.32

5 years ago

0.0.31

5 years ago

0.0.30

5 years ago

0.0.29

5 years ago

0.0.28

5 years ago

0.0.27

5 years ago

0.0.26

5 years ago

0.0.25

5 years ago

0.0.24

5 years ago

0.0.23

5 years ago

0.0.22

5 years ago

0.0.21

5 years ago

0.0.20

5 years ago

0.0.19

5 years ago

0.0.18

5 years ago

0.0.17

5 years ago

0.0.16

5 years ago

0.0.15

5 years ago

0.0.14

5 years ago

0.0.13

5 years ago

0.0.12

5 years ago

0.0.11

5 years ago

0.0.10

5 years ago

0.0.9

5 years ago

0.0.8

5 years ago

0.0.7

5 years ago

0.0.6

5 years ago

0.0.5

5 years ago

0.0.4

5 years ago

0.0.3

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago