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. You’ll learn how to create Appwrite functions in Node.js on Appwrite and set a schedule with the Appwrite console.
Prerequisites
- Appwrite installed
- Appwrite CLI installed
- Docker Compose (Version 2) installed
- Terminal
- Node.js installed
- VS Code 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 (which has built-in integration for users’ authentication), Database service (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 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 (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, which you can utilize by subscribing to any event 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.
Getting Started
To begin, ensure that you have installed Appwrite and Appwrite CLI. 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. 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.
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:
Now, you can access the Appwrite console by navigating to your browser with the URL and port number you specified at http://localhost:5000. Afterward, the signup page will open at http://localhost/auth/signup:
Enter your sign up details and proceed to the console, which opens at http://localhost/console:
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:
Navigate to your Appwrite console at http://localhost:5000/console/ and your project will be visible on the console, and you will have access to all Appwrite services:
Creating the Appwrite Function
Here, you’ll extend your Appwrite server functionality by creating the Appwrite function 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:
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:
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 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 with this command:
cd ./functions/Scheduler
npm i axios
Open the webhook service on your browser and copy the unique URL provided:
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:
To confirm the deployment of your function, navigate to your Appwrite console, click on functions on the sidebar menu, and you should see your deployment:
If the function doesn’t trigger automatically, go to the settings tab for the Functions and click the update button:
Click on the “View as JSON” link right-hand-side to view the schedule configuration for the function:
Navigate to your webhook service to view the incoming requests, which happens after every successful execution of the Appwrite function:
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
- Docker compose documentation