Skip to content

Instantly share code, notes, and snippets.

@dacharyc
Last active October 28, 2023 18:27
Show Gist options
  • Save dacharyc/cf96479f81d312f6dd2796eb67cd6729 to your computer and use it in GitHub Desktop.
Save dacharyc/cf96479f81d312f6dd2796eb67cd6729 to your computer and use it in GitHub Desktop.
Insert data to MongoDB Atlas in an Atlas Function called by a HTTPS Endpoint
// This Gist goes with the article at http://dacharycarey.com/2023/11/01/hackathon-part-1/
// This function is the endpoint's request handler.
exports = function({ formData, headers }, response) {
// Data can be extracted from the request as follows:
// Headers, e.g. {"Content-Type": ["application/json"]}
const contentTypes = headers["Content-Type"];
// The "formData" here is the form data sent from Google Analytics
console.log("Form data", JSON.stringify(formData));
// Querying a mongodb service:
const sdkDocsCollection = context.services.get("mongodb-atlas").db("DeviceSDK").collection("SDKDocs")
const mongoDBQuery = { "url": formData["url"] };
const dateAsDateTime = new Date(formData["date"]);
function getWeek(date) {
if (!(date instanceof Date)) date = new Date();
// ISO week date weeks start on Monday, so correct the day number
var nDay = (date.getDay() + 6) % 7;
// ISO 8601 states that week 1 is the week with the first Thursday of that year
// Set the target date to the Thursday in the target week
date.setDate(date.getDate() - nDay + 3);
// Store the millisecond value of the target date
var n1stThursday = date.valueOf();
// Set the target to the first Thursday of the year
// First, set the target to January 1st
date.setMonth(0, 1);
// Not a Thursday? Correct the date to the next Thursday
if (date.getDay() !== 4) {
date.setMonth(0, 1 + ((4 - date.getDay()) + 7) % 7);
}
// The week number is the number of weeks between the first Thursday of the year
// and the Thursday in the target week (604800000 = 7 * 24 * 3600 * 1000)
return 1 + Math.ceil((n1stThursday - date) / 604800000);
}
const weekNumber = getWeek(dateAsDateTime);
const dataOfAppropriateTypes = {
"bounce_rate": parseFloat(formData["bounce_rate"]),
"pages_per_session": parseFloat(formData["pages_per_session"]),
"users": parseInt(formData["users"]),
"avg_session_duration": parseInt(formData["avg_session_duration"]),
"unique_pageviews": parseInt(formData["unique_pageviews"]),
"sessions": parseInt(formData["sessions"]),
"session_duration": parseInt(formData["session_duration"]),
"year": dateAsDateTime.getFullYear(),
"week_number": weekNumber
}
const update = {
"$push": {
"weekly_data": dataOfAppropriateTypes
}
}
const options = { "upsert": false };
sdkDocsCollection.updateOne(mongoDBQuery, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully updated the item.`)
}
})
.catch(err => console.error(`Failed to update the item: ${err}`))
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment