Created
July 13, 2022 13:49
-
-
Save willsheppard/372ee75563930e0f8e4487522c357c41 to your computer and use it in GitHub Desktop.
Knex basics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| knex.select() | |
| .from('some_table') | |
| .where({ | |
| name: 'Mr Foo' | |
| }) | |
| .then((result) => { | |
| // This block is *REQUIRED* or the query is not sent to the database! | |
| if (! result[0]) { | |
| console.log(`Error: "Mr Foo" was not found.`); | |
| process.exit(1); // It is alright to exit here *IF* it's a fatal condition | |
| } | |
| // Mr Foo was found | |
| doSomethingWithMrFoo({ nameId: result[0].id }); | |
| }) | |
| .then(() => { | |
| // Query completed, Mr Foo may or may not have been found. | |
| console.log('Query done.'); | |
| doNextThing(); | |
| //process.exit(0); // Warning: Do not call exit here or the knex promises don't get fulfilled. | |
| }); | |
| function doNextThing { | |
| knex('track').insert({ | |
| name: track.name, | |
| artist: track.artist, | |
| }) | |
| .then(function(resp) { | |
| console.log('loaded track', resp); | |
| }).catch(function(err) { | |
| console.log('ERROR:', err); | |
| process.exit(1); // It is alright to exit here because there is a fatal error (the database failed to run the query) | |
| }); | |
| } | |
| console.log('Everything done.'); | |
| //process.exit(0); // Do not exit here either, or knex operations will not finish. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment