Skip to content

Instantly share code, notes, and snippets.

@mcasimir
Created December 6, 2019 11:48
Show Gist options
  • Save mcasimir/bb59a8b3417bcbb462eaf08e11657cd8 to your computer and use it in GitHub Desktop.
Save mcasimir/bb59a8b3417bcbb462eaf08e11657cd8 to your computer and use it in GitHub Desktop.
const {MongoClient} = require('mongodb');
const rewriteWithAwait = require('./rewrite-with-await.js');
const startShell = require('./start-shell.js');
function makeCollectionObject(nativeCollection) {
return {
insertOne: (...args) => {
return nativeCollection.insertOne(...args);
},
findOne: (...args) => {
return nativeCollection.findOne(...args);
},
find: (...args) => {
return nativeCollection.find(...args).toArray();
},
};
}
function makeDbObject(nativeDb) {
return new Proxy(
{},
{
get(target, propKey) {
return makeCollectionObject(nativeDb.collection(propKey));
},
},
);
}
async function main() {
const client = await MongoClient.connect('mongodb://localhost:27017/test', {
useUnifiedTopology: true,
});
startShell({
eval: async (replEval, cmd, context, filename) => {
return await replEval(rewriteWithAwait(cmd), context, filename);
},
context: {
db: makeDbObject(client.db()),
},
});
}
main();
const {parse} = require('@babel/parser');
const generate = require('@babel/generator').default;
const traverse = require('@babel/traverse').default;
const {awaitExpression, isAwaitExpression} = require('@babel/types');
function rewriteWithAwait(cmd) {
const ast = parse(cmd, {allowAwaitOutsideFunction: true});
traverse(ast, {
CallExpression: function(path) {
if (isAwaitExpression(path.parent)) {
return;
}
path.replaceWith(awaitExpression(path.node));
},
});
return generate(ast).code;
}
module.exports = rewriteWithAwait;
const nodeRepl = require('repl');
const {promisify} = require('util');
function startShell(options = {}) {
const replInstance = nodeRepl.start({
prompt: options.prompt,
});
Object.assign(
replInstance.context,
options.context,
);
const replEval = promisify(replInstance.eval.bind(replInstance));
replInstance.eval = async (cmd, context, filename, callback) => {
options.eval(replEval, cmd, context, filename)
.then((res) => callback(null, res))
.catch(callback);
};
return replInstance;
}
module.exports = startShell;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment