Skip to content

Instantly share code, notes, and snippets.

@pca2
Last active October 1, 2018 00:45
Show Gist options
  • Save pca2/399bf17084b25fbfa58dc0a5c364b43d to your computer and use it in GitHub Desktop.
Save pca2/399bf17084b25fbfa58dc0a5c364b43d to your computer and use it in GitHub Desktop.
Combining MongoDB Stitch Triggers and Services
<html>
<head>
<script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4.0.0/stitch.js"></script>
<script>
// Initialize the App Client
const client = stitch.Stitch.initializeDefaultAppClient("INSERT-YOUR-APP-ID");
// Get a MongoDB Service Client
const mongodb = client.getServiceClient(
stitch.RemoteMongoClient.factory,
"mongodb-atlas"
);
// Get a reference to the blog database
const db = mongodb.db("Weight");
function displayWeights() {
db.collection("weights")
.find({}, { limit: 1000 })
.asArray()
.then(docs => docs.map(doc => `<tr><td>${doc.weight}</td></tr>`))
.then(weights => document.getElementById("weights").innerHTML = weights.join(" ") )
}
function displayWeightsOnLoad() {
client.auth
.loginWithCredential(new stitch.AnonymousCredential())
.then(displayWeights)
.catch(console.error);
}
function addWeight() {
const newWeight = document.getElementById("new_weight");
console.log("add weight", client.auth.user.id)
db.collection("weights")
.insertOne({ owner_id: client.auth.user.id, weight: newWeight.value })
.then(displayWeights);
newWeight.value = "";
}
</script>
</head>
<body onLoad="displayWeightsOnLoad()">
<h3>Weight Tracker 3000</h3>
<div id="content">
Keep track of your weight with our nifty website
</div>
<hr>
<table id="weights"></table>
<hr>
Add a new weight: <input id="new_weight" type="number"><input value="Submit Weight" type="submit" onClick="addWeight()">
</body>
</html>
exports = function(changeEvent) {
const http = context.services.get("wt_http_service");
const newWeight = changeEvent.fullDocument.weight;
const thresholdWeight = 145;
const slackURL = 'https://hooks.slack.com/services/T8MHO2QSKK/BW8EFN/B5nKgGZYLuZcKgvY8rNvzHE';
const slackMsg = `Uh-oh a weight was posted of ${newWeight}, better lay off the pie`;
if(newWeight < thresholdWeight ){
return "Weight under threshold";
} else {
return http
.post({ url: slackURL, body: JSON.stringify({"text": slackMsg})})
.then(resp => {
return resp;
})
.catch(err => console.log(err) );
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment