GithubHelp home page GithubHelp logo

dcefram / fs-routes Goto Github PK

View Code? Open in Web Editor NEW
0.0 3.0 0.0 296 KB

Create routes based on the file structure. Works with fastify, express, polkajs, or anything that has the same express-like syntax. Inspired by Next.js' approach for its routes.

TypeScript 80.39% JavaScript 19.61%
router routes nodejs fastify express polka

fs-routes's Introduction

fs-routes

Inspired by Vercel's Nextjs approach to pages. Also inspired by the "original" fs-router for Micro.

I initially made this for Polka, but it also worked for my newer fastify-based projects when that became a thing.

Features

  • Structure route handlers like serverless functions/lambdas
  • Zero dependencies
  • Zero configuration
  • Path segments

Installation

npm i @dcefram/fs-routes

Usage

In your entry file where you created your fastify, polka, or express app:

import Fastify from "fastify";
import fsRoutes from "@dcefram/fs-routes";
const fastify = Fastify({ logger: true });

fsRoutes(fastify, "/routes").listen(process.env.PORT, (error) => {
  if (error) throw error;

  console.log(`API Server running at port ${process.env.PORT}`);
});

Folder structure of your app:

your-app
├── index.js # assuming that this is where you initialized your fastify app
└── routes
    └── user
        ├── [slug]
        │   ├── images.js
        │   └── comments.js
        └── [slug].js

Each routes file should have a module.exports that exports an object that contains the handlers. Here's an example:

const httpErrors = require("http-errors");

module.exports = {
  get: (request, reply) => {
    const { slug } = req.params;
    reply.send({ slug });
  },
  put: (request, reply) => {
    reply.send(httpErrors.NotImplemented());
  },
  delete: (request, reply) => {
    reply.send(httpErrors.NotImplemented());
  },
};

It could also export the handlers using the ESM format:

// OR export
export function get(request, reply) {
  const { slug } = req.params;
  reply.send({ slug });
}

export function put(request, reply) {
  reply.send(httpErrors.NotImplemented());
}

export function delete(request, reply) {
  reply.send(httpErrors.NotImplemented());
}

With the folder structure above, you'll get the following endpoints:

GET /user/:slug
PUT /user/:slug
DELETE /user/:slug
GET /user/:slug/images # assuming that images.js has only `get` exported
GET /user/:slug/comments # assuming that comments.js has only `get` exported

### Ignore Files

By default, fs-routes will ignore all files that is prefixed with an underscore (`_`). Example:

```bash

your-app
├── index.js
└── routes
    └── user
        ├── _helpers        # This folder will be ignored
        │   └── some-reusable-logic.js
        ├── [slug]
        │   ├── images.js
        │   ├── comments.js
        │   └── _utils.js    # This file will be ignored
        └── [slug].js

You can overwrite the ignore pattern, and supply it with your own. Example:

import Fastify from "fastify";
import fsRoutes from "@dcefram/fs-routes";

const fastify = Fastify({ logger: true });
const ignorePattern = "\\.internal\\."; // Will ignore files and folders with ".internal." in its name

fsRoutes(fastify, "/routes", { ignorePattern }).listen(
  process.env.PORT,
  (error) => {
    if (error) throw error;

    console.log(`API Server running at port ${process.env.PORT}`);
  }
);

Why make this?

I liked how easy it was to navigate through a Next.js-based project. But there are times that we simply want to ship a pure Node.js API without the frontend, and this is one of the building blocks that I made to make sure that I stay happy building the project.

fs-routes's People

Contributors

dcefram avatar dependabot[bot] avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.