Building Custom Cloud Functions using NodeJS with Appwrite!
Tags: appwrite, node, opensource, cloud
Published: 2022-03-02 17:02:18

As mentioned in the [0.13 release announcement](https://dev.to/appwrite/announcing-appwrite-013-with-major-upgrades-to-storage-and-functions-3hpf), functions in [Appwrite](https://appwrite.io) have gotten much better and faster! Asynchronous and synchronous functions, faster runtimes, and automated dependency management are just a few of the new features. 

This post shows you how to use Appwrite functions to generate memes from Giphy based on chat messages with NodeJS.

## 🤖 Installing the Appwrite CLI

The quickest way to create, manage, and deploy functions is with the Appwrite CLI. You can install the Appwrite CLI globally from the npm package using the command below:

```sh
npm i -g appwrite-cli
```

To use the Appwrite CLI as a locally installed package, install it as a dependency:

```sh
npm install appwrite-cli --save-dev
```

And use the `npx` command to invoke it:

```sh
npx appwrite
```

To verify the installation, open a new terminal and enter the following command:

```sh
npx appwrite --version
```

After the CLI is set, you’re ready to create an Appwrite function!

## ⏺ Setting Up A Function Trigger 

Functions can be triggered by any Appwrite system event, by CRON on a schedule, with an API call, or manually. We’ll be using a collection of chat messages to trigger functions. In your Appwrite instance, create a **chat** collection with the following attributes.

String attributes

| key     | size | required | array |
|---------|------|----------|-------|
| user    | 25   | true     | false |
| room    | 25   | true     | false |
| message | 280  | true     | false |

URL attributes

| key     | size | required | array |
|---------|------|----------|-------|
| meme    | -    | false    | false |

![Collection Attributes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v9tzmgvqwau1uen18rns.png) 

You can define a collection with whatever fields you need, but in this case, we’re keeping it simple. We’re storing the name of the user, the message, and a meme field that is populated by the function after the new message is added to the collection.

Next, let's create a function!

## 💡 Creating a function 

Functions can be stored alongside your project code, whether it be a frontend or backend application. To start, initialize an Appwrite function:

```sh
appwrite init function
```

* Enter **message** for the function name:
* There are many runtimes available for functions, but for this function, choose **node-17.0** from the list.

This creates a new function in your Appwrite instance. There is also a generated JavaScript file with a stub script to start with.

{% gist https://gist.github.com/brandonroberts/94918e4f8fe90f3880e8561ef489b787 %}

Functions are very flexible in that can handle extra processing for items in your database, storage, and more. For this function, we will parse the message data, send it to Giphy and update the **meme** attribute with the first result.

A basic README is also generated inside the function folder for your documentation. Here you should explain what function does, what its inputs are, what the schema of the input is, outputs, triggering events, and more. Keeping this README up to date is important for giving developers context about the function.

First, let’s add the **node-fetch** and **Giphy** libraries  the `dependencies` in the package.json for the function.

{% gist https://gist.github.com/brandonroberts/dcaf73ab9594294ebcf7f3c54e5e9bab %}

During the build process of the function inside of Appwrite, it installs dependencies automatically based on what’s in the **package.json**, so no manual installation is necessary.

## 📝 Defining The Function 

Now let’s update the **index.js** to parse the event from the Appwrite database insert.

{% gist https://gist.github.com/brandonroberts/f75923b0b3aa685b5942aa00fba05d44 %}

The function receives a number of environment variables upon execution. The **APPWRITE_FUNCTION_EVENT_DATA** contains the information about the newly inserted document. That data is parsed into an object, and the **message** property is used along with the Giphy SDK to search for the relevant gif.

## Adding Environment Variables and Event Triggers

Before deploying the function, configure the necessary environment variables and Appwrite events. In this case, we’ll need to configure the API Key for Giphy, the Appwrite function endpoint, and the Appwrite API Key. For added security, all environment variables are internally stored and encrypted.

![Environment Variables](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qrfwoh3cq00aqg5ueuvp.png)

**GIPHY_API_KEY** - Visit the **[Giphy Developer Documentation](https://developers.giphy.com/dashboard/)** to obtain an API key.

**APPWRITE_FUNCTION_ENDPOINT** - The function endpoint can be found on the settings page for your Appwrite project.

**APPWRITE_FUNCTION_API_KEY** - API keys are generated from within your Appwrite console, along with the permissions they provide for a given function. The **documents.write** scope is the only scope needed to update a collection item. 

Almost every action from the Appwrite Console is also available from the API. Read more about them in our [functions guide](https://appwrite.io/docs/client/functions).

Go to the settings of your function, choose the **database.documents.create** event, add the environment variables, and save the changes.

![Appwrite Events](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9y7wpvn4pv2cmec0w7ss.png)

## 🚛 Deploying a Function 

After the function is configured, let’s deploy the code for the function to Appwrite. Deploying the function can be done either with the Appwrite CLI, or through the Appwrite Console. 

Visit the overview page for the function, and copy the functionId. Use the functionId along with the Appwrite CLI to deploy the functions to your Appwrite instance.

```sh
appwrite deploy function
```

After you follow the prompts, the function is deployed, activated, and ready for use!

## 🚀 Triggering a Function 

To trigger the newly deployed function, go to the **chat** collection, and add a new document. After the document is added, the function is executed, and the **meme** property of the document is updated. You could also perform more processor-heavy tasks here such as image or video clip manipulation. Other tasks such as email notifications can be done also using functions.

Functions can also be executed directly from the Appwrite Console, along with viewing and monitoring them for execution results.

## 📃 Summary 

Appwrite Functions allow you to extend the functionality of Appwrite in any number of ways. Functions can be written in one of many available languages and runtimes supported natively inside Appwrite. We’re always looking at adding support for additional languages and runtimes also. You’re only limited by your imagination when using functions with Appwrite 😉.

The following resources can help you learn more about Appwrite:

🚀 [Getting Started Tutorial](https://appwrite.io/docs/getting-started-for-server)
🚀 [Appwrite GitHub](https://github.com/appwrite/appwrite)
📜 [Appwrite Docs](https://appwrite.io/docs)
💬 [Discord Community](https://discord.gg/appwrite)

If you liked this, click the :heart: so other people will see it. Follow [Brandon Roberts](https://twitter.com/brandontroberts) and [Appwrite](https://twitter.com/appwrite) on Twitter for more updates!

## Credits

Photo by <a href="https://unsplash.com/@ilumire?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Jelleke Vanooteghem</a> on <a href="https://unsplash.com/s/photos/cloudy?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>