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

z-file-router

v1.5.1

Published

file based routing for backend

Downloads

15

Readme

File Based Routing for Express Backend

To install z-file-router, open your terminal and paste the following command

npm i z-file-router
yarn add z-file-router

[!NOTE] I have give example of typescript but the same is applicable for javascript

Your project structure should look like this to enable file based routing

Project/
├── node_modules/
└── src/
|  /* your other folders */
|  ├── services/
|  |  ├── user
|  |  |  ├── index.ts      // required
|  |  |  ├── middleware.ts // optional
|  |  |  ├── model.ts      // optional
|  |  |  └── validate.ts   // optional
|  |  /* other services */
|  └── index.ts // stating point of your app
├── .gitignore
├── package.json
├── package-lock.json
├── README.md
└── tsconfig.json

[!NOTE]

  • There must be a folder named services in same level as main index.ts file for file based routing to work.
  • Service name inside services folder will be the endpoint for calling APIs.
  • Every service must have an index.ts file associated with it.

[!TIP] It is best practice to make a model.ts file for creating DB model for the respective service and a validate.ts file for validating payload. Use library like zod or joi for validating payload

To call one service into another service

z-file-router also gives Services.get() static method to call one service into another service

Services.get('service-name').find(query,req);

Here is your main index.ts file

import express from "express";
import { RouteLoader } from "z-file-router";

const app = express();

new RouteLoader({ app, port: 3000 });

RouterLoader constructor takes following parameter as an object

  • app (express) - this is express function
  • port (number) - port number (default port is 3000)
  • limit (string) - the maximum size of the JSON payload that the server will accept
  • listen (boolean) - false if you want to handle server start by yourself (by default its true, means server will start as soon as you call the RouteLoader constructor)

[!NOTE]

  • app.listen() and middleware express.json() is already handled by the RouteLoader constructor
  • if you have done listen equals false in RouteLoader contructor, you must write your own logic for starting server after calling RouteLoader class

Now create a folders inside services folder and name it as user create index.ts file for it

/services/user/index.ts

export class UserService {
  async find(query: Record<string, any>, req: Record<string, any>) {
    // do your logic here
    return {
      query,
    };
  }

  async get(id: string, query: Record<string, any>, req: Record<string, any>) {
    // do your logic here
    return {
      id,
      query,
    };
  }

  async post(
    body: Record<string, any>,
    query: Record<string, any>,
    req: Record<string, any>
  ) {
    // do your logic here
    return {
      body,
      query,
    };
  }

  async patch(
    id: string,
    body: Record<string, any>,
    query: Record<string, any>,
    req: Record<string, any>
  ) {
    // do your logic here
    return {
      id,
      body,
      query,
    };
  }

  async remove(
    id: string,
    query: Record<string, any>,
    req: Record<string, any>
  ) {
    // do your logic here
    return {
      id,
      query,
    };
  }

  async update(
    id: string,
    body: Record<string, any>,
    query: Record<string, any>,
    req: Record<string, any>
  ) {
    // do your logic here
    return {
      id,
      body,
      query,
    };
  }
}

[!IMPORTANT] Each service's index.ts file will have 6 functions exposed - find, get, post, patch, update, remove | FUNCTION | REQUEST | ENDPOINT | ARGUMENTS | |:---------|:--------|:------------------ |:----------------------| | find | GET | /{service} | query, req | | get | GET | /{service}/:id | id, query, req | | post | POST | /{service}/ | body, query, req | | patch | PATCH | /{service}/:id | id, body, query, req | | update | PUT | /{service}/:id | id, body, query, req | | remove | DELETE | /{service}/:id | id, query, req |

If you want to add middleware in specific route or all route, add a middlware.ts file in the respective service folder

[!NOTE]

  • middleware.ts file is optional.
  • Middleware file name must be middleware.ts for middlewares to get applied.
  • Middleware class must be default exported.

[!IMPORTANT]

  • (all) - to apply middleware to all routes
  • (find, get, post, patch, update, remove) - to apply middleware to respective route

services/user/middleware.ts

import { NextFunction, Request, Response } from "express";

function auth(req: Request, res: Response, next: NextFunction) {
  // do your logic here
  console.log("user auth middleware");
  next();
}

export default class UserMiddleware {
  private all = [auth];
}