UNPKG

2.42 kBJavaScriptView Raw
1#!/usr/bin/env node
2
3/*
4
5 This is a debugging REPL with access to the mongoose models (but not much else)
6
7 Usage:
8 $ ./_models.js
9 Loading REPL...
10 > models.require('Foo');
11 undefined
12 > Foo.find({ }, store('foos'));
13 { ... }
14 >
15 Stored 2 arguments in "foos"
16 > print(foos);
17 { ... }
18
19*/
20
21var path = require('path');
22var util = require('util');
23var colors = require('colors');
24
25// CONFIG
26var conf = {
27 url: '',
28 types: [ 'email', 'url', 'uuid' ],
29 modelPath: path.join(__dirname, 'models')
30};
31
32// Check for a color disable flag
33if (process.env.DISABLE_COLORS) {
34 colors.mode = 'none';
35}
36
37// Welcome message
38console.log('Loading REPL...'.grey);
39
40// Determine some config global
41global.REPL_PROMPT = process.env.REPL_PROMPT || '> ';
42global.INSPECT_DEPTH = Number(process.env.INSPECT_DEPTH);
43if (isNaN(global.INSPECT_DEPTH)) {
44 global.INSPECT_DEPTH = 2;
45}
46
47// Load mongoose models
48var models = global.models = require('mongoose-models');
49models.init(conf);
50
51// Patch models.require to store in global automatically
52models._require = models.require;
53models.require = function(model) {
54 global[model] = models._require(model);
55};
56
57// Define the print function
58var print = global.print = function() {
59 console.log.apply(console, arguments);
60 process.stdout.write(global.REPL_PROMPT);
61};
62
63// Define the store function
64var store = global.store = function(name) {
65 return function() {
66 var args = arguments;
67 process.nextTick(function() {
68 global[name] = args;
69 print(('\nStored ' + args.length + ' arguments to "' + name + '"').green.italic);
70 process.stdout.write(buffer);
71 });
72 };
73};
74
75// Enable stdin
76process.stdin.resume();
77process.stdin.setEncoding('utf8');
78
79// Build a buffer so we can reprint any given input when we
80// have to interupt the user
81var buffer = '';
82process.stdin.on('keypress', function(ch) {
83 buffer += ch;
84});
85
86// Eval stage
87process.stdin.on('data', function (data) {
88 buffer = '';
89 print(util.inspect(eval(data), true, global.INSPECT_DEPTH, ! process.env.DISABLE_COLORS));
90});
91
92// Allow exiting on ctrl+c
93process.on('SIGINT', function() {
94 console.log('\nGood Bye.'.grey)
95 process.exit();
96});
97
98// Print errors in red
99process.on('uncaughtException', function(err) {
100 if (typeof err === 'object' && err && err.stack) {
101 err = err.stack;
102 }
103 print(err.red);
104});
105
106// Start...
107process.stdout.write(global.REPL_PROMPT);
108
109/* End of file _models.js */