Skip to content

Commit dbb89d2

Browse files
committed
feat(sdk): dynamic-context-validation
1 parent da331f7 commit dbb89d2

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

kleros-sdk/src/dataMappings/utils/replacePlaceholdersWithValues.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import mustache from "mustache";
2+
import retrieveVariables from "./retrieveVariables";
23

34
export const replacePlaceholdersWithValues = (mapping: any, context: Record<string, unknown>) => {
45
const replace = (obj) => {
56
if (typeof obj === "string") {
7+
validateContext(obj, context);
68
return mustache.render(obj, context);
79
} else if (Array.isArray(obj)) {
810
return obj.map(replace);
@@ -15,3 +17,18 @@ export const replacePlaceholdersWithValues = (mapping: any, context: Record<stri
1517

1618
return replace(mapping);
1719
};
20+
21+
/**
22+
*
23+
* @param template
24+
* @param context
25+
* @description retrieves all variables from a template and validates if they are provided in the context
26+
*/
27+
const validateContext = (template: string, context: Record<string, unknown>) => {
28+
const variables = retrieveVariables(template);
29+
30+
variables.forEach((variable) => {
31+
if (!context[variable]) throw new Error(`Expected key : "${variable}" to be provided in context.`);
32+
});
33+
return true;
34+
};
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import mustache from "mustache";
2+
3+
/**
4+
*
5+
* @param template
6+
* @returns Variables[] returns the variables in a template string
7+
* @note This is a naive implementation and wil not work for complex tags, only works for {{}} and {{{}}} tags for now.
8+
* Reference : https://github.com/janl/mustache.js/issues/538
9+
*/
10+
const retrieveVariables = (template: string) =>
11+
mustache
12+
.parse(template)
13+
.filter(function (v) {
14+
return v[0] === "name" || v[0] === "&";
15+
}) // add more conditions here to include more tags
16+
.map(function (v) {
17+
return v[1];
18+
});
19+
20+
export default retrieveVariables;

0 commit comments

Comments
 (0)