Skip to content
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
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dist
3 changes: 3 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"singleQuote": true
}
47 changes: 23 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,31 @@ Here's how you can use this library. Begin by installing via NPM:
Here's a small example of usage showing the simplest case, a single string.

```js
const parse = require("json-templates");
const parse = require('json-templates');

const template = parse("{{foo}}");
const template = parse('{{foo}}');

console.log(template.parameters); // Prints [{ key: "foo" }]

console.log(template({ foo: "bar" })); // Prints "bar"
console.log(template({ foo: 'bar' })); // Prints "bar"
```

Parameters can have default values, specified using a colon. These come into play only when the parameter is `undefined`.

```js
const template = parse("{{foo:bar}}");
const template = parse('{{foo:bar}}');

console.log(template.parameters); // Prints [{ key: "foo", defaultValue: "bar" }]

console.log(template()); // Prints "bar", using the default value.

console.log(template({ foo: "baz" })); // Prints "baz", using the given value.
console.log(template({ foo: 'baz' })); // Prints "baz", using the given value.
```

Parameters can come from a nested object.

```js
const template = parse("{{foo.value:baz}}");
const template = parse('{{foo.value:baz}}');

console.log(template.parameters); // Prints [{ key: "foo.value", defaultValue: "baz" }]

Expand All @@ -44,51 +44,51 @@ console.log(template()); // Prints "baz", using the default value.
console.log(template({ foo: { value: 'bar' } })); // Prints "bar", using the given value.

// Example with parameter coming from array
const template = parse({ a: "{{foo.1:baz}}" });
const template = parse({ a: '{{foo.1:baz}}' });

console.log(template.parameters); // Prints [{ key: "foo.1", defaultValue: "baz" }]

console.log(template()); // Prints { a: "baz" }, using the default value.

console.log(template({ foo: ["baq", "bar"] })); // Prints { a: "bar" }, using the given value of array.
console.log(template({ foo: ['baq', 'bar'] })); // Prints { a: "bar" }, using the given value of array.
```

Context values could be objects and arrays.

```js
const template = parse("{{foo:baz}}");
const template = parse('{{foo:baz}}');

console.log(template.parameters); // Prints [{ key: "foo", defaultValue: "baz" }]

console.log(template()); // Prints "baz", using the default value.

console.log(template({ foo: { value: 'bar' } })); // Prints { value: 'bar' } , using the given value.

```

The kind of templating you can see in the above examples gets applied to any string values in complex object structures such as ElasticSearch queries. Here's an example of an ElasticSearch query.

```js
const template = parse({
index: "myindex",
index: 'myindex',
body: {
query: {
match: {
title: "{{myTitle}}"
}
title: '{{myTitle}}',
},
},
facets: {
tags: {
terms: {
field: "tags"
}
}
}
}
field: 'tags',
},
},
},
},
});

console.log(template.parameters); // Prints [{ key: "myTitle" }]

console.log(template({ title: "test" }));
console.log(template({ title: 'test' }));
```

The last line prints the following structure:
Expand All @@ -115,10 +115,9 @@ The last line prints the following structure:

The parse function also handles nested arrays and arbitrary leaf values. For more detailed examples, check out the [tests](https://github.com/curran/json-templates/blob/master/test.js).


## Why?

The use case for this came about while working with ElasticSearch queries that need to be parameterized. We wanted the ability to *specify query templates within JSON*, and also make any of the string values parameterizable. The ideas was to make something kind of like [Handlebars](http://handlebarsjs.com/), but just for the values within the query.
The use case for this came about while working with ElasticSearch queries that need to be parameterized. We wanted the ability to _specify query templates within JSON_, and also make any of the string values parameterizable. The ideas was to make something kind of like [Handlebars](http://handlebarsjs.com/), but just for the values within the query.

We also needed to know which parameters are required to "fill in" a given query template (in order to check if we have the right context parameters to actually execute the query). Related to this requirement, sometimes certain parameters should have default values. These parameters are not strictly required from the context. If not specified, the default value from the template will be used, otherwise the value from the context will be used.

Expand Down Expand Up @@ -148,6 +147,6 @@ Also it was a fun challenge and a great opportunity to write some heady recursiv

## Related Work

* [json-templater](https://www.npmjs.com/package/json-templater)
* [bodybuilder](https://github.com/danpaz/bodybuilder)
* [elasticsearch-query-builder](https://github.com/leonardw/elasticsearch-query-builder)
- [json-templater](https://www.npmjs.com/package/json-templater)
- [bodybuilder](https://github.com/danpaz/bodybuilder)
- [elasticsearch-query-builder](https://github.com/leonardw/elasticsearch-query-builder)
32 changes: 21 additions & 11 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ function Parameter(match) {
if (i !== -1) {
param = {
key: matchValue.substr(0, i),
defaultValue: matchValue.substr(i + 1)
defaultValue: matchValue.substr(i + 1),
};
} else {
param = { key: matchValue };
Expand All @@ -41,7 +41,9 @@ function Parameter(match) {

// Constructs a template function with deduped `parameters` property.
function Template(fn, parameters) {
fn.parameters = Array.from(new Map(parameters.map(parameter => [parameter.key, parameter])).values())
fn.parameters = Array.from(
new Map(parameters.map((parameter) => [parameter.key, parameter])).values()
);
return fn;
}

Expand All @@ -62,7 +64,7 @@ function parse(value) {
case 'array':
return parseArray(value);
default:
return Template(function() {
return Template(function () {
return value;
}, []);
}
Expand All @@ -75,14 +77,14 @@ const parseString = (() => {
// template parameter syntax such as {{foo}} or {{foo:someDefault}}.
const regex = /{{(\w|:|[\s-+.,@/\//()?=*_$])+}}/g;

return str => {
return (str) => {
let parameters = [];
let templateFn = () => str;

const matches = str.match(regex);
if (matches) {
parameters = matches.map(Parameter);
templateFn = context => {
templateFn = (context) => {
context = context || {};
return matches.reduce((result, match, i) => {
const parameter = parameters[i];
Expand All @@ -101,7 +103,11 @@ const parseString = (() => {
}

// Accommodate numbers as values.
if (matches.length === 1 && str.startsWith('{{') && str.endsWith('}}')) {
if (
matches.length === 1 &&
str.startsWith('{{') &&
str.endsWith('}}')
) {
return value;
}

Expand All @@ -116,16 +122,19 @@ const parseString = (() => {

// Parses non-leaf-nodes in the template object that are objects.
function parseObject(object) {
const children = Object.keys(object).map(key => ({
const children = Object.keys(object).map((key) => ({
keyTemplate: parseString(key),
valueTemplate: parse(object[key])
valueTemplate: parse(object[key]),
}));
const templateParameters = children.reduce(
(parameters, child) =>
parameters.concat(child.valueTemplate.parameters, child.keyTemplate.parameters),
parameters.concat(
child.valueTemplate.parameters,
child.keyTemplate.parameters
),
[]
);
const templateFn = context => {
const templateFn = (context) => {
return children.reduce((newObject, child) => {
newObject[child.keyTemplate(context)] = child.valueTemplate(context);
return newObject;
Expand All @@ -142,7 +151,8 @@ function parseArray(array) {
(parameters, template) => parameters.concat(template.parameters),
[]
);
const templateFn = context => templates.map(template => template(context));
const templateFn = (context) =>
templates.map((template) => template(context));

return Template(templateFn, templateParameters);
}
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"build": "rollup -c",
"pretest": "npm run build",
"test": "mocha",
"prettier": "prettier --write .",
"prepublishOnly": "npm test",
"postpublish": "git push && git push --tags"
},
Expand All @@ -26,6 +27,7 @@
"homepage": "https://github.com/datavis-tech/json-templates#readme",
"devDependencies": {
"mocha": "^10.2.0",
"prettier": "^2.8.8",
"rollup": "^3.26.0",
"rollup-plugin-buble": "^0.19.8"
},
Expand Down
8 changes: 3 additions & 5 deletions rollup.config.js → rollup.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ export default {
output: {
format: 'umd',
name: 'jsonTemplates',
file: 'dist/index.js'
file: 'dist/index.js',
},
plugins: [
buble()
]
}
plugins: [buble()],
};
Loading