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

gbox-helper

v1.3.47

Published

Gauss Box helper package

Downloads

24

Readme

Collection of useful helper functions, accessible in any API.    

Install

$ npm install --save gbox-apis

   

Usage

const helper = require('gbox-helper');

   

General methods

 

arrayToString(array)

Convert's array to string. Returns string.

let arr = [1,2,3];
let str = helper.arrayToString(arr);

Output:

1, 2, 3

 

randomHash()

Generates random hash string. Return string.

helper.randomHash();

Output:

655cef935de70225c0bd0e768afedbd4af20cd13

 

slugify(string)

Generates slug from random string. Return string.

helper.slugify("Some random string");

Output:

some-random-string

   

round(value, decimals)

Rounding decimal number to desire decimal places. Fix for problem rounding with toFixed method. Return number.

helper.round(100.575, 2);

Output:

100.58

   

Password

 

encrypt(password, saltRounds=10)

Async function for encrypting string with bcrypt choosing salt rounds (default 10). Returns encrypted string.

await helper.password.encrypt("mYRanDomPass123!");

Output:

$2a$10$xm7V4kGZ2dRUn8xhr9OfWOInJWYh1Yz1uGhMEJWAyv8MwmikV6WG2

 

compare(string, encrypted)

Async function for comparing encrypted string. Returns boolean true/false.

let pass = await helper.password.encrypt("mYRanDomPass123!");
let compare = await helper.password.compare("mYRanDomPass123!", pass);

Output:

true

 

generate()

Function for generating strong password. Returns string.

let pass = Helper.password.generate();

Output:

Zlfvf4t?fZela8Np?

 

strongValidate(password)

Function for strong password validation. Password must have at least one uppercase, one lowercase letter, one number and one special character, and must be at least 8 chars long. Returns JSON with isValid and errorMsg parameters.

let validate = Helper.password.strongValidate(password);

Output:

{
    "isValid": true,
    "errorMsg": ""
}

    #JsonWebToken  

issue(secret, payload, algorithm='HS512', expiresIn='60 m')

Async function for generating json web token. Accepts secret, payload, algorithm and expiresIn. Default algorithm is HS512, and default expiresIn is 60m. Returns encrypted string.

await helper.jwt.issue(secret, payload);

Output:

eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjIsImFwaUtleUlkIjoyLCJhcGlLZXlTdWJkb21haW4iOiJnYXVzc3Rlc3QiLCJlbWFpbCI6ImdhdXNzLnRlc3RAbWFpbC5jb20iLCJ1c2VybmFtZSI6IkdhdXNzVGVzdCIsInBlcm1pc3Npb24iOjEsImlhdCI6MTUyNzU3NjQyNzg2OSwiZXhwIjoxNTI3NTc2NDMxNDY5fQ.MckX_zo-UCyeKJZYPNBlqiQ_Mm6eAmkNl5SFylxMtitiv4o0Iy8ryWCDtOpuO_Ti86b9o3GglkdrqxZYs8BaoQ

 

verify(token, secret, algorithm='HS512')

Async function for verifying json web token. Accepts encrypted token, secret, and algorithm. Default algorithm is HS512. Returns payload.

await helper.jwt.verify(token, secret);

   

Database

 

makeConnectionString(connection)

Generates MySQL connection string from connection object. Returns string.

await helper.jwt.issue(secret, payload);

Output:

mysql://user:password@host:port/database

   

GaussBox

Helper method only for GaussBox and some of them uses Sails objects.  

cleanUrl(url)

Parsing and cleaning GaussBox API url's. Returns string.

let url = "v1/user/get?id=2";
helper.gbox.cleanUrl(url);

Output:

v1/user/get

 

getAction(url, service)

Getting action object from list of API actions. Returns JSON.

await helper.gbox.getAction("v1/user/get", "user");

Output:

{
    id: 1,
    actionName: 'Get user details',
    type: 'private',
    routeVersion: 'undefined',
    method: 'GET',
    route: '/v1/user/get/:id'
}

 

activityLog(loggedUser, action, subject = null, parent = null, loginData = null, modificationData = null)

Async function for saving activity log. LoggedUser is user object passed from Master API. Action can be one of ['logged_in', 'created', 'deleted', 'modified', 'moved_to_archive', 'restored_from_archive', 'completed', 'reopened', 'uploaded', 'added_to', 'removed_from', 'added_to_stock', 'removed_from_stock', 'write_off_from_stock']. Subject is GaussBox JSON object with id (number), type (string) and name (string) properties defining subject interacting on. Parent is GaussBox JSON object with id (number), type (string) and name (string) properties defining parent of subject interacting on. LoginData is GaussBox JSON object with some login info data. ModificationData is stringyfied array of JSON objects defining what parameter is changed, old and new value.

[
    {
        "field":"name",
        "oldValue":"oldName",
        "newValue":"newName",
    },
    ...
]

Returns string.

await helper.gbox.activityLog(loggedUser, 'logged_in', null, null, loginData);

Output:

Log created.

 

internalRedirect(apiData, tokenSecret, route, method, data = null)

Async function for internal redirects between API's. apiData is JSON received from master API containing api data like loggedUser info, userSettings etc. tokenSecret is secret for generating internal token. Route is url path to API, aka http://127.0.0.1:1111/v1/user/create. Method is http method for requested URL. Data is optional parameter with request data. Return JSON.

await helper.gbox.internalRedirect('http://127.0.0.1:1111/v1/user/create', 'POST', data);

Output:

User created.

 

compareObjects(dataBaseData, requestData)

Async function for comparing two models. It is possible to compare single models or array of models. This is used for preparing data for creating activity log. Returns JSON object.

await helper.gbox.compareObjects(loggedUser, 'logged_in', null, null, loginData);

Output:

{
    delete: [],
    create: [],
    update: []
}

 

parseApiKey(apiKeyData)

Parsing output data from p_getApiKeyData procedure to get apiKey JSON. Returns JSON object.

helper.gbox.parseApiKey(apiKeyData);

Output:

{
    id: 1,
    name: 'Gauss Test',
    dataSource: 'gbox',
    dataConnection: '',
    apiKey: '******',
    subdomain: 'gausstest',
    licence: {
        id: 1,
        issuedAt: 1529381622000,
        validTo: 1692136800000,
        licenceType: 'user',
        noUsers: 1,
        licenceName: 'Gauss Test',
        licenceModules: [1, 2, 3, 4, 5],
        moduleLimits: [
            {
                "module": 1,
                "limit": null
            },
            {
                "module": 2,
                "limit": 5
            },
            ...
        ],
        isFreemium: false,
        isBlocked: false
    }
}

 

parseCompany(companyData)

Parsing output data from companyApi procedures to get company JSON. Returns JSON object.

helper.gbox.parseCompany(companyData);

Output:

{ company object }

 

parseUser(userData)

Parsing output data from userApi procedures to get user JSON. Returns JSON object.

helper.gbox.parseUser(userData);

Output:

{ user object }

 

validateApiKey(apiKey)

Validating Gauss Box apiKey object. Returns JSON object.

helper.gbox.validateApiKey(apiKey);

Output:

{
    "isValid": false,
    "errorMsg": "Some validate error msg."
}

 

registerEvents(redisConf, apis, eventName, payload, jobOpts, getDetails)

Async function that emit event jobs to provided api's and throws error if occurred. Returns JSON object.

helper.gbox.registerEvents(sails.config.redis, ["testApi"], "test_event", { payload: inputs }, {}, false);

Output:

{
    "api": "testApi",
    "eventName": "test_event",
    "jobDetails": {....}
}

 

fancyQr(text, options)

Generates fancy qr code with background and/or overlay image. Text is text which will be encoded to qrCode. Options is optional, and have this params:

  • size (number) - size of qr code. Auto calculate best size if not set.
  • forceReadability (boolean, default=false) - by default force is under 300px of size, qrCode will look uglier but it will be more readable.
  • image (string) - can be base64, url or path to file.
  • margin (number, default=4) - margin of 4 is 4*scale.
  • background (string, default='#fff') - background of margin. Set to null if you want transparent.
  • version (number) - qr code version. If not set, will be calculated automatically. (https://www.npmjs.com/package/qrcode#qr-code-capacity).
  • regularQr (boolean, default=false) - if image is not set this will be true. If true, returns regular QR canvas.
  • overlay (JSON) - overlay graphic configuration.
  • overlay.image (string) - can be base64, url, path to file or even loaded canvas image.
  • overlay.width (number) - overlay width. If not sent calculated automatically.
  • overlay.height (number) - overlay height. If not sent calculated automatically.
  • overlay.double (number) - doubles default width/height calculation if possible (works only with default w/h option).
  • overlay.opacity (number, default=1) - overlay opacity 0-1.
  • overlay.onTop (boolean, default=true) - if you want to put overlay on top of qrCode image.
  • overlay.position (string) - tl, tm, tr, ml, mm, mr, bl, bm, br (t = top, m = middle, b = bottom)

Methods:

  • toCanvas() Async function which generates canvas. Returns HTMLCanvasElement.
  • toDataUrl(mimeType) Async function which generates dataURL from qrCode canvas. It accepts mimeType parameter, if not provided, default is image/png. It returns base64 string.
  • toBuffer() Async function which generates buffer from qrCode canvas.

Returns JSON object.

const FancyQr = require('gbox-helper').gbox.fancyQr;
let fancyQrCode = new FancyQr('https://www.gaussbox.net', {
      image: 'image path'
    });
let base64QRcode = await fancyQrCode.toDataUrl();

     

Created by

Saša Mihaljenović, Gauss d.o.o.