cypher-tagged-templates
A tiny helper for writing and running Cypher queries using Javascript tagged templates.
Basic example
It supports variables interpolation, automatically using the Neo4j driver to escape values.
The return value of the query is an array of records, after calling the toObject
method on them.
const neo4j = v1const Cypher = default const driver = neo4jconst cypher = driverquery const email = 'anna@example.com'const query = cypher` MATCH (user:User {email: }) RETURN user` const result = query // at some point// driver.close()
Enable automatic integers parsing
You can configure the helper to automatically convert Neo4j integers to native Javascript, avoiding having to deal with that yourself.
// ... const driver = neo4j const cypher = driver parseIntegers: truequery // ...
Override configuration options when running a query
// ...const cypher = driverqueryconst query = cypher` MATCH (user:User {status: "active"}) RETURN user` const result = await query// ...
Nested queries
You can also nest subqueries as variables.
// ...setup const email = 'anna@example.com'const selectDb = cypher`MATCH (neo:Database {name: "Neo4j"})`const selectPerson = cypher`MATCH (anna:Person {email: })`const createFriend = cypher` CREATE (anna) -[:FRIEND]->(:Person:Expert {name:"Amanda"}) -[:WORKED_WITH]->(neo)` const mainQuery = cypher` ` const result = mainQuery
Manual queries
Instead of directly runing the queries, you can export them as a string and a parameters object so you can execute them yourself (E.g. execute multiple queries as part of a transaction).
// ...setup const email = 'anna@example.com'const status = 'active'const findUser = cypher` MATCH (user:User {email: }) WHERE status = RETURN user` const query params = findUser /*query = 'MATCH (user:User {email: {p_0}}) WHERE status = {p_1} RETURN user'params = { p_0: 'anna@example.com', p_1: 'active'}*/
Using with Typescript
An example of using Typescript's generic types
// ... // result is an array of {user: IUser}// ...
API