How to Create Scheduled Webhook Triggers with Appwrite Functions
Published: 2022-10-10 13:03:22

When building an application, it’s best practice to consider the development speed, the engineering cost, etc. Utilizing a service that can run and maintain your backend development tasks and cloud infrastructure while focusing on the core or client-side development is a wise choice.

A Backend-as-a-Service (BaaS) platform generally provides tools and features (like sets of APIs) or database services to aid the creation of your backend code, thereby increasing the speed of your development process. A real-life use case of BaaS is in advanced applications that involve data streaming, scheduling emails based on specific events, and pushing notifications.

This article explores the functionalities of a BaaS platform called [Appwrite](https://appwrite.io/?utm_source=hackmamba&utm_medium=hackmamba-blog). You’ll learn how to create [Appwrite functions](https://appwrite.io/docs/functions) in [Node.js](https://nodejs.org/en/) on Appwrite and set a schedule with the Appwrite console.


### Prerequisites
- [Appwrite](https://appwrite.io/docs/installation) installed 
- [Appwrite CLI](https://appwrite.io/docs/command-line) installed
- [Docker Compose](https://docs.docker.com/compose/install/) (Version 2) installed
- Terminal
- [Node.js](https://nodejs.org/en/) installed
- [VS Code](https://code.visualstudio.com/download) editor

### Appwrite Functions

Appwrite is an open-source, backend-as-a-service with in-built features, tools, APIs, and a management console used by developers to handle complex backend tasks and increase the speed of developing applications. It offers several services, including [Account service](https://appwrite.io/docs/client/account) (which has built-in integration for users’ authentication), [Database service](https://appwrite.io/docs/databases) (which provides access to Appwrite REST APIs for interfacing user data), and so on. 

When users of your application create an account or log in, you can define code in [Appwrite functions](https://appwrite.io/docs/functions) to run and execute based on system events. Appwrite functions support multiple runtimes (like Node.js, Python, and PHP) and allow you to schedule the functions in your code to run at specific time intervals with your specified runtime. 

In addition, you can seamlessly create and deploy your functions by running commands in your Appwrite [CLI](https://appwrite.io/docs/command-line) (which enables you to work with the Appwrite server).


### Webhooks

When developing large-scale applications that interact with several applications or systems (e.g., payment or banking systems), establishing a communication bridge that listens for events between these systems is crucial. 
Appwrite supports [Webhooks](https://appwrite.io/docs/webhooks), which you can utilize by subscribing to any [event](https://appwrite.io/docs/webhooks#events) to send automated messages to your application when an event is triggered (e.g., you can get notified when users register to your application). 

For this article, you’ll be using an external [Webhook service](https://webhook.site/).

### Getting Started

To begin, ensure that you have installed [Appwrite](https://appwrite.io/docs?utm_source=hackmamba&utm_medium=blog&utm_campaign=hackmamba) and [Appwrite CLI](https://appwrite.io/docs/command-line). Confirm that you have the CLI installed by running this command:


    appwrite -v

Start running your Appwrite server by choosing the command suitable for your OS as defined in the [documentation](https://appwrite.io/docs/installation). For Unix systems, run this command:


    docker run -it --rm \ --volume /var/run/docker.sock:/var/run/docker.sock \ --volume "$(pwd)"/appwrite:/usr/src/code/appwrite:rw \ --entrypoint="install" \ appwrite/appwrite:0.15.3

Note that the Appwrite server would not run if you have not installed [docker-compose V2](https://docs.docker.com/compose/install/).

After running the command, at the prompt, choose the server HTTP port, HTTPS port, and secret API key and then enter your hostname for Appwrite and DNS.

To confirm the installation, you should see the message “Appwrite installed successfully” in your terminal:


![](https://lh3.googleusercontent.com/HyPeI6nVlItYRqzzd57gaPJheBKeM4dpa-PUyoVgmunvcPrryXCENtspztmr15Wiihx0saqO3ZrcEIgUaAICb0-ysl17CPr0Bmx877OIBsppvqzrdf2AT0uV9D19XYMrUH1JJ2MB7TCKGYo_GoYcU38)


Now, you can access the Appwrite console by navigating to your browser with the URL and port number you specified at [http://localhost:5000](http://localhost:5000). Afterward, the signup page will open at [http://localhost/auth/signup](http://localhost/auth/signup):


![](https://lh4.googleusercontent.com/1R7yzkwS1Ftn_0uaSrx8KGvcCwCIWS0ctxCRs9jXsSGzW-GKZUd1BZnOYV1ounX2WV_FaNT5KhhLpNZm8nOwPHwztn9K_V7FmX_imOrkCU2iRZKY9m2fIxU-gqawDmHMhIVKoti5Y_qXIy1WQtU16c8)


Enter your sign up details and proceed to the console, which opens at [http://localhost/console](http://localhost/console): 


![](https://lh6.googleusercontent.com/ICnh0JA2CDCn1FZo97tLn-dqIQKQufRsToMKTvsH7FVC39fVFbd2BxN9A0SxYWYMQHoZBkEhJy6_sJuTnyE3XsrQiTBgH_S9blLmb62Ca4_f8zJ1MqzkGil9xXsgBS8LxC7OqORiDQ-pzrersyzp5ww)

### Creating the Appwrite Project

Here, you’ll create a project using the Appwrite CLI that will act as a container for your application, including all the dependencies. Create a directory named “**test1**” for your project:


    mkdir test1
    cd test1

Now that you have created your Appwrite account, log in to access the CLI with:


    appwrite login

Once you run this command, enter your email, password, and Appwrite server endpoint at the prompt. Afterward, you should get a **success** message confirming that you have logged in. 

To use Appwrite, you need to initialize your Appwrite project with the Appwrite CLI. In your application’s directory test1, run this command:


    appwrite init project

After running this command, at the prompt, enter the following answers:

- How would you like to start? - choose the first option
- What you’d like to name the project? - test1 (use any name of your choice)
- What ID you’d like to use to identify your project on Appwrite? - test1 (use any ID)

Afterward, you should get a success message in your terminal. Appwrite will add an appwrite.json file to your application’s directory containing your project’s name and ID. 
Run `code .` in your terminal to view the file:


![](https://lh5.googleusercontent.com/ggQcir5vMfbDp1tYePj1sMOlTCVBMcs5T-xi-tPi9KIzLwJKGvsS7gJV9gu6C6_lcJ5HTpXsx8Say3Bq0zT7Tzi1mE5_7BJ1Tnk_R35ycpzVjpLXXqprhZ_lRgy7lpTuwKHbFr76Fl6CMlZKl_FIaMY)


Navigate to your Appwrite console at [http://localhost:5000/console/](http://localhost:5000/console/) and your project will be visible on the console, and you will have access to all Appwrite services:


![](https://lh6.googleusercontent.com/9i-6u5Vr3Ia8051pRBBo7RJYxeBlcv9KScBPOeLgSgEEbZmYUG7uA9kwZCKdTEgsmQtS5kKT_smYtStuCN8WKBPV1BE57w9y8JMZAuEH24zWV0ZTPguQn5h3l3NBz0En5fQQ8tQg19r6JFEhOIZH16U)

### Creating the Appwrite Function

Here, you’ll extend your Appwrite server functionality by creating the [Appwrite function](https://appwrite.io/docs/functions) using Node.js as the runtime and setting a timing schedule for them on your Appwrite console. 

To create your Appwrite functions, run this command in your project’s directory:


    appwrite init function

At the prompt, enter a name for your function and an ID and choose the Node.js runtime from the options:

![](https://lh4.googleusercontent.com/c2jQLWleZrFvpaK9FWnW16gHuxa5B1LBeNA8qubxfFwa0-gAmop9TPNodQHpCmSvlQtxfSQ2mf5C-IjireIqSFQscOz2U99EbjRr3M1t5zp4fVrTya4VplAXKu3REXqjCpTn0aJ4vHT4w7M1i4en-Us)


Then, Appwrite will create a **functions** folder in your project’s folder with the **Scheduler Function** that contains your Node.js project (including a **package.json** file and an **src** folder with an **index.js** file). Your folder structure and **appwrite.json** file in your code editor should look like this:


![](https://lh6.googleusercontent.com/loxzfulW5ro1WF9P_AvLtlh2zMiP6F5IRHXIjAzBDBwyPS62ap3GgtMctRo2q0GGNIdQdWFS22dt2yTWBIimnBXXSHSukmO4lXZk6SgcwVH0bwsIwaaQyUcnUBcIQCjHjy9YEKyFU7N02uTMOTNThSc)


Next, set the schedule option in the appwrite.json file to `* * * * *` cron expression for Appwrite to trigger the function every second.

### Executing the Appwrite Function

To execute the Appwrite function, you’ll use a free [webhook service](https://webhook.site/#!/5232a175-81bb-40c5-b4f5-63fd12fac625) as an external API that your function can call every second.

You'll need an HTTP client to make function calls to the webhook service. In your functions directory, Install [axios](https://axios-http.com/docs/intro) with this command:


    cd ./functions/Scheduler
    npm i axios

Open the [webhook service](https://webhook.site/#!/5232a175-81bb-40c5-b4f5-63fd12fac625) on your browser and copy the unique URL provided:


![](https://lh5.googleusercontent.com/MNqwRLfFXaa85iCvmKVAUytgYNX14c6Q0tG-lrsI0lLOQUcMno1jEUelvsJ6P2lm2CHG91AtlND_KVOeu8fSXI6pTUNbYytt_vlHSegnyUuX3QehV3o-bL8zlHFgA-gx-u-Rnwo7llMMDU6w7ySVXjw)


Then, replace the code in the index.js file located in functions>Scheduler>src folder with this code:


    const { default:axios } = require("axios")
     
    module.exports = async function (req, res) {
     try {
       const response = await axios.post("https://webhook.site/0f97880b-f517-410e-8d73-6fa342ecd6eb", {
         payload: req.payload
       })
        res.json({
         message: 'Success!',
         payload: req.payload,
         response: response.data
       });
     } catch(error) {
         res.send("something went wrong")
     }
    };

The code above:

- Creates an asynchronous function that does the following:
    - Makes a post request with axios using the unique URL from the webhook service and sets the payload (JSON string containing the data created on execution) in the request object
    - Sets the message (a string that displays on successful execution), payload, and the response data in the response object

Deploy your function by going back to your test1 directory and running this command:


    cd ../..
    appwrite deploy function

This command will prompt you to choose the function you would like to deploy; select your **Scheduler** function, and Appwrite will successfully deploy your function:

![](https://lh6.googleusercontent.com/F7JNWzdZ1abejr16oLxX7SNS4VT_nKnOzqHBcZDDhGUtUeZHj_WBL0yoqy7AuuW1uv2gKU2TdBtbkttzBSNeEjXc_R7olLgC4x5Jhrh8R-nZir9Ki0bgvtSBld-9ZGo_p70Ici1hu_kgY7AoCj__MiM)


To confirm the deployment of your function, navigate to your Appwrite console, click on [functions](https://webhook.site/#!/5232a175-81bb-40c5-b4f5-63fd12fac625) on the sidebar menu, and you should see your deployment:


![](https://lh5.googleusercontent.com/y8WVhRtQE4s1iJ8R2raJFWfuSoSKZdopeZXael4V-_FCgSehYR9M6Q8CiruGXAeYRRqlNDhlT1OBkoq0FG5seX8M5-pmmm240GwpTTNrXeHx_eMXh1zGVTaXY46oCQgOit814trdeiuojPQFwpEO85Y)


If the function doesn’t trigger automatically, go to the **settings** tab for the **Functions** and click the **update** button:


![](https://paper-attachments.dropbox.com/s_F11C30ABE81847FC189EED79B91424256FB3D0462DBCD22C3D11CAD875B073FB_1661435033821_Screenshot+2022-08-25+at+14.42.33.png)


Click on the “View as JSON” link right-hand-side to view the schedule configuration for the function:


![](https://paper-attachments.dropbox.com/s_F11C30ABE81847FC189EED79B91424256FB3D0462DBCD22C3D11CAD875B073FB_1661435517117_Screenshot+2022-08-25+at+14.50.27.png)


Navigate to your webhook service to view the incoming requests, which happens after every successful execution of the Appwrite function:


![](https://lh3.googleusercontent.com/UqannFZ2H8o3crXVjVf1P_zcNgXrasNlap704v-6xfdkFg_1cIAE7YCprDI0dnoTcxtgsc7YMq7FEZVXUWRaVb-AV-W_YOK2a7Ufq2YEeJZg5wG3GtlX9youF30YtWQL-0mO1gdr9hW4BFD_sgaSMZ4)

### Conclusion

Integrating Appwrite functions into your projects saves development time and overall cost. In this article, you covered Appwrite functions, setting a schedule to execute the functions in Node.js runtime with an external webhook service. 

### Resources

You may find the following links useful:

- Appwrite functions [documentation](https://appwrite.io/docs?utm_source=hackmamba&utm_medium=blog&utm_campaign=hackmamba) 
- [Docker compose](https://docs.docker.com/compose/install/) documentation