This is simple server which basically just writes something to mongo after it accepts POST request, and then initiates a new HTTP request. I would appreciate feedback especially if I am doing correctly error handling etc. The code does its job though.
const MongoClient = require('mongodb').MongoClient;
const express = require('express')
const app = express()
var bodyParser = require('body-parser');
var http = require('http');
/* Connection URL */
const URL = 'mongodb://localhost:27017';
/* Database Name */
const DB_NAME = 'config-insert';
/* Handle to the connection */
let db = null;
/* Middlewares */
app.use(bodyParser.json());
/*
* Use connect method to connect to the server
*/
MongoClient.connect(URL, function (err, client) {
if (err) {
throw new Error("Error connecting to mongo");
}
db = client.db(DB_NAME);
});
/*
* Insert one document to mongo database.
*
* Parameters
* data - what to insert.
* successCallback - success callback.
*
*/
function insertOne(data, successCallback) {
if (!db) {
throw new Error("There is no connection");
}
/* Insert a single document */
db.collection('config-history').insertOne(data, {
w: 'majority'
, wtimeout: 10000
, serializeFunctions: true
}, function (err, r) {
if (err) {
throw new Error("Error inserting");
}
successCallback(r);
});
}
/*
* Handler for post request
*/
app.post('/', function (req, res) {
let data = req.body;
insertOne(JSON.parse(JSON.stringify(data)) /* use this otherwise mongo was modifying data variable */, function success() {
let req = http.request({
host: '10.1.1.41',
path: `/category/${data.id}`,
method: 'PUT',
port: 9202
}, function (response) {
var resp = '';
response.on('data', function (d) {
resp += d;
});
response.on('end', function () {
if (JSON.parse(resp)._shards.successful == 1) {
res.status(200).json({ status: "ok" })
}
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
req.write(JSON.stringify(data));
req.end();
})
})
/*
* Listen for connections.
*/
app.listen(4000, () => console.log('Example app listening on port 4000!'))