Skip to content

Instantly share code, notes, and snippets.

@snehil002
Created January 25, 2023 12:33
Show Gist options
  • Save snehil002/7eba630327d70435206b206b3cbcf38b to your computer and use it in GitHub Desktop.
Save snehil002/7eba630327d70435206b206b3cbcf38b to your computer and use it in GitHub Desktop.
Web Analytics Tool - Server API Endpoint Calculations - Requests from Dashboard to Server and Tracked Website To Server
/*
* GET /get-metric
* is the API endpoint for requesting data
* from DashBoard to the Server
*/
app.get("/get-metric", async (req, res) =>
{
// create parameters for MongoDB aggregation pipeline for
// reducing the lines of code
const aggrParams = createAggrParams(metricname, timezone);
// Filter the large DB with Date Range and URL Path
// Record is the Mongoose Model name
// This is the $match stage of the pipeline
const aggrMatch = matchWithDateAndPath(timestringi, timestringf, visitedurl, Record);
// This is the $group and $project stage of the Pipeline
// Here we use the Parameters created initially
const aggrProject = await groupAndProject(aggrMatch, aggrParams);
// X and Y axes of the Graph to be presented on the Dashboard
// are returned here
const result = getAxes(metricname, timestringi, timestringf, aggrProject);
// Labels of the Graph to be presented on the Dashboard
// are returned here
const yLabels = getYLabels(metricname);
// Labels are inserted in the correct spot of the JS Object 'result'
result["yaxis"]["visitorCount"]["ylabel"] = yLabels["visitorCountYLabel"];
result["yaxis"]["avgTime"]["ylabel"] = yLabels["avgTimeYLabel"];
// 'result' object is then sent to the Dashboard
// after converting to JSON
res.json(result);
}
/*
* POST /save-session-data
* is the API endpoint for collecting data
* from Tracked Website to the Server
*/
app.post("/save-session-data", async (req, res) => {
try {
// Data collected from the Tracked Website
// is stored in 'received'
const received = req.body;
// Creating a document from the received data
const doc = new Record(received);
// Received Object is attempted to be stored in the DB
// as it is. If there is validation error, then control
// moves to 'catch' and data is not saved in DB.
// Otherwise it is stored as is.
const saved = await doc.save();
// Success message is sent if there are no errors
console.log(saved);
res.json("Got Data!🎉");
}
catch(err) {
// Error message is sent on validation errors
console.error(err["message"]);
res.json("Error Tracking!😁");
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment