npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

robbyson-library-v2

v0.4.7

Published

This package contains all common libraries for Robbyson services

Downloads

3,541

Readme

Robbyson Library

pipeline status

coverage report

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

Documentation

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.

Usage

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',
    port:0000,
};
app.use(robbysonDatabase.configure({
    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.

Usage

// app.js
import { RobbysonHttp } from 'robbyson-library-v2';
// ...
app.use(RobbysonHttp.getInstance().setup);
// 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

Usage

Middleware

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';
// ...
app.use(robbysonLogger.configure({
    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;
logger.qualifyUser(/*...*/);
logger.log(/*...*/);
logger.broadcast(/*...*/);

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.

Instalation:

You can simply add to your service:

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

Usage:

A request like:

http://127.0.0.1:8027?$filter.identification=08646144623&$limit=100&$skip=0&$filter.primaryAttribute.value.$in=/sky.*gold/i,/tim.*gre/g
&$fields=date,primaryAttribute.value,indicator._id,primaryAttribute._id&$sort=-date

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
    .find(filter)
    .skip(skip)
    .limit(limit)
    .sort(sort)
    .select(projection);

Operators:

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: $filter.name.$regex=teste

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

$filter.name.$regex=/teste/i

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.

queryBuilder.parser

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

usage:

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

// ...
queryParser.parser(req.query);
// ...

Robbyson Decoder Middleware

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

Usage

// app.js
import { robbysonUserDecoder } from 'robbyson-library-v2';
// ...
app.use(robbysonUserDecoderMiddleware);

Robbyson Broker Message

This library is the RabbitMQ message broker. It accepts, forwards, stores binary data blobs - messages. To work with communication between systems. Operating asynchronously.

Usage

So far this lib just sends messages, the consumption of messages is being done by routines. When necessary, they will be implemented in JavaScript services that require consuming messages if necessary.

First you must instantiate the class in the service app to start and connect to the channel

// app.js
import { RobbysonBrokerMessage } from 'robbyson-library-v2';
// ...
RobbysonBrokerMessage.getInstance();

Then you must create in the service layer o broadcast-service of the service that will consume the robbyson broker message

//some-api-service-consumer
//services/broadcast-service
import RobbysonBrokerMessage from 'robbyson-library-v2';

module.exports = {
    [ 'name_method_that_makes_sense_to_use' ]: async function([ 'objeto_to_send' ] ){
        const queueName = ' [name_queue] ';
        const broker = RobbysonBrokerMessage.getInstance();

        return await broker.sendQueueMessage(queueName, [ 'objeto_to_send' ] )
    }
}

Finally call the broadcast in the scope that will use it

//layer-service
const broadcast = require("../services/broadcast-service");

//...scope

await broadcast.[ 'name_method_that_makes_sense_to_use' ]([ 'objeto_to_send' ]);