Appwrite Functions with TypeScript
Tags: appwrite, functions, typescript, dxftw
Published: 2023-06-24 03:30:00

### 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](https://appwrite.io/docs/functions)

### 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](https://cloud.appwrite.io)
2. Create a new project
3. Get Project ID from the Appwrite Console

    ![Copying ProjectId from Appwrite Console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kk95l73wswvv00i27one.png)
4. Setup Appwrite CLI in your local desktop, for more information refer the [docs here](https://appwrite.io/docs/command-line)

5. Let's start coding :)

### How to use integrate with typescript

1. Create a folder for your functions
    ```bash
    mkdir Appwrite Functions
    ```
2. Init function
> Please initialize your project if you haven't already with `appwrite project init` before `appwrite function init`
    ```bash
    appwrite init function
    ```

    ![Terminal window with choosing Appwrite function config](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n5d94atnf3t2yzmal7fe.jpg)


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

    a. Go into the directory
    ```bash
    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
    ```json
  "scripts": {
    "build": "tsc src/index.ts  --outDir build"
  },
...
  "devDependencies": {
    "@types/node": "^18.16.3",
    "typescript": "^5.0.4"
  }
    ```
    d. Install all the packages
    ```bash
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x0uld84dxn9xdufs3zcc.png)

    
    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.
    ```ts
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
    ```json
...
   "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
    ```bash
appwrite deploy function
    ```
    Your response should look similar to this
        ![Terminal window showing response of appwrite function deploy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0hbbf110oeqoiau4yn15.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x1lsk2o20an3ojcxkbou.png)

    b. Now we will run the function from the console! 
    
      ![Appwrite console screen for executing the function from console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tscbht1ngog0dywbhmz4.png)

    c. Goto Executions in your function and check for the latest output
    
      ![Appwrite console list screen for function executions](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8s4m73ojwykgjhd3s0av.png)

      ![Appwrite Function output screen](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/45r1z4qtclch3qjxmy19.png)



You can find the GitHub code for the above Article here
{% github nimit2801/Appwrite-Function-TS %}




#### Credits
Credits to the graphic designer who made this cover for me
#### Socials where we can connect
Discord Server: [Last Friday's Thing](https://discord.gg/BB5AqebMgk)
Twitter: [SavantNimit](https://twitter.com/SavantNimit)
Instagram: [nimit_savant](https://instagram.com/nimit_savant)
LinkedIn: [nimitsavant](https://www.linkedin.com/in/nimitsavant)
Website: [Personal Website](https://nimitsavant.me)