bruno/packages/bruno-js/src/bru.js

106 lines
2.4 KiB
JavaScript
Raw Normal View History

const { cloneDeep } = require('lodash');
const { interpolate } = require('@usebruno/common');
2023-12-01 20:57:18 +01:00
const variableNameRegex = /^[\w-.]*$/;
2023-01-26 22:54:21 +01:00
class Bru {
constructor(envVariables, runtimeVariables, processEnvVars, collectionPath, requestVariables) {
this.envVariables = envVariables || {};
this.runtimeVariables = runtimeVariables || {};
this.processEnvVars = cloneDeep(processEnvVars || {});
this.requestVariables = requestVariables || {};
this.collectionPath = collectionPath;
2023-09-06 17:06:55 +02:00
}
_interpolate = (str) => {
if (!str || !str.length || typeof str !== 'string') {
return str;
}
const combinedVars = {
...this.envVariables,
...this.requestVariables,
...this.runtimeVariables,
process: {
env: {
...this.processEnvVars
}
}
};
return interpolate(str, combinedVars);
};
cwd() {
return this.collectionPath;
}
2023-09-06 17:06:55 +02:00
getEnvName() {
return this.envVariables.__name__;
2023-01-26 22:54:21 +01:00
}
getProcessEnv(key) {
return this.processEnvVars[key];
}
hasEnvVar(key) {
return Object.hasOwn(this.envVariables, key);
}
2023-01-29 00:19:31 +01:00
getEnvVar(key) {
return this._interpolate(this.envVariables[key]);
2023-01-29 00:19:31 +01:00
}
setEnvVar(key, value) {
if (!key) {
throw new Error('Creating a env variable without specifying a name is not allowed.');
2023-01-29 00:19:31 +01:00
}
2023-09-06 17:06:55 +02:00
this.envVariables[key] = value;
2023-01-26 22:54:21 +01:00
}
2023-02-01 13:26:13 +01:00
hasVar(key) {
return Object.hasOwn(this.runtimeVariables, key);
}
2023-02-01 13:26:13 +01:00
setVar(key, value) {
if (!key) {
throw new Error('Creating a variable without specifying a name is not allowed.');
2023-02-01 13:26:13 +01:00
}
2023-12-01 20:57:18 +01:00
if (variableNameRegex.test(key) === false) {
throw new Error(
`Variable name: "${key}" contains invalid characters!` +
2023-12-01 20:57:18 +01:00
' Names must only contain alpha-numeric characters, "-", "_", "."'
);
}
this.runtimeVariables[key] = value;
2023-02-01 13:26:13 +01:00
}
getVar(key) {
2023-12-01 20:57:18 +01:00
if (variableNameRegex.test(key) === false) {
throw new Error(
`Variable name: "${key}" contains invalid characters!` +
2023-12-01 20:57:18 +01:00
' Names must only contain alpha-numeric characters, "-", "_", "."'
);
}
return this._interpolate(this.runtimeVariables[key]);
2023-02-01 13:26:13 +01:00
}
2023-10-16 13:28:58 +02:00
deleteVar(key) {
delete this.runtimeVariables[key];
}
getRequestVar(key) {
return this._interpolate(this.requestVariables[key]);
}
2023-10-16 13:28:58 +02:00
setNextRequest(nextRequest) {
this.nextRequest = nextRequest;
}
2023-01-26 22:54:21 +01:00
}
module.exports = Bru;