1.3.47 • Published 4 years ago

gbox-helper v1.3.47

Weekly downloads
233
License
******
Repository
-
Last release
4 years ago

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.

1.3.47

4 years ago

1.3.46

4 years ago

1.3.45

4 years ago

1.3.44

5 years ago

1.3.43

5 years ago

1.3.42

5 years ago

1.3.41

5 years ago

1.3.40

5 years ago

1.3.39

5 years ago

1.3.38

5 years ago

1.3.37

5 years ago

1.3.36

5 years ago

1.3.35

5 years ago

1.3.34

5 years ago

1.3.33

5 years ago

1.3.31

5 years ago

1.3.30

5 years ago

1.3.29

5 years ago

1.3.28

5 years ago

1.3.27

5 years ago

1.3.26

5 years ago

1.3.25

5 years ago

1.3.24

5 years ago

1.3.23

5 years ago

1.3.22

5 years ago

1.3.21

5 years ago

1.3.20

5 years ago

1.3.19

5 years ago

1.3.18

5 years ago

1.3.17

5 years ago

1.3.16

5 years ago

1.3.15

5 years ago

1.3.14

5 years ago

1.3.13

5 years ago

1.3.12

5 years ago

1.3.11

5 years ago

1.3.10

5 years ago

1.3.9

5 years ago

1.3.8

6 years ago

1.3.7

6 years ago

1.3.6

6 years ago

1.3.5

6 years ago

1.3.4

6 years ago

1.3.3

6 years ago

1.3.2

6 years ago

1.3.1

6 years ago

1.3.0

6 years ago

1.2.9

6 years ago

1.2.8

6 years ago

1.2.7

6 years ago

1.2.6

6 years ago

1.2.5

6 years ago

1.2.4

6 years ago

1.2.3

6 years ago

1.2.2

6 years ago

1.2.0

6 years ago

1.1.9

6 years ago

1.1.8

6 years ago

1.1.7

6 years ago

1.1.6

6 years ago

1.1.5

6 years ago

1.1.4

6 years ago

1.1.3

6 years ago

1.1.2

6 years ago

1.1.0

6 years ago

1.0.6

6 years ago

1.0.5

6 years ago

1.0.4

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago