|
| 1 | +// An example that shows a database operation. |
| 2 | +// I used an in-memory mongodb server for this |
| 3 | +// extract the client address, compute the current |
| 4 | +// time and store these in the db. Respond back |
| 5 | +// with the history of all client accesses. |
| 6 | + |
| 7 | +// server |
| 8 | + |
| 9 | +// source-in an in-memory server module |
| 10 | +const { MongoMemoryServer } = require('mongodb-memory-server') |
| 11 | + |
| 12 | +// server host |
| 13 | +const HOST = 'localhost' |
| 14 | + |
| 15 | +// server port |
| 16 | +const PORT = 13000 |
| 17 | + |
| 18 | +// db instance name |
| 19 | +const DBNAME = 'mydb' |
| 20 | + |
| 21 | +// server instance, created through dbstart |
| 22 | +let mongod = null |
| 23 | + |
| 24 | +// start a server instance |
| 25 | +async function dbstart() { |
| 26 | + mongod = new MongoMemoryServer({instance: {port: PORT, dbName: DBNAME}}) |
| 27 | + await mongod.getDbName() |
| 28 | +} |
| 29 | + |
| 30 | +// stop the server instance |
| 31 | +exports.dbstop = async function() { |
| 32 | + if(mongod) |
| 33 | + await mongod.stop() |
| 34 | +} |
| 35 | + |
| 36 | +// client |
| 37 | + |
| 38 | +async function exec(req, res) { |
| 39 | + // source-in the db client |
| 40 | + const MongoClient = require('mongodb').MongoClient |
| 41 | + |
| 42 | + // start the db server |
| 43 | + await dbstart() |
| 44 | + const url = `mongodb://${HOST}:${PORT}` |
| 45 | + |
| 46 | + // connect to the db server |
| 47 | + MongoClient.connect(url, (err, client) => { |
| 48 | + const db = client.db(DBNAME) |
| 49 | + const collection = db.collection('documents') |
| 50 | + |
| 51 | + // create a new record |
| 52 | + var record = {} |
| 53 | + record.time= new Date().toString() |
| 54 | + record.client = req.connection.remoteAddress |
| 55 | + |
| 56 | + // insert the record into the db |
| 57 | + collection.insertMany([record], function(err, result) { |
| 58 | + |
| 59 | + // retrieve all the records back |
| 60 | + collection.find({}).toArray(function(err, docs) { |
| 61 | + |
| 62 | + // send it as the response. |
| 63 | + res.end(JSON.stringify(docs)) |
| 64 | + client.close() |
| 65 | + }) |
| 66 | + }) |
| 67 | + }) |
| 68 | +} |
| 69 | + |
| 70 | +exports.setup = function(app) { |
| 71 | + app.get('/db', (req, res) => { |
| 72 | + exec(req, res) |
| 73 | + }) |
| 74 | +} |
| 75 | + |
0 commit comments