zcatalyst-integ-cliq
Version:
Node.js SDK for integrating Zoho Catalyst with Zoho Cliq
93 lines (92 loc) • 3.19 kB
JavaScript
import { existsSync, readFile, readFileSync } from 'fs';
import { dirname, join, normalize } from 'path';
import { promisify } from 'util';
import { CatalystError } from './error.js';
import CONSTANTS from './constants.js';
import { homedir } from 'os';
import { fileURLToPath, parse } from 'url';
import { apiRequest } from './cliq-api/api-util.js';
export const readAsync = promisify(readFile);
export async function readConfig(path) {
const functionRoot = getFunctionRoot();
const configFilePath = join(functionRoot, path);
if (!existsSync(configFilePath)) {
throw new CatalystError('Config file does not exist in the path: ' + configFilePath);
}
return readAsync(normalize(configFilePath), { encoding: 'utf-8' });
}
export function readConfigSync(path) {
const functionRoot = getFunctionRoot();
const configFilePath = join(functionRoot, path);
if (!existsSync(configFilePath)) {
throw new CatalystError('Config file does not exist in the path: ' + configFilePath);
}
return readFileSync(normalize(configFilePath), { encoding: 'utf-8' });
}
export function isEmpty(obj) {
if (obj === undefined ||
obj === null ||
Object.keys(obj).length === 0 ||
(typeof obj === 'string' && obj === '') ||
obj.length === 0) {
return true;
}
return false;
}
export function getFunctionRoot() {
if (process.env.functionRoot) {
return process.env.ZC_FUNCTION_ROOT;
}
const homeDir = join(homedir(), './');
const fnRoot = findFunctionRoot(homeDir, dirname(fileURLToPath(import.meta.url)));
if (fnRoot === undefined) {
throw new CatalystError('Unable to get the function root');
}
process.env.ZC_FUNCTION_ROOT = fnRoot;
return fnRoot;
}
function findFunctionRoot(userHome, path) {
if (existsSync(join(path, CONSTANTS.CONFIGJSON))) {
return path;
}
if (normalize(path) === userHome) {
return;
}
return findFunctionRoot(userHome, join(path, '../'));
}
/**
* Override a value with supplied environment variable if present.
*
* @param {string} envname The env key name.
* @param {string} value The value to use if key is not present.
* @param {Function} coerce Function to do manipulation of env value and given value.
* @return {any} Either the env value or the given value according the presence.
*/
export function envOverride(envname, value, coerce) {
if (process.env[envname]?.length) {
if (coerce !== undefined) {
try {
return coerce(process.env[envname], value);
}
catch (e) {
return value;
}
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return process.env[envname];
}
return value;
}
export async function sendRequest(url, requestMethod, responseBody) {
const parsed = parse(url);
const options = {
hostname: parsed.hostname,
port: parsed.port,
path: parsed.path,
method: requestMethod,
headers: {
['User-Agent']: CONSTANTS.USER_AGENT
}
};
return apiRequest(options, responseBody);
}