DEV Community

loading...
Cover image for #30DaysOfAppwrite : Cloud Function with CRON
Appwrite

#30DaysOfAppwrite : Cloud Function with CRON

Torsten Dittmann
Fullstack Engineer
・4 min read

Intro

#30DaysOfAppwrite is a month long event focused at 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 of each day in a Collection - this data allows us to create Graphs and Statistics to track.

First of all, we are going to create a new Statistics collection with the following Rules:

  • Profiles:

    • Label: Profiles
    • Key: profiles
    • Rule Type: Numeric
  • Posts:

    • Label: Posts
    • Key: posts
    • Rule Type: Numeric
  • Timestamp:

    • Label: Timestamp
    • Key: timestamp
    • Rule Type: Numeric

The Permissions will be * 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 for when they're using an API key.

Rules

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.

Create a Node.js project using npm:

mkdir create-statistics
cd create-statistics
npm init -y
Enter fullscreen mode Exit fullscreen mode

Now add node-appwrite as a dependency:

npm install node-appwrite
Enter fullscreen mode Exit fullscreen mode

Create index.js file and put in following content:

const STATISTICS_COLLECTION = process.env.STATISTICS_COLLECTION;
const PROFILE_COLLECTION = process.env.PROFILE_COLLECTION;
const POST_COLLECTION = process.env.POST_COLLECTION;

// Initialise the client SDK
const appwrite = require('node-appwrite');
const client = new appwrite.Client();
const database = new appwrite.Database(client);

client
    .setEndpoint(process.env.APPWRITE_ENDPOINT) // Your API Endpoint
    .setProject(process.env.APPWRITE_PROJECT_ID) // Your project ID
    .setKey(process.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.sum);
const posts = database.listDocuments(POST_COLLECTION, ['published=1'], 0).then(r => r.sum);

// Waiting for all promises to resolve and write into the Statistics Collection
Promise.all([profiles, posts]).then(([profiles, posts]) => {
    return database.createDocument(STATISTICS_COLLECTION, {
        posts: posts,
        profiles: profiles,
        timestamp: Date.now()
    }, ['*']);
}).then(console.log).catch(console.error);
Enter fullscreen mode Exit fullscreen mode

We can upload the Function very easily using the Appwrite CLI (or upload it manually in the dashboard):

appwrite functions createTag --code=. --functionId=[YOUR_FUNCTION_ID] --command='node index.js'
Enter fullscreen mode Exit fullscreen mode

Don't forget to activate the tag we just created!
We covered both the CLI method and Manual method on Day 23. So feel free to check it out if you get stuck.

Testing Our Cloud Function

We can easily test out our function by waiting for 12:00 or just executing it manually in your Functions page. If the function was executed successfully, you can head over the the Statistics Collection and you should find a document like this:

Result

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 👋

Discussion (0)