Invoice Application Backend Using ApsaraDB for MongoDB

Setting Up the Application Backend

  • Package.json
    This file holds all the information regarding the dependencies, such as development dependencies.
  • Server.js
    This is the key file where we write the logic. In production scenarios it is recommended to use the frameworks like Loopback to have a high-performance API with much more control.
  • Sprint-JS, mongoDB, node-UUID, formidable — for connecting to the database and creating the URL’s at runtime
  • Express and body-parser — are used to create the API’s and get the incoming request in a JSON format.
http.createServer(app).listen(443, function () {
console.log('Server for Invoice Backend running on port 443!');
});
const bodyParser = require("body-parser");
const express = require("express");
const app = express();
var uuid = require('node-uuid');
var http = require('http');
var fs = require('fs');
var sprintf = require("sprintf-js").sprintf;
var mongoClient = require('mongodb').MongoClient;
// ApsaraDB for MongoDB related configurations
var host1 = "dds-6gj540e0c157941.mongodb.ap-south-7.rds.aliyuncs.com";
var port1 = 3012;
var host2 = "dds-6gj54080c157942.mongodb.ap-south-7.rds.aliyuncs.com";
var port2 = 3012;
var username = "root";
var password = "Mongodb@12345";
var replSetName = "mgset-1050000641";
var demoDb = "admin";
app.post('/data/invoice', (req, res) => {
console.log(req.body);
var saveData = saveInvoiceData(req.body);
saveData.then(function(dbResponse){
console.log(dbResponse);
res.status(201).send(dbResponse);
},function(err){
console.log(err);
res.status(400).send(err);
});
});
function saveInvoiceData(collectionData) {  console.log(collectionData);
return new Promise(function (resolve, reject) {
// Logic to fetch from the MongoDB
mongoClient.connect(url, function (err, db) {
//if error console error
console.log(err);
if (err) {
// Database not connected : error thrown
console.error("connect err:", err);
reject(err);
} else {
//Database connected successfully, get the DB Object
var adminDb = db.admin();
//Authenticate Database
adminDb.authenticate(username, password, function (err, result) {
if (err) {
console.log("authenticate err:", JSON.stringyfy(err));
reject(err);
} else {
console.log('Authenticated : ', JSON.stringify(result));
// Get the Collection handle.
var collection = db.collection("saleData");
collection.insertOne(collectionData,function(err,result){
if(err){
reject(err);
}else{
resolve(result);
}
});
}
});
}
});
});
}
app.get('/data/dashboard', (req, res) => {
var getData = getDashboardData();
getData.then(function(result){
res.status(200).send(result);
},function(err){
console.log(err);
res.status(400).send(err);
});
});
function getDashboardData() {  return new Promise(function (resolve, reject) {
// Logic to fetch from the MongoDB
mongoClient.connect(url, function (err, db) {
//if error console error
console.log(err);
if (err) {
// Database not connected : error thrown
console.error("connect err:", err);
reject(err);
} else {
//Database connected successfully, get the DB Object
var adminDb = db.admin();
//Authenticate Database
adminDb.authenticate(username, password, function (err, result) {
if (err) {
console.log("authenticate err:", JSON.stringyfy(err));
reject(err);
} else {
console.log('Authenticated : ', JSON.stringify(result));
// Get the Collection handle.
var collection = db.collection("saleData");
collection.find({}).toArray(function (err, items) {
if (err) {
console.error('Unable to find data' + JSON.stringify(err));
} else {
console.info('data Fetched from MongoDB');
var response = {};
var datesArr = [];
var salesArr = [];
var ordersArr = [];
var i =0;
for(i=0; i<5; i++){
var totalSales = 0;
var totalOrders = 0;
var d = new Date();
d.setDate(d.getDate() - i);
var month = d.getMonth() + 1;
var day = d.getDate();
var output = d.getFullYear() + '/' + (month < 10 ? '0' : '') + month + '/' + (day < 10 ? '0' : '') + day;
datesArr.push(output);
console.log("In Loop 1 : "+i);
for(var k=0; k<items.length; k++){
var item = items[k];
if(item.invoiceDate == output){
totalSales = totalSales + item.totalAmount;
totalOrders = totalOrders+1;
}
}
salesArr.push(totalSales);
ordersArr.push(totalOrders);
}
response.datesArr = datesArr;
response.salesArr = salesArr;
response.ordersArr = ordersArr;
resolve(response);
}
});
}
});
}
});
});
}
{
"datesArr": [
"2018/03/25",
"2018/03/24",
"2018/03/23",
"2018/03/22",
"2018/03/21"
],
"salesArr": [
0,
4197.3,
34,
0,
0
],
"ordersArr": [
0,
1,
1,
0,
0
]
}

POSTMAN

  • You can call have different methods like GET, POST, PUT, PATCH, DELETE
  • There is a URI/address bar which also accepts the query parameters.
  • Click the send button to make the request and get the response.
  • You can explore more about this, you can run test cases or peak performance testing. This is a free tool you can use it for commercial purposes.

Deploying the API

Running the Code

Conclusion

--

--

--

Follow me to keep abreast with the latest technology news, industry insights, and developer trends. Alibaba Cloud website:https://www.alibabacloud.com

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Video Chapters from .vtt files using vue.js

Javascript String, Math and Array prototype

Using React Hooks to Update DOM

Regular Expressions Password Checker

The JavaScript Slice Cheat Sheet

A knife resting on a cutting board with a chili pepper and lines cut through board.

Deploying a React Native App to the App Store

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alibaba Cloud

Alibaba Cloud

Follow me to keep abreast with the latest technology news, industry insights, and developer trends. Alibaba Cloud website:https://www.alibabacloud.com

More from Medium

MongoDB database

Secure API with Oauth 2.0 Kong Plugin

Scaling A Node JS Application -Part 1