Back

Functions typing (server code)

  • 0
  • Functions
maru
27 Apr, 2024, 19:23

Taking this example on how to build a Function in JS from the docs:

TypeScript
export default async ({ req, res, log }) => {

    switch (req.query.type) {
        case 'empty': 
            return res.empty();
        case 'json':
            return res.json({"type": "This is a JSON response"});
        case 'redirect':
            return res.redirect("https://appwrite.io", 301);
        case 'html':
            return res.send(
                "<h1>This is an HTML response</h1>", 200, {
                    "content-type": "text/html"
                });
        default:
            return res.send("This is a text response");
    }
}

I wonder if there's some documentation on the typing of req, res and log? Or even better a dependency I can pull in for it... I actually develop in TypeScript and use Bun for execution, and not having any typing is hard. E.g. can I pass a status code to res.json()? Which parameter would it be? Will it always be the second one? Can I always send headers on the third parameter? What's the fourth parameter?

TL;DR
Developers want to add typing for `req`, `res`, and `log` in their server code. They use TypeScript and Bun for execution. They are unsure about passing parameters like status code in `res.json()` and headers in the third parameter. They seek documentation or a dependency for this. **Solution:** Incorporate TypeScript declaration files for proper typing. For instance, create a `types.d.ts` file where you can declare the types for `req`, `res`, and `log`. This way, you can have the necessary types even in a JavaScript project.
maru
27 Apr, 2024, 19:37

I found a comment in one of the projects, which hints to types, but it's a comment (not code or types) and it's not complete: https://github.com/appwrite/functions-starter/blob/main/node-18.0/src/index.js

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more