sunjith / loopback-connector-neo4j-graph

MIT License
7 stars 2 forks source link

How to use options.tx #2

Closed mingjinc closed 7 years ago

mingjinc commented 7 years ago

Hi, For multiple cypher operation, how to use options.tx for it?

sunjith commented 7 years ago

Hi Ming! Thank you for writing in. Didn't fully test transactions as we didn't have that use case. You should be able use it by calling the startTransaction to return a tx reference, and use the tx, commit and/or rollback options in further calls to cypher to process the full transaction.

Like:

var tx = ModelClass.dataSource.connector.startTransaction();
var cypher = {
    query: "MATCH (u:User {email: {email}}) RETURN u",
    params: {
        email: 'alice@example.com',
    }
};
var options = {tx: tx};
var callback = function (err, results) {
    if (err) {
        throw err;
    }
    var result = results[0];
    if (!result) {
        console.log('No user found.');
    } else {
        var user = result['u'];
        console.log(JSON.stringify(user, null, 4));
    }
};

ModelClass.dataSource.connector.execute(
    cypher,
    [],
    options,
    callback
); // call with different cypher queries to add them to the transaction

 // EITHER commit the transaction
options.commit = true;
ModelClass.dataSource.connector.execute(
    cypher, // final query
    [],
    options,
    callback
); 

// OR rollback the transaction
options.rollback = true;
ModelClass.dataSource.connector.execute(
    {}, // no query for rollback
    [],
    options,
    callback
);

Please revert if you encounter any issue. If you have any patches to fix them, those are most welcome. Just send a pull request.

Also let me know how it goes. If all works well, I shall update the README with the example so that others may also find it useful.