This package contains all common libraries for Robbyson services
Last updated 2 months ago by phfernandes .
ISC · Original npm · Tarball · package.json
$ cnpm install robbyson-library-v2 
SYNC missed versions from official npm registry.

Robbyson Library

pipeline status

coverage report

A library with a set of useful functions in Robbyson services environment.


Robbyson Database Connection

Robbyson database connection is the library responsible for accessing mongodb databases mongodb in Robbyson environment.

It creates connections on demand, by registering the required ones on a express middleware. When the API user accesses some service, the application searches and connects to some specific mongodb database. In cases that the service connects to contractors database, a new contractor's connection is automaticaly made when the first user requests some resource. This connection, after that, is cached and reused by other user's requets.

It supports two kinds of connections:

  • contractor's connection: connects to databases exclusive for some contractor in robbyson env. This connection is created based on some connection handle identification, passed on the robbyson database middleware.
  • static connections: connects to databases common to all contractors. This connections are identified by an unique inside the service string key and the connection configurations.

Robbyson database connection includes some extra utilities, like the query explainer middleware. It gives the developer informations about the queries executed, showing some harmfull queries.


First, you must create the connections on the service's middleware. It can be a static connection, in other words, a simple connection, shared by all users. It is identified by a tuple, containing the connection's identifier and the connection config.

It can also be a contractor's specific connection, aka instance connection. It is identified by the connection's identifier.

// app.js
import { robbysonDatabase } from 'robbyson-library-v2';
// registering the middleware
// ...
const connectionConfig = {
    server: 'string',
    user: 'string',
    password: 'string',
    database: 'string',
    static: [
        ['static_connection', connectionConfig]
    instance: [ 'pre_configured_instance_connection' ]

To access the database, you can use the modelProvider module. It exposes two methods: getStaticConnectionByName, that accesses some static connections registered in the middleware, and getByContractorId, that returns models for instance connections. Both of them requires an identifier, the static connection registered in the middleware or the contractor id, and a mongoose schema. The connection and models created will be cached at the first try, and reused from now on.

// service.js
import { robbysonDatabase } from 'robbyson-library-v2';

const modelProvider = robbysonDatabase.modelProvider;
const staticConnectionModel = modelProvider.getStaticConnectionByName('static_connection', myMongooseSchema);
const contractorBasedModel = modelProvider.getByContractorId(
    1001, myMongooseSchema
contractorBasedModel.findOne({ _id: 'my_id' });
staticConnectionModel.findOne({ _id: 'my_id' });

Robbyson HTTP

This library is used to make http requests. It is useful because we can pass the origin request meta data from our network handling layer to the other one, like the repositories, where services interact with other ones. This feature is highly used to log service interactions.

Robbyson HTTP exposes a singleton class. This class has a method to assign the robbyson http middleware, which intercepts the incoming request meta data, and stores it, to be used by the other public methods, which interacts directly with http methods, like GET, POST, PUT, DELETE, etc. Data collected from the incoming request will be sent via headers to the next network call. Robbyson services which assign a robbyson http middleware are able to read and use meta data sent by the former service.


// app.js
import { RobbysonHttp } from 'robbyson-library-v2';
// ...
// some-api-service-consumer.js
import { RobbysonHttp } from 'robbyson-library-v2';

const httpClient = RobbysonHttp.getInstance();
const url = 'my-awesome-api-url';
const options = {
    params: {
        _id: '123'
    headers: {
        token: 'my-secret-key-to-access-service'
httpClient.get(url, options);

Robbyson Logger

Robbyson logger is the library responsible for logging any event in robbyson services. By default, any request made for any route in the service which declares this lib's middleware, will log an event as trying to access that route and one more event, that registers the output from that route, being it a successfull or failured response.

For more informations about what is logged by this service, there's the current documentation, available here



Robbyson logger exposes a function to configure the middleware. The middleware configuration exposes the following options:

  • serviceName (required): Describes the service to be logged.
  • protectedFields (optional): Array of strings, listing all fields that must be skipped in log. by default, robbyson logger will skip password, currentPassword, newPassword and confirmationNewPassword
  • skip (optional): Array of routes that should be skipped in the logs. It is empty, by default.
  • responseProcessor (optional): Function used to process the log. By default, it uses the default processor from robbyson logger library. This function works as described in this docs.
// app.js
import { robbysonLogger } from 'robbyson-library-v2';
// ...
    serviceName: 'service_name'

Logger methods

By default, the logger can do the necessary job by itself. But, if we want to write some job manually, this is possible by logger module. This module exposes three methods:

  • logger.qualifyUser: Method used to anotate the current user's data. This method is util when user is recently authenticated, and must be qualified, so logger can send logs to correct contractor (by default, logs will be writen as broadcasted events)
  • logger.log: Method to write a log to specific contractor.
  • logger.broadcast: Method to write logs when it's not possible to recognize the user's contractor
import { robbysonLogger } from 'robbyson-library-v2';
// ...
const { logger } = robbysonLogger;

Robbyson Query Parser ????

Robbyson query parser is a node service middleware. Parses queries in a way that mongo understands. Utilizes mongoose as a data tool.


You can simply add to your service:

var express = require("express");
const robbysonQueryParser = require("robbyson-library-v2").middleware
var app = express();


A request like:$filter.identification=08646144623&$limit=100&$skip=0&$filter.primaryAttribute.value.$in=/sky.*gold/i,/tim.*gre/g

Is translated to:

  projection: {
    date: 1,
    'primaryAttribute.value': 1,
    'indicator._id': 1,
    'primaryAttribute._id': 1
  skip: 0,
  sort: { date: -1 },
  limit: 100,
  filter: {
    identification: '08646144623',
    'primaryAttribute.value': { '$in': [ /sky.*gold/i, /tim.*gre/g ] }

In your repository:

return model


There is a whitelist of allowed operators in robbyson-query-parser/utils/operators-whitelist.ts so anything else that starts with $ will throw an error by the middleware.

base operators: $filter, $fields, $sort, $skip, $limit.

mongo operators: $eq, $gt, $gte, $in, $lt, $lte, $ne, $nin, $and, $not, $nor, $or, $regex, $exists.

$filter: filter to be executed in mongo.

Accepts another mongo operators. How it works:

  • Goes another level on every $ operator.
  • Undestands consecutive field operators as same level ex: $filter.indicator._id.$eq=1 => { filter: { indicator._id: { $eq:1 } } }

$eq/$gt/$gte/$lt/$lte/$ne: $filter.identification.$eq=123 translates to:

filter: {
    identification: {
        $eq: 123;

$in/$nin: $filter.identification.$in=123&$filter.identification.$in=111 ou $filter.identification.$in=123,111 translates to:

filter: {
    identification: {
        $in: [123, 111];

$regex: $$regex=teste

filter: {
    name: {
        $regex: /teste/;


filter: {
    name: {
        $regex: /teste/i;

$or/$nor: $filter.$or.primaryAttribute.value.$regex=/teste/i&$filter.$or.indicator._id=15

filter: {
    $or: [
        { "primaryAttribute.value": { $regex: /sky/ } },
        { "indicator._id": "15" }

$sort: sort result set by fields.

Accepts Array<string> ["date", "indicator._id"] or a string joined by , "date, indicator._id".

  • To sort by field DESC add - before the field name. $fields="-date, -indicator._id" =>
{ projection: { date: -1, indicator._id: -1 }}
  • To sort by field ASC just write the field as is. $fields=["date", "indicator._id"] =>
{ projection: { date: 1, indicator._id: 1 }}

$fields: projection of fields to be returned

Accepts Array<string> ["date", "indicator._id"] or a string joined by , "date, indicator._id".

  • To exclude fields just add - before the field name. $fields="-date, -indicator._id" =>
{ projection: { date: 0, indicator._id: 0 }}
  • To include just write the field as is. $fields=["date", "indicator._id"] =>
{ projection: { date: 1, indicator._id: 1 }}

Include and Exclude fields at same time is not allowed by mongoose except the document _id field.

$skip: amount of results to skip.

Accepts a number.

$limit: quantity of results to return.

Accepts a number.


This method is usefull when it's required to parser the raw values, sent in the req.query param


import { queryParser } from 'robbyson-library-v2';

// ...
// ...

Robbyson Decoder Middleware

Middleware responsible for decoding data from authentication headers to service. This middleware interacts directly with the protocol used by apigateways.


// app.js
import { robbysonUserDecoder } from 'robbyson-library-v2';
// ...

Current Tags

  • 0.2.9                                ...           latest (2 months ago)

15 Versions

  • 0.2.9                                ...           2 months ago
  • 0.2.8                                ...           2 months ago
  • 0.2.7                                ...           8 months ago
  • 0.2.6                                ...           10 months ago
  • 0.2.5                                ...           a year ago
  • 0.2.4                                ...           a year ago
  • 0.2.3                                ...           a year ago
  • 0.2.2                                ...           a year ago
  • 0.2.1                                ...           a year ago
  • 0.2.0                                ...           a year ago
  • 0.1.0                                ...           a year ago
  • 0.0.4                                ...           a year ago
  • 0.0.3                                ...           a year ago
  • 0.0.2                                ...           a year ago
  • 0.0.1                                ...           a year ago
Today 0
This Week 0
This Month 0
Last Day 0
Last Week 0
Last Month 16
Dependencies (12)
Dev Dependencies (17)
Dependents (1)

Copyright 2014 - 2017 © |