1.0.2 • Published 4 years ago

htch-ms v1.0.2

Weekly downloads
-
License
ISC
Repository
-
Last release
4 years ago

Hotech Microservice Node.js Package

Generic structure created for Hotech microservice Node.js side.

Contents

Getting Started

Installation

This library is distributed on npm. In order to add it as a dependency, run the following command:

$ npm install htch-ms

Google APIs JWT

JSON Web Tokens

Provides support for creating (encoding) and verifying (decoding) JWTs, especially JWTs generated and consumed by Google infrastructure.

See for more details on JWTs.

Example

Generic simple function for Google APIs JWT authentication.

const {google} = require("googleapis");
const {logger} = require("../logging");
const {relativeFilePath} = require("../config");

/**
 * Jwt authentication for use the google api.
 * @param client = The client_email value in the service account json file you will use.
 * @param key = The private_key value in the service account json file you will use.
 * @param scope = Scope for google api you will use Eg. https://www.googleapis.com/auth/cloud-platform
 * @param user = If a user is required for the scope you will use
 * @returns {JWT}
 */
module.exports.jwtAccess = (client, key, scope, user) => {
    const jwtAccess = new google.auth.JWT(
        client,
        null,
        key,
        scope,
        user
    );
    jwtAccess.authorize(error => {
        if (error) {
            return logger.error({
                path: relativeFilePath(__dirname, __filename),
                message: error
            });
        }
    });
    return jwtAccess;
};

Orest Authentication

Getting access_token for authentication from orest side.

{
    "access_token": "b6c94cfb-9acb-4654-8149-9517810df105",
    "token_type": "bearer",
    "refresh_token": "f27e6ea6-a365-440d-a2aa-d9fd1daa1cdc",
    "expires_in": 8269,
    "scope": "read write"
}

Example

Two things are very important here.

  • Working environment (dev / real)

  • Model user information

const {envProperties, relativeFilePath} = require("../config");
const axios = require('axios');
const {logger} = require("../logging");

/**
 * Working environment => ./src/properties/(dev/real)
 * @type {*}
 */
const config = envProperties();
/**
 * The person model to login to orest
 * @type {string}
 */
const modelUser = `username=${config.user.email}&password=${config.user.password}&grant_type=${config.field.type}&client_id=${config.field.clientId}`;

/**
 * This function login to orest and returns access_token value.
 * @returns {Promise<void>}
 */
module.exports.getToken = async () => {
    try {
        let response = await axios({
            method: config.header.post,
            url: config.path.url,
            header: config.header.form,
            data: modelUser
        });
        if (response.status === 200) {
            logger.info({
                filename: relativeFilePath(__dirname, __filename),
                message: `Token: ${response.data.access_token}`
            });
            config.header.token = response.data.access_token;
            return config.header.token;
        }
    } catch (error) {
        logger.error({
            filename: relativeFilePath(__dirname, __filename),
            message: error
        });
    }
};

Logging

The winston library is selected for logging.

Example

const {createLogger, format, transports} = require("winston");

/**
 * The function we will use for logging.
 * level key value has to be debug cause of debug displays all logs (info, warn, error etc).
 * @type {winston.Logger}
 */
module.exports.logger = createLogger({
    level: 'debug',
    format: format.combine(
        format.colorize(),
        format.timestamp(),
        format.printf(msg => `${msg.timestamp} ${msg.level} ${msg.filename} -> ${msg.message}`)
    ),
    transports: [new transports.Console()]
});

Generic Environment Properties

What to do

  • NODE_ENV = (real/dev) in the .env file you will create in the project.
  • Let us examine the reason we do this.

Example

This file goes to the dev or real properties file according to the NODE_ENV variable in the .env file.

const {config} = require("dotenv");
/**
 * * What environment will the properties work for (real-dev).
 * It is directed to the related properties file according to the environment it will work in.
 * @returns {*}
 */
module.exports.envProperties = () => {
    return require(`../../src/properties/${config().parsed.NODE_ENV}`);
};

/**
 * Returns the relative path of the running file. Eg. src/index.js
 * @param folder = Gives absolute path for the folder where the running file is located.
 * @param file = Gives absolute path the running file is located.
 * @returns {String}
 */
module.exports.relativeFilePath = (folder, file) => {
    return folder.split('/').pop() + file.slice(folder.length);
};
1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago