Created
September 10, 2018 10:14
-
-
Save darahayes/fd3c18bd4b57fdbeaf947fb6d78e5485 to your computer and use it in GitHub Desktop.
This file contains 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
const knex = require('knex') | |
const db = knex({ | |
client: 'pg', | |
connection: { | |
'user': 'postgresql', | |
'password': 'postgres', | |
'database': 'memeolist_db', | |
'host': '127.0.0.1', | |
'port': '15432' | |
} | |
}) | |
const sandbox = { | |
db: db | |
} | |
const {VM, VMScript} = require('vm2') | |
const vm = new VM({ | |
sandbox | |
}) | |
// we can load/parse the scripts at startup/reload time | |
// which ensures we are not parsing/compiling every time we call the resolver | |
const script = new VMScript(`db.select().from('meme')`) | |
// result is whatever is implicitly returned from the script | |
// in this case it will be the query builder object from knex | |
const result = vm.run(script) | |
// can look at the raw sql | |
if (result.toSQL) { | |
console.log(result.toSQL().toNative()) | |
} | |
// The thing is 'thenable' which means we build the query in the sandbox | |
// and run it outside of the sandbox | |
// can use async/await too | |
result.then(console.log) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OMG - I absolutely love this!