Skip to content

Commit

Permalink
fix: support generating values with faker.js in scripting
Browse files Browse the repository at this point in the history
  • Loading branch information
ihexxa committed May 27, 2024
1 parent 967ac06 commit 217566a
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
24 changes: 24 additions & 0 deletions packages/insomnia-sdk/src/objects/__tests__/environments.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { describe, expect, it } from '@jest/globals';
import { validate } from 'uuid';

import { Environment, Variables } from '../environments';

describe('test Variables object', () => {
it('test basic operations', () => {
const variables = new Variables({
globals: new Environment('globals', { value: '777' }),
environment: new Environment('environments', {}),
collection: new Environment('baseEnvironment', {}),
data: new Environment('iterationData', {}),
});

const uuidAnd777 = variables.replaceIn('{{ $randomUUID }}{{value }}');
expect(validate(uuidAnd777.replace('777', ''))).toBeTruthy();

const uuidAndBrackets1 = variables.replaceIn('{{ $randomUUID }}}}');
expect(validate(uuidAndBrackets1.replace('}}', ''))).toBeTruthy();

const uuidAndBrackets2 = variables.replaceIn('}}{{ $randomUUID }}');
expect(validate(uuidAndBrackets2.replace('}}', ''))).toBeTruthy();
});
});
38 changes: 37 additions & 1 deletion packages/insomnia-sdk/src/objects/interpolator.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { fakerFunctions } from 'insomnia/src/ui/components/templating/faker-functions';
import { configure, type ConfigureOptions, type Environment as NunjuncksEnv } from 'nunjucks';

class Intepolator {
Expand All @@ -10,7 +11,42 @@ class Intepolator {
render = (template: string, context: object) => {
// TODO: handle timeout
// TODO: support plugin?
return this.engine.renderString(template, context);
return this.engine.renderString(
this.renderWithFaker(template),
context
);
};

renderWithFaker = (template: string) => {
const segments = template.split('}}');
if (segments.length === 1) {
return template;
}

const translatedSegments = segments.map(segment => {
const tagStart = segment.lastIndexOf('{{');
if ((tagStart) < 0) {
return segment;
}

const tagName = segment
.slice(tagStart + 2)
.trim();
if (!tagName.startsWith('$')) {
// it is a tag probably for interpolating, at least not for generating
return segment + '}}';
}
const funcName = tagName.slice(1) as keyof typeof fakerFunctions; // remove prefix '$'

if (!fakerFunctions[funcName]) {
throw Error(`replaceIn: no faker function is found: ${funcName}`);
};

const generated = fakerFunctions[funcName]();
return segment.slice(0, tagStart) + generated;
});

return translatedSegments.join('');
};
}

Expand Down

0 comments on commit 217566a

Please sign in to comment.