Skip to content

Instantly share code, notes, and snippets.

@cmorss
Last active November 7, 2019 22:52
Show Gist options
  • Save cmorss/17d0e497535b99ab098c16451b88f069 to your computer and use it in GitHub Desktop.
Save cmorss/17d0e497535b99ab098c16451b88f069 to your computer and use it in GitHub Desktop.
// In express middleware when a request comes in we start a transaction
// and store it in continuation local store (think thread local store)
// Create a new user in the DB and return the newly created User instance
let user = await User.create({name: "Sally Smith", email: "sally@gmail.com"});
user.setAddressStreet1("123 Main St."); // With no Typescript
user.addressStreet1 = "123 Main St."; // If we introduce Typescript this would be okay too
user.save().then();
// All these static class query methods actually return an Objection QueryBuilder instance.
let userId = "34kaDFiidF";
user = await User.findById(userId);
// We could add an option to allow for blocking calls
user = User.findById(userId, {async: false});
await user.delete();
user.setName("Charlie"); // throw exception since the object is deleted
const users = await User.where('email', 'sally@gmail.com');
users.forEach(user => {
user.setRole("learner");
user.save({async: false})
});
// This does an "AND"
user = await User.findBy({role: 'learner', phone_number: '206-555-1212'});
// In express middleware we can catch a DB error (if it's not caught in application code) and
// rollback the transaction.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment