Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: refactor mapping validators #122

Merged
merged 3 commits into from
Oct 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/engine.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { JsonTemplateEngine } from './engine';
import { PathType } from './types';

describe('engine', () => {
describe('isValidJSONPath', () => {
Expand Down Expand Up @@ -66,4 +67,25 @@ describe('engine', () => {
).toThrowError('Invalid mapping');
});
});
describe('isValidMapping', () => {
it('should convert to JSON paths when options are used', () => {
expect(
JsonTemplateEngine.isValidMapping(
{
input: '$.events[1]',
output: 'events[1].name',
},
{ defaultPathType: PathType.JSON },
),
).toBeTruthy();
});
it('should throw error when output is not valid json path without engine options', () => {
expect(
JsonTemplateEngine.isValidMapping({
input: '$.events[2]',
output: 'events[2].name',
}),
).toBeFalsy();
});
});
});
66 changes: 56 additions & 10 deletions src/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,20 +59,57 @@
}
}

private static prepareMappings(mappings: FlatMappingPaths[]): FlatMappingPaths[] {
return mappings.map((mapping) => ({
private static toJsonPath(input: string): string {
if (input.startsWith('$')) {
return input;
}

// Check if it's wrapped in quotes
// or is a simple identifier
// or contains dots
if (
/^'.*'$/.test(input) ||
/^".*"$/.test(input) ||
/^\w+$/.test(input) ||
input.includes('.')
) {
return `$.${input}`;
}

// If input contains special characters
return `$.'${input}'`;
}

Check warning on line 81 in src/engine.ts

View check run for this annotation

Codecov / codecov/patch

src/engine.ts#L79-L81

Added lines #L79 - L81 were not covered by tests
koladilip marked this conversation as resolved.
Show resolved Hide resolved
koladilip marked this conversation as resolved.
Show resolved Hide resolved

private static convertToJSONPath(path?: string, options?: EngineOptions): string | undefined {
if (!path) {
return path;

Check warning on line 85 in src/engine.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement
}

Check warning on line 86 in src/engine.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement

Check warning on line 86 in src/engine.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🌿 Branch is not covered

Warning! Not covered branch

Check warning on line 86 in src/engine.ts

View check run for this annotation

Codecov / codecov/patch

src/engine.ts#L85-L86

Added lines #L85 - L86 were not covered by tests
if (options?.defaultPathType === PathType.JSON) {
return JsonTemplateEngine.toJsonPath(path);
}
return path;
}

private static prepareMapping(mapping: FlatMappingPaths, options?: EngineOptions) {
return {
...mapping,
input: mapping.input ?? mapping.from,
output: mapping.output ?? mapping.to,
}));
output: JsonTemplateEngine.convertToJSONPath(mapping.output ?? mapping.to, options),

Check warning on line 97 in src/engine.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🌿 Branch is not covered

Warning! Not covered branch
};
}

private static prepareMappings(
mappings: FlatMappingPaths[],
options?: EngineOptions,
): FlatMappingPaths[] {
return mappings
.map((mapping) => JsonTemplateEngine.prepareMapping(mapping, options))
.filter((mapping) => mapping.input && mapping.output);
}

static validateMappings(mappings: FlatMappingPaths[], options?: EngineOptions) {
JsonTemplateEngine.prepareMappings(mappings).forEach((mapping) => {
if (
!JsonTemplateEngine.isValidJSONPath(mapping.input) ||
!JsonTemplateEngine.isValidJSONPath(mapping.output)
) {
JsonTemplateEngine.prepareMappings(mappings, options).forEach((mapping) => {
if (!JsonTemplateEngine.isValidJSONPath(mapping.output)) {
throw new JsonTemplateMappingError(
'Invalid mapping: invalid JSON path',
mapping.input as string,
Expand All @@ -83,12 +120,21 @@
JsonTemplateEngine.parseMappingPaths(mappings, options);
}

static isValidMapping(mapping: FlatMappingPaths, options?: EngineOptions) {
try {
JsonTemplateEngine.validateMappings([mapping], options);
return true;
} catch (e) {
return false;
}
}
koladilip marked this conversation as resolved.
Show resolved Hide resolved
koladilip marked this conversation as resolved.
Show resolved Hide resolved

private static createFlatMappingsAST(
mappings: FlatMappingPaths[],
options?: EngineOptions,
): FlatMappingAST[] {
const newOptions = { ...options, mappings: true };
return JsonTemplateEngine.prepareMappings(mappings)
return JsonTemplateEngine.prepareMappings(mappings, options)
.filter((mapping) => mapping.input && mapping.output)
.map((mapping) => ({
...mapping,
Expand Down
6 changes: 3 additions & 3 deletions src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,11 @@ type PathTypeResult = {
};

export class JsonTemplateParser {
private lexer: JsonTemplateLexer;
private readonly lexer: JsonTemplateLexer;

private options?: EngineOptions;
private readonly options?: EngineOptions;

private pathTypesStack: PathTypeResult[] = [];
private readonly pathTypesStack: PathTypeResult[] = [];

// indicates currently how many loops being parsed
private loopCount = 0;
Expand Down
2 changes: 1 addition & 1 deletion src/reverse_translator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ import { BINDINGS_PARAM_KEY, DATA_PARAM_KEY, EMPTY_EXPR, INDENTATION_SPACES } fr
import { escapeStr } from './utils';

export class JsonTemplateReverseTranslator {
private options?: EngineOptions;
private readonly options?: EngineOptions;

private level = 0;

Expand Down
14 changes: 14 additions & 0 deletions src/utils/converter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { SyntaxType } from '../types';
import { convertToObjectMapping } from './converter';

describe('Converter:', () => {
describe('convertToObjectMapping', () => {
it('should validate mappings', () => {
expect(() =>
convertToObjectMapping([
{ inputExpr: { type: SyntaxType.EMPTY }, outputExpr: { type: SyntaxType.EMPTY } },
] as any),
).toThrowError(/Invalid mapping/);
});
koladilip marked this conversation as resolved.
Show resolved Hide resolved
});
});
14 changes: 10 additions & 4 deletions test/scenarios/mappings/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,10 +214,6 @@ export const data: Scenario[] = [
mappingsPath: 'invalid_object_mappings.json',
error: 'Invalid mapping',
},
{
mappingsPath: 'invalid_output_mapping.json',
error: 'Invalid mapping',
},
{
mappingsPath: 'mappings_with_root_fields.json',
input,
Expand Down Expand Up @@ -293,6 +289,16 @@ export const data: Scenario[] = [
],
},
},
{
mappingsPath: 'non_path_output.json',
output: {
'Content-Type': 'application/json',
'a.b.c': 3,
bar: 1,
c: { 'Content-Type': 'text/plain' },
'x-bar': 2,
},
},
{
mappingsPath: 'object_mappings.json',
input: {
Expand Down
7 changes: 0 additions & 7 deletions test/scenarios/mappings/invalid_output_mapping.json

This file was deleted.

26 changes: 26 additions & 0 deletions test/scenarios/mappings/non_path_output.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
[
{
"input": "'application/json'",
"output": "Content-Type"
},
{
"input": "1",
"output": "bar"
},
{
"input": "2",
"output": "x-bar"
},
{
"input": "2",
"description": "This mapping will be ignored because the output is not defined"
},
{
"input": "3",
"output": "'a.b.c'"
},
{
"input": "'text/plain'",
"output": "c.'Content-Type'"
}
]
Loading