Allow dynamic values to replace values internally.

If the only thing passed as a value is a dynamic value whatever it
returns will become the new value internally. This means that they are
no longer required to be strings. This also allows plugins to use native
objects and types internally to do more advance things.
This commit is contained in:
David Diaz 2018-04-30 11:34:44 -06:00
parent 92142c148b
commit dd2842c097
3 changed files with 36 additions and 26 deletions

View File

@ -1,24 +1,5 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Beau's plugin system Dynamic Values should look for dynamic values executing and replacing them 1`] = `
Object {
"body": "Hello World",
"request": Object {
"body": undefined,
"endpoint": "http://example.com/hello/3",
"headers": Object {
"count": "3",
"preRequestModifier": true,
},
},
"response": Object {
"body": "Hello World",
"headers": Array [],
"status": 200,
},
}
`;
exports[`Beau's plugin system Request Modifiers should modify the request and response using modifiers. 1`] = `
Object {
"body": "Hello World",

View File

@ -65,21 +65,32 @@ describe(`Beau's plugin system`, () => {
endpoint: 'http://example.com',
alias: 'say-hello',
headers: {
count: '$[add(1, $value2)]'
}
count: '$[add(1, $value2)]',
empty: ''
},
payload: 'counted $[add(1, $value2)] so far.'
},
plugins
);
});
it(`should look for dynamic values executing and replacing them`, async () => {
let cache = new RequestCache();
cache.add('value2', '2');
let cache = new RequestCache();
cache.add('value2', '2');
it(`should look for dynamic values executing and replacing them`, async () => {
let req = await request.exec(cache);
expect(req).toHaveProperty('request.headers.count', '3');
expect(req).toMatchSnapshot();
expect(req).toHaveProperty('request.body', 'counted 3 so far.');
});
it(`should change the internal datatype if the only thing in the value is the dynamic value`, async () => {
let req = await request.exec(cache);
expect(req).toHaveProperty('request.headers.count', 3);
});
it(`should return empty values as empty`, async () => {
let req = await request.exec(cache);
expect(req).toHaveProperty('request.headers.empty', '');
});
it(`should throw when calling an undefined dynamic value`, async () => {

View File

@ -47,7 +47,25 @@ class Plugins {
replaceDynamicValues(obj) {
return replaceInObject(obj, val => {
let valIsEmpty = val.trim().length === 0;
if (valIsEmpty) {
return val;
}
try {
let onlyHasDynamic =
val.replace(dynamicValueRegex, '').trim() === '';
if (onlyHasDynamic) {
let call;
val.replace(dynamicValueRegex, (match, c) => {
call = c;
});
return vm.runInContext(call, this.context);
}
return val.replace(dynamicValueRegex, (match, call) => {
return vm.runInContext(call, this.context);
});