Skip to content

Instantly share code, notes, and snippets.

@walshie4
Created July 20, 2018 01:14
Show Gist options
  • Save walshie4/d340f7f91cf396326933af5a7b835fa6 to your computer and use it in GitHub Desktop.
Save walshie4/d340f7f91cf396326933af5a7b835fa6 to your computer and use it in GitHub Desktop.
How to properly use Google's Spanner nodejs client library to do a transactional update in a Promise workflow
import spanner from '@google-cloud/spanner';
const spannerOptions = {
min: 10,
max: 100,
};
// Pretend projectId is a variable with your project ID string in it
// and instanceName is a variable with your db instance name in it
// and databaseName is a variable with your db database name in it
const db = spanner({ projectId }).instance(instanceName).database(databaseName, spannerOptions);
new Promise((resolve, reject) => {
db.runTransaction(async (err, dbTrx) => {
if (err) {
// Error getting session, creating transactional locks, etc
return reject(err);
}
// do stuff, like:
dbTrx.insert(tableName, rowData);
// If you'd like to bail out on the txn and have only done reads, do the following:
return dbTrx.end().then(resolve).catch(reject);
// If you'd like to bail but you've staged writes already, do:
return dbTrx.rollback().catch((rollbackErr) => {
return dbTrx.end().then(() => reject(rollbackErr)).catch((endErr) => reject(endErr));
});
// Ending may be changed to determine if promise should resolve or reject
// when a rollback was done vs an error performing the rollback, up to you
// When done staging writes and would like to commit, do the following:
// When passed no callback commit() returns a promise
return dbTrx.commit()
.then(resolve)
.catch((commitErr) => {
return dbTrx.end().then(() => reject(commitErr));
}); // Release the session
});
})
.then((resValue) => {
console.log('resolved');
})
.catch((err) => {
console.error('rejected');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment