GithubHelp home page GithubHelp logo

vanilla-icecream / vite-plugin-fastify-routes Goto Github PK

View Code? Open in Web Editor NEW
4.0 1.0 0.0 333 KB

File-based routing for Fastify applications using Vite.

Home Page: https://vitesheet.onrender.com/vite-plugin-fastify-routes/

License: MIT License

TypeScript 100.00%
fastify vite router

vite-plugin-fastify-routes's Introduction

vite-plugin-fastify-routes

File-based routing for Fastify applications using Vite.

Installation

Install vite-plugin-fastify-routes with your favorite package manager:

$ npm i vite-plugin-fastify-routes -D
# or
$ yarn add vite-plugin-fastify-routes -D
# or
$ pnpm i vite-plugin-fastify-routes -D
# or
$ bun add vite-plugin-fastify-routes -D

Usage

Add Scripts

Add the following scripts to your package.json file:

{
  // ...
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
  },
  // ...
}

Configure Vite

Configure Vite by creating a vite.config.ts file in the root directory of your project, as shown below:

// vite.config.ts
import { resolve } from 'path';
import { defineConfig } from 'vite';
import fastify from 'vite-plugin-fastify';
import fastifyRoutes from 'vite-plugin-fastify-routes';

export default defineConfig({
  server: {
    host: '127.0.0.1',
    port: 3000,
  },
  plugins: [
    fastify(),
    fastifyRoutes(), // Default: { routesDir: './src/routes' }
  ],
  resolve: {
    alias: {
      '~': resolve(__dirname, 'src'),
    },
  },
});

Create the Fastify Application

Create a Fastify application by defining src/app.ts:

// src/app.ts
import type { FastifyServerOptions } from 'fastify';
import fastify from 'fastify';

import router from '~/plugins/router';

const app = async (options: FastifyServerOptions = {}) => {
  const app = fastify(options);

  app.register(router);

  return app;
};

export default app;

Start the Server

Start the server by defining src/server.ts:

// src/server.ts
import app from './app';

const start = async () => {
  const server = await app({
    logger: {
      transport: {
        target: '@fastify/one-line-logger',
      },
    },
  });

  try {
    server.listen({ host: '127.0.0.1', port: 3000 });
  } catch (err) {
    server.log.error(err);
    process.exit(1);
  }
};

start();

Create the Router Plugin

Create the router plugin by defining src/plugins/router.ts:

// src/plugins/router.ts
import plugin from 'fastify-plugin';

import routes from 'virtual:fastify-routes';

export default plugin(
  async (app) => {
    routes(app, { prefix: '/api' });
  },
  { name: 'router' },
);

Type

// vite-env.d.ts
/// <reference types="vite-plugin-fastify-routes/client" />

Define Routes (Route Handlers)

Define routes by creating a +handler.ts (or .js) file in the src/routes directory:

src/routes/path/to/+handler.ts
# or
src/routes/path/to/+handler.js
// src/routes/hello-world/+handler.ts
import type { FastifyInstance } from 'fastify';

export default async (app: FastifyInstance) => {
  // curl http://127.0.0.1:3000/api/hello-world
  app.get('', async (request, reply) => {
    return reply.send({ message: 'hello-world' });
  });
};

Route File Naming Convention

The file naming convention for the routes is as follows:

src/routes/hello-world/+handler.ts -> /hello-world

src/routes/products/+handler.ts -> /products
src/routes/products/[id]/+handler.ts -> /products/:id

src/routes/posts/[[title]]/+handler.ts -> /posts/:title?

src/routes/blog/[...info]/+handler.ts -> /blog/*

src/routes/(group)/foo/+handler.ts -> /foo
src/routes/(group)/bar/+handler.ts -> /bar

src/routes/(freeze)/+handler.ts -> /
// src/routes/path/to/+handler.ts
import type { FastifyInstance } from 'fastify';

export default async (app: FastifyInstance) => {
  // The path parameter can be initialized with an empty string.
  app.get('', async (request, reply) => {
    // Focus on your handler here
  });
};

Define Hooks (Middleware)

Define hooks by creating a +hook.ts (or .js) file in the src/routes directory:

src/routes/path/to/+hook.ts
# or
src/routes/path/to/+hook.js
// src/routes/path/to/+hook.ts
import plugin from 'fastify-plugin';

export default plugin(async (app) => {
  app.addHook('preHandler', async (request, reply) => {
    await new Promise((resolve, reject) => {
      console.log('preHandler');
      resolve('');
    });
  });
});

Hook File Naming Convention

The file naming convention for the routes is as follows:

routes
├── hooked
│   ├── +handler.ts
│   ├── +hook.ts # request.hookOne = 'yes'
│   └── children
│       ├── +handler.ts
│       └── grandchildren
│           ├── +handler.ts
│           └── +hook.ts # request.hookTwo = 'yes'
└── standard
    └── +handler.ts
// src/routes/hooked/+hook.ts
import plugin from 'fastify-plugin';

export default plugin(async (app) => {
  app.addHook('preHandler', async (request, reply) => {
    request.hookOne = 'yes';
  });
});

// src/routes/hooked/children/grandchildren/+hook.ts
import plugin from 'fastify-plugin';

export default plugin(async (app) => {
  app.addHook('preHandler', async (request, reply) => {
    request.hookTwo = 'yes';
  });
});
$ curl http://127.0.0.1:3000/api/hooked
# { hookOne: 'yes', hookTwo: undefined }

$ curl http://127.0.0.1:3000/api/hooked/children
# { hookOne: 'yes', hookTwo: undefined }

$ curl http://127.0.0.1:3000/api/hooked/children/grandchildren
# { hookOne: 'yes', hookTwo: 'yes' }

$ curl http://127.0.0.1:3000/api/standard
# { hookOne: undefined, hookTwo: undefined }

If the hook only needs to be in the current route, it can be placed within +handler.ts:

routes
├── hooked
│   ├── +handler.ts # request.hook = 'yes'
│   ├── +hook.ts # request.hookOne = 'yes'
│   └── children
│       ├── +handler.ts # request.hookChildren = 'yes'
│       └── grandchildren
│           ├── +handler.ts # request.hookGrandchildren = 'yes'
│           └── +hook.ts # request.hookTwo = 'yes'
└── standard
    └── +handler.ts
// src/routes/hooked/+handler.ts
import type { FastifyInstance } from 'fastify';

export default async (app: FastifyInstance) => {
  app.addHook('preHandler', async (request, reply) => {
    request.hook = 'yes';
  });

  app.get('', async (request, reply) => {
    // ...
  });
};

// src/routes/hooked/children/+handler.ts
import type { FastifyInstance } from 'fastify';

export default async (app: FastifyInstance) => {
  app.addHook('preHandler', async (request, reply) => {
    request.hookChildren = 'yes';
  });

  app.get('', async (request, reply) => {
    // ...
  });
};

// src/routes/hooked/children/grandchildren/+handler.ts
import type { FastifyInstance } from 'fastify';

export default async (app: FastifyInstance) => {
  app.addHook('preHandler', async (request, reply) => {
    request.hookGrandchildren = 'yes';
  });

  app.get('', async (request, reply) => {
    // ...
  });
};
$ curl http://127.0.0.1:3000/api/hooked
# { hookOne: 'yes', hookTwo: undefined }
# { hook: 'yes', hookChildren: undefined, hookGrandchildren: undefined }

$ curl http://127.0.0.1:3000/api/hooked/children
# { hookOne: 'yes', hookTwo: undefined }
# { hook: undefined, hookChildren: 'yes', hookGrandchildren: undefined }

$ curl http://127.0.0.1:3000/api/hooked/children/grandchildren
# { hookOne: 'yes', hookTwo: 'yes' }
# { hook: undefined, hookChildren: undefined, hookGrandchildren: 'yes' }

$ curl http://127.0.0.1:3000/api/standard
# { hookOne: undefined, hookTwo: undefined }
# { hook: undefined, hookChildren: undefined, hookGrandchildren: undefined }

vite-plugin-fastify-routes's People

Contributors

shyam-chen avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 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.