Appwrite Functions with TypeScript

nimit2801

Nimit Savant

Posted on June 24, 2023

Appwrite Functions with TypeScript

What are we covering in this article?

  • Introduction to Appwrite functions
  • Why would you want to use TS with Appwrite functions
  • How to initialize a NodeJs function
  • How to use integrate with typescript

Introduction to Appwrite functions

Appwrite functions are amazing serverless functions introduced by Appwrite used to run in the Appwrite environment on the appwrite cloud or in your self-hosted environment. More on Appwrite Functions could be found here

Why would you want to use TS with Appwrite functions

  • Personally some developers working with other libraries would want to have types integrated in their functions, and that won't be possible in the js version.
  • Also this type checking would really allow the developers to find any silly bugs at compilation time. Because when you're making functions you'd want to upload the functions lesser number of times because it's tedious to debug in runtime in general. And this would really save some silly bugs that you might be doing.
  • While writing complex logic for your backend you would want to have a robust type checking not just for the code interacting with your Appwrite but also the external ones.

How to initialize a NodeJs function

Pre-requisites

  1. You need an account on their beta cloud platform
  2. Create a new project
  3. Get Project ID from the Appwrite Console

    Copying ProjectId from Appwrite Console

  4. Setup Appwrite CLI in your local desktop, for more information refer the docs here

  5. Let's start coding :)

How to use integrate with typescript

  1. Create a folder for your functions

    mkdir Appwrite Functions
    
  2. Init function

    Please initialize your project if you haven't already with appwrite project init before appwrite function init

    appwrite init function
    

    Terminal window with choosing Appwrite function config

  3. Steps to configure from Node.js to Node.js(TS)

    a. Go into the directory

    cd functions/Appwrite Function TS
    

    b. Add tsconfig.json file

    {
      "compilerOptions": {
       "target": "es5",                          
       "module": "commonjs",                    
       "lib": ["es6"],                     
       "allowJs": true,
       "outDir": "build",                          
       "rootDir": "src",
       "strict": true,         
       "noImplicitAny": true,
       "esModuleInterop": true,
       "resolveJsonModule": true
     }
    }
    

    c. Add @types/node and typescript in devDependencies in package.json and a build step in script

    typescript: For transpiling ts to js code in build folder
    @types/node: For getting node types in ts

    "scripts": {
    "build": "tsc src/index.ts  --outDir build"
    },
    ...
    "devDependencies": {
    "@types/node": "^18.16.3",
    "typescript": "^5.0.4"
    }
    

    d. Install all the packages

    yarn #or npm install
    

    e. Create a new file in /src and called index.ts and copy content from index.js and feel free to delete the index.js file or keep feel free to keep it for future reference. At this point your folder structure should look like this

    Folder Structure in VS Code

    f. Make changes to your index.ts to make it ts compatible, your final code should look like this in index.ts

    You'd also need an API for your function to have access to your Appwrite environment, you might have this question so as to why is that so, Appwrite functions are part of the Appwrite environment. Well I had the same doubt and Appwrite team working on this.
    This is important for two reasons

    • We don't know what permission the Appwrite function might need so its better to specify an API key with perfect perms
    • Appwrite function is in general really a backend server only using node-appwrite sdk which in turn needs API key for its working.
    import * as sdk from 'node-appwrite';
    /*
    'req' variable has:
    'headers' - object with request headers
    'payload' - request body data as a string
    'variables' - object with function variables
    'res' variable has:
    'send(text, status)' - function to return text response. Status code defaults to 200
    'json(obj, status)' - function to return JSON response. Status code defaults to 200
    If an error is thrown, a response with code 500 will be returned.
    */
    module.exports = async function (req: any, res: any) {
    const client = new sdk.Client();
    if (
    !req.variables['APPWRITE_FUNCTION_ENDPOINT'] ||
    !req.variables['APPWRITE_FUNCTION_API_KEY']
    ) {
    console.warn(
      'Environment variables are not set. Function cannot use Appwrite SDK.'
    );
    } else {
    client
      .setEndpoint(req.variables['APPWRITE_FUNCTION_ENDPOINT'])
      .setProject(req.variables['APPWRITE_FUNCTION_PROJECT_ID'])
      .setKey(req.variables['APPWRITE_FUNCTION_API_KEY'])
      .setSelfSigned(true);
    }
    res.json({
    areDevelopersAwesome: true,
    });
    };
    

    g. Go one folder up to Appwrite Functions TS Folder where we initialized our code and edit appwrite.json. Change the entry point from src/index.js -> build/index.js

    This basically helps to point at the transpiled ts code in build folder

    ...
    "entrypoint": "build/index.js",
    ...
    

    h. Run the deploy command and stay in the same folder you created called Appwrite Function TS

    🎊 Congratulations your ts function is made, now let's run the deploy command to upload this function on Appwrite cloud/self-hosted cloud

    appwrite deploy function
    

    Your response should look similar to this
    Terminal window showing response of appwrite function deploy

  4. Let's configure Appwrite Function on Console
    a. Now let's configure the Appwrite Function in the web console and add APPWRITE_FUNCTION_API_KEY & APPWRITE_FUNCTION_ENDPOINT

    Appwrite console where we're adding endpoint and api key

    b. Now we will run the function from the console!

    Appwrite console screen for executing the function from console

    c. Goto Executions in your function and check for the latest output

    Appwrite console list screen for function executions

    Appwrite Function output screen

You can find the GitHub code for the above Article here

GitHub logo nimit2801 / Appwrite-Function-TS

This repo helps as a boiler plate to build appwrite functions with ts

Credits

Credits to the graphic designer who made this cover for me

Socials where we can connect

Discord Server: Last Friday's Thing
Twitter: SavantNimit
Instagram: nimit_savant
LinkedIn: nimitsavant
Website: Personal Website

💖 💪 🙅 🚩
nimit2801
Nimit Savant

Posted on June 24, 2023

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

Sign up to receive the latest update from our blog.

Related