-
Notifications
You must be signed in to change notification settings - Fork 1
/
repl.js
76 lines (66 loc) · 1.91 KB
/
repl.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import 'esm';
import 'isomorphic-fetch';
import 'babel-polyfill';
import REPL from 'repl';
import replPromised from 'repl-promised';
import history from 'repl.history';
// import babel from 'babel-core';
const babel = require('babel-core');
import { connectDatabase } from './src/database';
import * as M from './src/model';
import { generateToken } from './src/auth';
// based on https://gist.github.com/princejwesley/a66d514d86ea174270210561c44b71ba
/**
* Preprocess repl command to wrap await inside an async function if needed
* @param input
* @returns {*}
*/
function preprocess(input) {
const awaitMatcher = /^(?:\s*(?:(?:let|var|const)\s)?\s*([^=]+)=\s*|^\s*)(await\s[\s\S]*)/;
const asyncWrapper = (code, binder) => {
let assign = binder ? `global.${binder} = ` : '';
return `(function(){ async function _wrap() { return ${assign}${code} } return _wrap();})()`;
};
// match & transform
const match = input.match(awaitMatcher);
if (match) {
input = `${asyncWrapper(match[2], match[1])}`;
}
return input;
}
function myEval(cmd, context, filename, callback) {
const code = babel.transform(preprocess(cmd), {
presets: [
'flow',
[
'env',
{
targets: {
node: 'current',
},
},
],
],
plugins: [['babel-plugin-transform-flow-strip-types']],
}).code;
_eval(code, context, filename, callback);
}
let _eval;
(async () => {
try {
const info = await connectDatabase();
console.log(`Connected to ${info.host}:${info.port}/${info.name}`);
const repl = REPL.start({
prompt: 'awesome > ',
});
_eval = repl.eval;
repl.eval = myEval;
repl.context.M = M;
repl.context.generateToken = generateToken;
history(repl, `${process.env.HOME}/.node_history`);
replPromised.promisify(repl);
} catch (error) {
console.error('Unable to connect to database');
process.exit(1);
}
})();