Deno + Appwrite

asiancat54x

0xsapphir3

Posted on October 22, 2021

Deno + Appwrite

Hi there!

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

Deno + Appwrite

Setting up

You should have cli version of deno installed.


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";
Enter fullscreen mode Exit fullscreen mode
  1. Create a Appwrite client

const client = new sdk.Client()

  1. 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

Enter fullscreen mode Exit fullscreen mode
  1. Create a instance of the Function class
const functions = new sdk.Functions(client)
Enter fullscreen mode Exit fullscreen mode

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

Creating function

Create

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)
})

Enter fullscreen mode Exit fullscreen mode

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
  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 in appwrite's console.

You should see a new function being created!

Output


Listing all the functions

Listing

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
    })
})
Enter fullscreen mode Exit fullscreen mode

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.

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
Enter fullscreen mode Exit fullscreen mode

Getting functions

Image description

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}`)
})
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Updating functions

Update

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)
})
Enter fullscreen mode Exit fullscreen mode

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

Deleting functions

Delete

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

functions.delete("6172d8bc57f89").then(() => {
    console.log("Successfully deleted")
})
Enter fullscreen mode Exit fullscreen mode

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


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")
})
Enter fullscreen mode Exit fullscreen mode

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.


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!")
})
Enter fullscreen mode Exit fullscreen mode

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.


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
    }
})
Enter fullscreen mode Exit fullscreen mode

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


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)
})
Enter fullscreen mode Exit fullscreen mode

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.


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")
})
Enter fullscreen mode Exit fullscreen mode

Well, this doesnt require a explanation.


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")
})
Enter fullscreen mode Exit fullscreen mode

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


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
    }
})
Enter fullscreen mode Exit fullscreen mode

The listExecutions function takes in the function id as a param. It returns an list of objects of the executions.
Here is the format of the return value.


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
})
Enter fullscreen mode Exit fullscreen mode

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


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

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

💖 💪 🙅 🚩
asiancat54x
0xsapphir3

Posted on October 22, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Deno + Appwrite
deno Deno + Appwrite

October 22, 2021