dino-express
Version:
DinO enabled REST framework based on express
178 lines • 6.1 kB
JavaScript
;
// Copyright 2018 Quirino Brizi [quirino.brizi@gmail.com]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Helper = void 0;
const dino_core_1 = require("dino-core");
const zlib_1 = require("zlib");
/**
* @private
*/
const base64RegExp = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
/**
* Helper class exposes utility methods
* @public
*/
class Helper {
/**
* Normalize swagger path definition to express notation
* @param {String} path the API path
*
* @public
* @static
*/
static normalizePath(path) {
let answer = path;
if (/.*{.*}.*/.test(path)) {
answer = path.replace(/{/g, ':').replace(/}/g, '');
}
return answer;
}
/**
* Allows to retrieve a variable from the configuration or as environment variable, supports
* both `:` and `_` notation.
* @param {Environment} environment the configuration container
* @param {string} key the key for the variable to retrieve
* @param {any} _default the default value if the variable is nt defined.
*/
static getVariable(environment, key, _default) {
const envVarKey = key.replace(/:/g, '_');
return environment.get(key) || environment.get(envVarKey) || environment.get(envVarKey.toUpperCase()) || _default;
}
/**
* Ensure that either the value or default value are returned.
* @param {any} value the value to verify
* @param {any} the default value to return
*/
static ensureValue(value, _default) {
if (typeof value === 'boolean') {
return value;
}
return value || _default;
}
static requestHasBody(req) {
if (dino_core_1.ObjectHelper.isNotDefined(req?.method)) {
return false;
}
return Helper.isPayloadBeringMethod(req.method);
}
static isPayloadBeringMethod(method) {
if (method === undefined) {
return false;
}
return ['post', 'put', 'patch'].includes(method.toLowerCase());
}
/**
* Format the response based on the content type defined
* @returns {String}
*/
static format(payload, contentType) {
if (['application/xml', 'text/xml'].some((type) => type == contentType)) {
return require('xml')(payload);
}
return payload;
}
static isAPromise(obj) {
return (!!obj && obj instanceof Promise) || ((typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function');
}
/**
* Evaluate if an obj is an instance of a type
*
* @param {Any} obj the object to be verified
* @param {Any} type the type the object will be verified against
* @returns {Boolean} true if obj is instance of type, false otherwise
*/
static instanceOf(obj, type) {
// eslint-disable-next-line no-prototype-builtins
return (type.isPrototypeOf(obj) ||
obj instanceof type ||
// eslint-disable-next-line no-prototype-builtins
(obj.hasOwnProperty('prototype') && obj.prototype instanceof type) ||
// eslint-disable-next-line no-prototype-builtins
obj.isPrototypeOf(type));
}
/**
* Tests if the provided string is base64
* @param {string} v the string to test for base64
* @returns true if the provided string is base64 encoded, false otherwise
* @public
* @static
*/
static isBase64(v) {
if (typeof v === 'string') {
if (v.trim().length === 0 || v.length % 4 !== 0) {
return false;
}
return base64RegExp.test(v);
}
return false;
}
/**
* Decode a base64 string, decompress and parse from JSON if needed.
*
* @param {string} str a string to decode if base64 encoded
* @returns the decoded string or the string as is
* @public
* @static
*/
static decodeFromBase64AndParse(str) {
if (Helper.isBase64(str)) {
const decodedString = Helper.decompress(Buffer.from(str, 'base64'));
try {
return JSON.parse(decodedString);
}
catch (e) {
return decodedString;
}
}
else {
return str;
}
}
/**
* Normalise the response body from the received error
* @param {any} response the response for the client
* @returns the body response
*
* @private
*/
static buildResponseBody(response, asString, asBase64) {
const body = response.body;
if (asBase64) {
return Buffer.from(JSON.stringify(body || {}), 'utf-8').toString('base64');
}
return asString ? JSON.stringify(body || {}) : body || {};
}
/**
* Decompress using zlib the provided content, if the content is not compressed or
* cannot be decompressed it will be returned as is.
*
* @param input the content to decompress
* @returns the decompressed content
*/
static decompress(input) {
try {
return (0, zlib_1.inflateSync)(input).toString();
}
catch (error) {
if (error.errno === -3) {
// "incorrect header check", the input is not compressed
return input.toString();
}
throw error;
}
}
}
exports.Helper = Helper;
//# sourceMappingURL=Helper.js.map