1.0.7 • Published 4 years ago

node-hotech v1.0.7

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 node-hotech

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.

/**
 * 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: this.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
/**
 * Working environment
 * @type {*}
 */
const model = this.envProperties();

/**
 * This function login to orest and returns access_token value.
 * @returns {Promise<void>}
 */
module.exports.getToken = async () => {
    /**
     * The person model to login to orest
     * @type {string}
     */
    const modelUser = `username=${model.user.email}&password=${model.user.password}&grant_type=${model.field.type}&client_id=${model.field.clientId}`;
    return new Promise(resolve => {
        const xhr = new XMLHttpRequest();
        xhr.open(model.header.post, model.path.url + model.entity.auth, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onload = () => {
            const response = JSON.parse(xhr.responseText);
            if (xhr.status === 200) {
                model.header.token = response.access_token;
                this.logger.info({
                    filename: this.relativeFilePath(__dirname, __filename),
                    message: `Method: ${model.header.post} Status: ${xhr.status} Token: ${model.header.token} for ${model.path.url}`
                });
                return resolve(model.header.token);
            }
            return this.logger.error({
                filename: this.relativeFilePath(__dirname, __filename),
                message: `Method: ${model.header.post} Status: ${xhr.status} Error: ${xhr.responseText} for ${model.path.url}`
            });
        };
        xhr.onerror = () => {
            return this.logger.error({
                filename: this.relativeFilePath(__dirname, __filename),
                message: `Method: ${model.header.post} Status: ${xhr.status} Error: ${xhr.responseText} for ${model.path.url}`
            });
        };
        xhr.send(modelUser);
    });
};

Generic Request Function

This function is a general request function according to the url method and data information given in the object.

Example

The important things

  • method = request type get/post etc
  • url = which url will be requested
  • data = data content for url to send
/**
 * Generic request function
 * @param object = {
 *     method: request type,
 *     url: url to send request,
 *     data: data content for url to send request
 * }
 * @returns {Promise<void>}
 */
module.exports.genericRequest = async (object) => {
    return new Promise(resolve => {
        const xhr = new XMLHttpRequest();
        xhr.open(object.method, object.url, true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.setRequestHeader("Authorization", `Bearer ${model.header.token}`);
        xhr.onload = () => {
            if (xhr.status === 200) {
                this.logger.info({
                    filename: this.relativeFilePath(__dirname, __filename),
                    message: `Method: ${object.method} Status: ${xhr.status} Error: ${xhr.responseText} for ${object.url}`
                });
                return resolve(JSON.parse(xhr.responseText));
            }
            return this.logger.error({
                filename: this.relativeFilePath(__dirname, __filename),
                message: `Method: ${object.method} Status: ${xhr.status} Error: ${xhr.responseText} for ${object.url}`
            });
        };
        xhr.onerror = () => {
           return this.logger.error({
                filename: this.relativeFilePath(__dirname, __filename),
                message: `Method: ${object.method} Status: ${xhr.status} Error: ${xhr.responseText} for ${object.url}`
            });
        };
        xhr.send(object.data);
    });
};

Logging

The winston library is selected for logging.

Example
/**
 * 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

NODE_ENV = real/dev in the .env file you will create in the project.

Example
NODE_ENV=real
/**
 * * 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);
};

Example Usage

note: CommonJS usage

  • In order to gain the TypeScript typings while using CommonJS imports with require() use the following approach:
const hotech = require("node-hotech");
hotech.envProperties();
Response
{
  "path": { "url": "url" },
  "entity": { "auth": "auth" },
  "user": { "email": "email", "password": "password" },
  "header": { "token": "token", "post": "post", "get": "get" }
}
Author: @asince
1.0.7

4 years ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.2

4 years ago

1.0.3

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago