0

I want to pass an n-number of cypher-queries to a neo4j-transaction and I am thinking about a good approach.

At the moment I have a working approach that takes the array-item or if it is not available a dummy-query. (Code below)

I believe this is not best-practice. Does anybody know or have an idea how this can be done better?

    function Neo4jTransaction(QueryArray) {
        const session = driverWrite.session();
        const tx = session.beginTransaction();
        tx.run(QueryArray[0] || "RETURN 0")
        tx.run(QueryArray[1] || "RETURN 0")
        tx.run(QueryArray[2] || "RETURN 0")
        tx.run(QueryArray[3] || "RETURN 0")
        .then(result => {
            return tx.commit()
        }).then(() => {
            session.close()
            driverWrite.close()
        }).catch(exception => {
            console.log(exception)
            session.close()
            driverWrite.close()
        })
    }
Peter
  • 323
  • 4
  • 15

1 Answers1

0

First, if you have an array, you might want to iterate over it. Second, tx.run() returns a Promise that you need to catch if it fails. In your code, it is called 4 times in a row, but only the last one waits for the result and catches the error. I looks like some lines of the code are missing.

neo4j-driver documentation gives a good example on explicit transactions: https://github.com/neo4j/neo4j-javascript-driver#explicit-transactions

The queries are executed sequentially. If one fails the whole transaction will be rolled back.

async function neo4jTransaction(queryArray) {

  const session = driver.session();

  const txc = session.beginTransaction();

  try {

    for (const query of queryArray) {
      await txc.run(query || 'RETURN 0');
    }

    await txc.commit();

  } catch (e) {

    await txc.rollback();
    return Promise.reject(e);

  } finally {

    await session.close();

  }

}
Brakebein
  • 2,197
  • 1
  • 16
  • 21