#30DaysOfAppwrite : Cloud Function with CRON
Torsten Dittmann
Posted on May 25, 2021
Intro
#30DaysOfAppwrite is a month-long event focused on giving developers a walk-through of all of Appwrite's features, starting from the basics to more advanced features like Cloud Functions! Alongside we will also be building a fully-featured Medium clone to demonstrate how these
concepts can be applied when building a real-world app. We also have some exciting prizes for developers who follow along with us!
Creating Statistics
On Day 24, we created a Cloud Function that was triggered by an event. This comes in handy when you want to react to interactions from the Client Side. For Day 25, we are going to create a Cloud Function that will be triggered at particular intervals of time. We can accomplish this by adding a CRON Schedule to our Cloud Function.
For Day 25, we are creating a Cloud Function that will run every day and create statistics for our App. We are going to save the number of profiles and posts every day in a Collection - this data allows us to develop Graphs and Statistics to track.
First of all, we are going to create a new Statistics collection with the following Rules:
-
Profiles:
- ID: profiles
- Rule Type: Integer
-
Posts:
- ID: posts
- Rule Type: Integer
-
Timestamp:
- ID: timestamp
- Rule Type: Integer
The Permissions will be role:all
for read, so anyone can retrieve the statistic, and we are going to leave the write permissions empty. Leaving the write empty will block anyone from writing to that Collection, except when they're using an API key.
Now that the Collection is prepared let's start with our cloud function. For this example, we are going to create another Node.js Cloud Function. As environment variables, we are going to add the following:
- APPWRITE_PROJECT_ID: Insert your project ID.
- APPWRITE_ENDPOINT: Insert your Appwrite endpoint.
- APPWRITE_API_KEY: Insert an API key that has documents.read and documents.write permissions.
- STATISTICS_COLLECTION: Insert the ID of the Statistics collection.
- PROFILE_COLLECTION: Insert the ID of the Profile collection.
- POST_COLLECTION: Insert the ID of the Post collection.
Under the Settings page of this Cloud Function, you also need to add a value in the Schedule (CRON Syntax) field. For our use case, we are setting it to 0 12 * * *
, which will execute this function every day at 12:00.
We will again move to our project directory and use the Appwrite CLI to create a NodeJS 16.0 function called create-statistics
.
appwrite init function
Within the src/index.js
, put in the following content:
const appwrite = require("node-appwrite");
module.exports = async function(req, res) {
const STATISTICS_COLLECTION = req.env.STATISTICS_COLLECTION;
const PROFILE_COLLECTION = req.env.PROFILE_COLLECTION;
const POST_COLLECTION = req.env.POST_COLLECTION;
// Initialise the client SDK
const client = new appwrite.Client();
const database = new appwrite.Database(client);
client
.setEndpoint(req.env.APPWRITE_ENDPOINT) // Your API Endpoint
.setProject(req.env.APPWRITE_PROJECT_ID) // Your project ID
.setKey(req.env.APPWRITE_API_KEY) // Your secret API key
;
// Get the sum of Profiles and Posts
const profiles = database.listDocuments(PROFILE_COLLECTION, [], 0).then(r => r.total);
const posts = database.listDocuments(POST_COLLECTION, [appwrite.Query.equal('published', true)], 0).then(r => r.total);
// Waiting for all promises to resolve and write into the Statistics Collection
Promise.all([profiles, posts]).then(([profiles, posts]) => {
return database.createDocument(STATISTICS_COLLECTION, "unique()", {
posts: posts,
profiles: profiles,
timestamp: Date.now()
}, ['role:all']);
}).then(res.send).catch((err) => res.send(err, 500));
};
We will then deploy the function to our instance, go ahead and change our directory to the project one and run the following command:
appwrite deploy function
Make sure to select our create-statistics
function and deploy it.
Testing Our Cloud Function
We can easily test out our function by waiting for 12:00 or just executing it manually on your Functions page. If the function was executed successfully, you could head over to the Statistics Collection, and you should find a document like this:
With this data, we can create Charts and Statistics to monitor the usage of our application.
Feel free to share how you would leverage this data and implement it in the Medium clone!
Credits
We hope you liked this write-up. You can follow #30DaysOfAppwrite on Social Media to keep up with all of our posts. The complete event timeline can be found here
Feel free to reach out to us on Discord if you would like to learn more about Appwrite, Aliens, or Unicorns 🦄. Stay tuned for tomorrow's article! Until then 👋
Posted on May 25, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.