Skip to content

Instantly share code, notes, and snippets.

@darahayes
Created September 10, 2018 10:14
Show Gist options
  • Save darahayes/fd3c18bd4b57fdbeaf947fb6d78e5485 to your computer and use it in GitHub Desktop.
Save darahayes/fd3c18bd4b57fdbeaf947fb6d78e5485 to your computer and use it in GitHub Desktop.
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)
@wtrocki
Copy link

wtrocki commented Sep 10, 2018

OMG - I absolutely love this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment