npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

appwrouter

v0.1.5-rc.2

Published

A router for appwrite cloud functions

Downloads

92

Readme

Appwrouter

Example of a simple router for Appwrite Cloud Functions with support for middlewares and error handling. Click Me

Table of Contents

Introduction

What is Appwrouter?

Appwrouter is a simple router for Appwrite Cloud Functions. It will help you to create a simple routing system, with support for middlewares and error handling.

Why Appwrouter?

Appwrite Cloud Functions does not have a built-in routing system. Appwrouter will help you to create a simple routing system for your Appwrite Cloud Functions. With Appwrouter, you can easily encapsulate your function logic and route it to the appropriate path. Lastly Appwrite Cloud function does not handle for path parameters (e.g. /user/:id), Appwrouter will help you to handle path parameters.

Features

  • Robust routing system
  • Middleware support
  • Error handling
  • Easy to use
  • Path parameters
  • Redirects
  • Versioning Routes

Installation

npm install appwrouter

for yarn users:

yarn add appwrouter

for pnpm users:

pnpm add appwrouter

for bun users:

bun add appwrouter

Usage

  1. First, create a new instance of Appwrouter. Then register your routes using the get, post, put, patch and delete methods.
import { Appwrouter } from "appwrouter";

const router = new Appwrouter();

router.get("v1", "/", async ({ req, res, log, error, client }) => {
  res.send("Hello World");
});
  1. Initialize the Approuter in the main method of Appwrite Cloud Function.

export default async ({req,res,log,error})={
    return await initialize({
    req,
    res,
    log,
    error,
    onMiddleware: async ({
      req,
      res,
      log,
      error,
      path,
      eventMap,
      eventType,
      method,
      triggeredType,
    }) => {
     ///  In Middleware, you can do some operation for handling the redirect path, or you can do some operation before it proceed to `onNext` function. But after handling the middle make sure to return the `Client` object from Appwrite SDK.
    //  ...
     return client
    },
    onNext: async (req,res,client) => {
      return await router.handleRequest({ req, res, log, error, client });
    },
    onError: (e) => {

      return res.send(
        JSON.stringify({
          message: "Internal server error",
          error: e,
        }),
        500,
        {
          "content-type": "application/json",
        }
      );
    },
  });
}

Appwrouter Instance

get

router.get("v1", "/", async ({ req, res, log, error, client }) => {
  res.send("Hello World");
});

post

router.post("v1", "/", async ({ req, res, log, error, client }) => {
  res.send("Hello World");
});

put

router.put("v1", "/", async ({ req, res, log, error, client }) => {
  res.send("Hello World");
});

patch

router.patch("v1", "/", async ({ req, res, log, error, client }) => {
  res.send("Hello World");
});

delete

router.delete("v1", "/", async ({ req, res, log, error, client }) => {
  res.send("Hello World");
});

handleRequest

The third parameter of route handler is an function which will be called when the route is matched. The function will receive an object with the following properties:

  • req: The request object.
  • res: The response object.
  • log: The log object.
  • error: The error object.
  • client: The Appwrite SDK client object.
router.get("v1", "/", async ({ req, res, log, error, client }) => {
  res.send("Hello World");
});

It recommend to encapsulate the route handler logic in a separate function and pass it as a parameter to the route handler.

import { RouteHandler } from "appwrouter";

const handler: RouteHandler = async ({ req, res, log, error, client }) => {
  res.send("Hello World");
};

router.get("v1", "/", handler);

Please be informed that the handleRequest function should be returned as same how Appwrite cloud function returning a response. For resources on how to return a response in Appwrite cloud function, please refer to the Appwrite Cloud Function Response documentation.

Versioning Routes

In Appwrouter, you can indicate the version of the route by passing the version as the first parameter of the route handler.

router.get("v1", "/", async ({ req, res, log, error, client }) => {
  res.send("Hello World");
});

Why versioning routes? Versioning routes is a good practice to maintain backward compatibility. By versioning your routes, you can easily maintain multiple versions of the same route.

Initialization of Appwrouter

onMiddleware

In onMiddleware function, you can do some operation for handling the redirect path, or you can do some operation before it proceed to onNext function. But after handling the middle make sure to return the Client object from Appwrite SDK.

onMiddleware: async ({
  req,
  res,
  log,
  error,
  path,
  eventMap,
  eventType,
  method,
  triggeredType,
}) => {
  //  In Middleware, you can do some operation for handling the redirect path, or you can do some operation before it proceed to `onNext` function. But after handling the middle make sure to return the `Client` object from Appwrite SDK.
  //  ...
  return client;
},
OnMiddleware Passed Parameters

The onMiddleware function have the following parameters:

  • req: The request object.
  • res: The response object.
  • log: The log object.
  • error: The error object.
  • method: The HTTP method of the request. For example, GET, POST, PUT, PATCH, DELETE.
  • triggeredType : The type of the trigger. For example, http, schedule, event.
  • eventType : The type of the event. For example, create, update, delete. This parameter is only available when the triggeredType is event. It means that this could be a undefined value.
  • eventMap : The event map object. This parameter is only available when the triggeredType is event. It means that this could be a undefined value. In the x-appwrite-event header, it contains a string, for example, databases.[id].collections.[id].documents.[id].create. This string will be converted to an object. For example, eventMap will be
{
  'databases': '[id]',
  'collections': '[id]',
  'documents': '[id]'
}

onNext

In onNext function, you can call the handleRequest function from the Appwrouter instance.

onNext: async (req,res,client) => {
  return await router.handleRequest({ req, res, log, error, client });
},

onError

This function will be called when an error occurs in the Appwrite Cloud Function.

onError: (e) => {
  return res.send(
    JSON.stringify({
      message: "Internal server error",
      error: e,
    }),
    500,
    {
      "content-type": "application/json",
    }
  );
},

Redirects

In Appwrouter, can handle redirects by using the redirect method from Appwrouter package. If you want a redirect or manipulating the default path that given by Appwrite Cloud Function, then handle the redirect path in onMiddleware function.

redirect(req, "/v1/some/other/path");

In Example usage:

onMiddleware: async ({
     req,
      res,
      log,
      error,
      path,
      eventMap,
      eventType,
      method,
      triggeredType,}) => {
        if (triggeredType === "event" && path === "/" && method === "POST") {
        if (eventType === "update") {
          log(`Event map: ${JSON.stringify(eventMap)}`);

          if (
            eventMap["collections"] === "<COLLECTION_ID>" &&
            eventMap["documents"]
          ) {
            log('Redirecting to "/v1/some/other/path"');

            // Here we are redirecting to another path
            redirect(req, "/v1/some/other/path");
          }
        } else if (eventType === "create") {
          if (eventMap["users"]) {
            log('Redirecting to micro service "/v2/micro/users"');

            /// Here we are redirecting to another path
            redirect(req, "/v2/micro/users");
          }
        }
      }
  }
  return client;
},

Path Parameters

In Appwrite Cloud Function, it already gives you how to get the query parameters by using req.query object. But it does not handle the path parameters. In Appwrouter, you can handle the path parameters by using the req.params object.

router.get("v1", "/user/:id", async ({ req, res, log, error, client }) => {
  const { id } = req.params;
  res.send(`User ID: ${id}`);
});

License

MIT