jbmusso / gremlin-javascript

JavaScript tools for graph processing in Node.js and the browser inspired by the Apache TinkerPop API
MIT License
214 stars 63 forks source link

Building queries with makeTemplateTag #77

Closed danvoyce closed 7 years ago

danvoyce commented 7 years ago

I want to build up a query from several items depending in an array, so I am doing this:

const queries = items.reduce((carry, value) => {
    return carry + `__.has('title', '${value}'),`;
  }, '');

and then running

gremlinTemplate`g.V().or(${queries}).path()`;

But this throws an error. I guess it has something to do with the Tagged template literals syntax which I've not used before.

I've tried this with just one item, and therefor no comma at the end of the reduced string, so thats not the issue.

Any thoughts?

jbmusso commented 7 years ago

Could you please post the error?

TLDR: template strings can be used to dynamically escape parameters but cannot be used to dynamically generate strings of Gremlin.

In the context of gremlin-javascript, the purpose of tagged template literals is to dynamically escape interpolated values as parameters sent to Gremlin server along with the script. The benefit of this is to avoid Gremlin/SQL-like injection as well as improve performance (see below). If I understand your code snippet well, you're asking to escape chunks of Gremlin has parameters rather than values (ie. primitives, arrays of objects), which will not work.

Also, I'd advise against trying to dynamically generate Gremlin script because this which will hurt the performance badly (Gremlin Server will have to compile a new script every time, which is an expensive operation). It's best to pass parameters along with your script. See also: http://tinkerpop.apache.org/docs/3.2.4/reference/#parameterized-scripts