Deno + Appwrite
Tags: deno, javascript, appwrite
Published: 2021-10-22 17:03:01

Hi there!

This post teaches you how you can use Appwrites Deno SDK to write Appwrite Functions.

![Deno + Appwrite](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i0wr2afc1svawv8j5s68.png)

## Setting up

You should have cli version of deno installed.

<hr>

Let's start learning!

## Importing module and setting up the function API

1. Appwrite has the sdk for deno published to deno land. We can import easily with the help of the package's url:

```
import * as sdk from "https://deno.land/x/appwrite/mod.ts";
```

2. Create a Appwrite client

```const client = new sdk.Client()```

3. Set apiEndpoint , apiKey and projectID

Next, we will require the above mentioned data and set it to the client

```
client.setProject(projectId)
      .setEndpoint(endPoint)
      .setKey(apiKey

```

4. Create a instance of the Function class

```
const functions = new sdk.Functions(client)
```

Now that we have imported the import, we will start interacting with the Appwrite's functions API.


## Creating function

![Create](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/je2iib1733h885cre29q.png)

Lets first get started by creating a function. Now, creating a function is pretty simple. You just need to run a method and pass all the data for your new function

```
functions.create("foo" , ["*"] , "node-16.0").then(() => {
    console.log("Successfully created a new function")
})
.catch((error) => {
    console.log("Error while creating a new function.")

    console.log(error)
})

```

Okay, lets understand the code line by line:

`functions.create("foo" , ["*"] , "node-16.0").then(() => {` - This line calls the function that creates the function. The parameters are the following:

1. Name - The first parameter states the name of the function. You can give it a name of your choice
2. Permissions - The second parameter takes in a list of permission that you will allow your function. "*" means all the function. You can find a list of all the permission [here](https://appwrite.io/docs/permissions)
3. Runtime - The third parameter takes in the excecution runtime. It can be one of the following - java-16.0 (Java), python-3.9 (Python), ruby-3.0 (Ruby), php-8.0 (PHP), node-16.0 (Typescript / JavaScript)

The next line is printing to console telling that the function was created successfully.

Now, run the code by running `deno run --allow-net main.js` and then go ahead to [Function tab](http://localhost:4003/console/functions?project=6172d13cf302d) in appwrite's console.

You should see a new function being created!

![Output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qaomuyvyn7qmogc0ahfv.png)

<hr>

## Listing all the functions

![Listing](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/umh88d8hemhybj7ndybi.png)

Now, at some point of time you will require to print all the available functions. Here is how to you do it:

```
functions.list().then((res) => {
    let index = 0

    res.functions.forEach((_function) => {
        console.log(`${index}: ${_function.name}`)

        index += 1
    })
})
```

What is happening here?

So the first line basically fetches all the functions which are registered in our database. Next, we are iterations over all the functions. Each function object looks like [this](https://appwrite.io/docs/models/functionList).

Next, we are just printing the name of each of the function.

Run the file by this command: `deno run --allow-net main.js`

This should give the following output:

```
0: foo
```

<hr>

## Getting functions

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fo9jo8thu2nrf86f14bn.jpg)

You can get the details of a function using the function's id.
Here is how you can do it:

```
functions.get("6172d8bc57f89").then((res) => {
    console.log(`Fetching details for function id ${res.$id}`)
    console.log(`Name - ${res.name}`)
    console.log(`Created at - ${res.dateCreated}`)
    console.log(`Status - ${res.status}`)
    console.log(`Runtime - ${res.runtime}`)
})
```

So, in the first line, we are fetching the function by id. It returns a object with [these] key-value pairs. We then just print some of the properties to the console. The output is like this:

```
Fetching details for function id 6172d8bc57f89
Name - foo
Created at - 1634916540
Status - disabled
Runtime - node-16.0
```

<hr>

## Updating functions

![Update](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dl4bj2ruq9swy4kckguz.jpg)

Now, are you stuck at the place where you want to rename your function? Its easy! Appwrite provies a function to change the function's id , name , runtime etc. Here is how you do it:

```
const newName = "Bar"

functions.update("6172d8bc57f89", newName, ["*"]).then(() => {
    console.log("Successfully renamed the function!")
}).catch((err) => {
    console.log(err)
})
```

So, first we are initiating a variable with the new name of the function.

Next, we are running the function and updating the function. The parameters are as follows:
1. ID - The id of the function that we want to change
2. Name - The new name for this function
3. Permissions - New permissions for this function 
4. Rest - Rest args are not required, you can read those [here](https://appwrite.io/docs/server/functions#functionsUpdate)

<hr>

# Deleting functions

![Delete](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b03brt7xrsg8e2ziv0fk.jpeg)

Got fed up by a function and want to delete it forever, well, its easy!

```
functions.delete("6172d8bc57f89").then(() => {
    console.log("Successfully deleted")
})
```

Well, there isnt anything to explain here. The function name and the parameter describes it. The function delete the function from the database. The parameter is the id of the function.

*Function*

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5v4sk0i9bnqh9y50hfr3.gif)

<hr>

## Creating tags

Now, to create a tag, use the following code:

```
functions.createTag("6172e57d60cc5", "foo", "somepath.tar.gz").then(() => {
    console.log("Successfully created a new tag")
})
```

Now, the first parameter takes in the id of the function (target). The second parameter takes in the name of the code extension command. The last is the path of the zipped code.

<hr>


## Updating tag id

You can set a custom tag id and use them. 

```
functions.updateTag("6172e57d60cc5", "foo-tag").then(() => {
    console.log("Succesfully changed the tag!")
})
```

So, we call the updateTag function. It takes in two parameter - first for the function id while the last for the new name of the tag.

<hr>

## Listing tags

Same as that for the function, we may also require to print all the tags. Here is how you can do it:

```
functions.listTags("6172e57d60cc5").then((res) => {
    let index = 0

    for (const tag of res.tags) {
        console.log(`${index}: ${tag.$id}`)

        index += 1
    }
})
```

So, we are fetching all the tags available in a function. Then we print the id of all the tags.

<hr>

## Getting tag data

Now, we saw how to create tags, list tags, now to fetch a single one?

Here is how you can do it:

```
functions.getTag("6172e57d60cc5", "foo-tag").then((res) => {
    console.log("Tag id is", res.$id)
})
```

The first param is for the function id and the second is for the tag's id. Then we just do a simple console logging.

<hr>

## Deleting tags

Are you even fed up of the tag? Here is how you delete it:

```
functions.deleteTag("6172e57d60cc5", "foo-tag").then(() => {
    console.log("Successfully deleted the tag")
})
```

Well, this doesnt require a explanation. 

<hr>

## Creating executions

After all the tiring work, you now want your application to execute the functions properly.

Here is how you can create execution:

```
functions.createExecution("6172e57d60cc5").then((res) => {
    console.log("Created an excecution")
})
```

So, this creates up an execution of the function with the id which is passed as an argument.

<hr> 

## Listing executions

Now, do you want to get all the current user function execution logs? As always, its simple:

```
functions.listExecutions("6172e57d60cc5").then((res) => {
    let index = 0

    for (const tag of res.executions) {
        console.log(`${index}: ${tag.$id}`)

        index += 1
    }
})
```

The listExecutions function takes in the function id as a param. It returns an list of objects of the executions.
[Here](https://appwrite.io/docs/models/executionList) is the format of the return value.

<hr>

## Getting execution

Last but not the least, get a single execution. Here is how you can do it:

```
functions.getExecution("6172e57d60cc5", "5e5ea5c16897e").then((res) => {
    // Play with the execution object
})
```

So, here you run the function getExecution which takes in the function id as the first parameter and the function id as the second parameter. It returns a execution object with multiple different properties, all about that execution


<hr>

## Conclusion

Thanks for reading this post. I hope that you will have understood how to use the function api with the deno sdk. 

## Github repository

You can get the code [here](https://github.com/AsianCat54x/Deno-Appwrite)

My github account - https://github.com/AsianCat54x