-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
90 lines (69 loc) · 1.85 KB
/
index.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const express = require('express');
const bodyParser = require('body-parser');
const MongoConnection = require('./utils/mongodb.connection');
// Create app
const app = express();
const port = 4000;
// Enable serving static files
app.use(express.static('public'));
// Use convenient middleware to extract fully-parse JSON body
app.use(bodyParser.json());
// Process mongo commands
app.post('/', async (req, res) => {
const {
url, method, collection, data, options,
} = req.body;
res.setHeader('Content-Type', 'application/json');
// Connect to mongo instance
const db = new MongoConnection(url);
try {
await db.open();
} catch (e) {
console.error(e);
return res.status(500).json(e);
}
console.log('\nProcessing Query:');
console.log(data);
// Handle options
console.log('\nWith options:');
console.log(options);
// Execute request
try {
let result = await db.collection(collection)[method](data || {}, options);
switch (method) {
case 'aggregate':
case 'find':
result = await result.toArray();
break;
default:
}
db.close();
return res.status(200).json(result);
} catch (e) {
console.error(e);
return res.status(400).json(e);
}
});
// Get list of collections
app.post('/get-collections', async (req, res) => {
const { url } = req.body;
res.setHeader('Content-Type', 'application/json');
// Connect to mongo instance
const db = new MongoConnection(url);
try {
await db.open();
} catch (e) {
console.error(e);
return res.status(500).json(e);
}
// Execute request
try {
const result = await db.listCollections().toArray();
db.close();
return res.status(200).json(result);
} catch (e) {
console.error(e);
return res.status(400).json(e);
}
});
app.listen(port, () => console.log(`Listening on port ${port}`));