Coder Social home page Coder Social logo

marcoturi / fastify-boilerplate Goto Github PK

View Code? Open in Web Editor NEW
45.0 2.0 0.0 2.68 MB

Fastify application boilerplate based on clean architecture, domain-driven design, CQRS, functional programming, vertical slice architecture for building production-grade applications ๐Ÿš€

License: MIT License

JavaScript 27.51% Shell 0.12% TypeScript 70.41% Gherkin 1.96%
backend clean-architecture cqrs ddd fastify graphql hexagonal-architecture mercurius nodejs onion-architecture typescript bdd cucumber vitest functional-programming

fastify-boilerplate's Introduction

Fastify Boilerplate Logo

code style: prettier Commitizen friendly MIT License GitHub Actions Workflow Status GitHub Actions Workflow Status

This meticulously crafted boilerplate serves as a solid foundation for building production-ready Fastify applications. While designed specifically for Fastify, the underlying principles and best practices aim to be adaptable to different frameworks and languages. These principles include clean architecture, domain-driven design, CQRS, vertical slice architecture, and dependency injection.

โšก Features

๐Ÿ‘‰ Table of Contents

โœจ Getting Started

npx degit marcoturi/fastify-boilerplate my-app
cd my-app

# To enable yarn 4 follow the instruction here: https://yarnpkg.com/getting-started/install
yarn #Install dependencies.

Common Commands

  • yarn start - start a development server.
  • yarn build - build for production. The generated files will be on the dist folder.
  • yarn test - run unit and integration tests.
  • yarn test:coverage - run unit and integration tests with coverage.
  • yarn test:unit - run only unit tests.
  • yarn test:coverage - run only integration tests.
  • yarn test:e2e - run E2E tests
  • yarn type-check - check for typescript errors.
  • yarn deps:validate - check for dependencies problems (i.e. use route code inside a repository).
  • yarn outdated - update dependencies interactively.
  • yarn format - format all files with Prettier.
  • yarn lint - runs ESLint.
  • yarn create:env - creates and .env file by copying .env.example.
  • yarn db:create-migration - creates a new db migration.
  • yarn db:migrate - start db migrations.
  • yarn db:create-seed - creates a new db seed.
  • yarn db:seed - start db seeds.

๐Ÿงฑ Principles

Fastify Boilerplate Diagram adapted from here

Project Principles

  • Adaptable Complexity: The structure should be flexible (scalable through adding or removing layers) to handle varying application complexities.
  • Future-Proofing: Technology and design choices should ensure the project's long-term health. This includes: clear separation of framework and application code and utilizing well-established, widely used packages/tools with minimal dependencies.
  • Functional Programming Emphasis: Prioritize functional programming patterns and composition over object-oriented approaches (OOP) and inheritance for potentially improved maintainability.
  • Microservices-Ready Architecture: Leveraging techniques like vertical slice architecture, path aliases, and CQRS (Command Query Responsibility Segregation) for communication. This promotes modularity and separation of concerns, facilitating potential future extraction and creation of microservices.

Code Principles

  • Framework Agnostic: Using vanilla Node.js, express, fastify? Your core business logic does not care about that either. Therefore, we will minimize fastify dependencies inside modules folder.
  • Client Interface Agnostic: The core business logic does not care if you are using a CLI, a REST API, or even gRPC. Command/Query handlers will serve every protocol needs.
  • Database Agnostic: Your core business logic does not care if you are using Postgres, MongoDB, or CouchDB for that matter. Database code, problems and errors should be tackled only in repositories.
  • The dependencies between software components should always point inward towards the core of the application. In other words, the innermost layers of the system should not depend on the outer layers. The flow of the code will be Route โ†’ Handler โ†’ Domain (optional) โ†’ Repository.

This project is based on some of the following principles/styles:

Modules

  • Each module's name should reflect an important concept from the Domain and have its own folder (see vertical slice architecture).
  • It's easier to work on things that change together if those things are gathered relatively close to each other (see The Common Closure Principle (CCP)).
  • Every module is independent (i.e. no direct imports) and has interactions between modules minimal. You want to be able to easily extract a module into a separate microservice if needed.

How do I keep modules clean and decoupled between each one?

  • One module shouldn't call other module directly (for example by importing an entity from module A to module B). You should create public interfaces to do so (for example, create a query that returns some data from feature A to anyone who calls it, so module B can query it).
  • In case of fire and forget logic (like sending an email after some operation), you can use events to communicate between modules.
  • If two modules are too "chatty", maybe they should be merged into a single module

Module Components

Each layer should handle its own distinct functionality. Ideally, these components should adhere to the Single Responsibility Principle, meaning they have a single, well-defined purpose:

Route: The process starts with a request (HTTP, GRPC, Graphql) sent to the route. You can find the routes in the src/modules/feature/{commands|queries} folder. Routes handle HTTP request/response, request validation, and response formatting based on the type of protocol implied. They should not contain any business logic.

Example file: find-users.route.ts

Command/Query Handler: The Command or Query Handler, or an application Service handles the received request. It executes the necessary business logic by leveraging Domain Services. It also interacts with the infrastructure layer through well-defined interfaces (ports). Commands are state-changing operations and Queries are data-retrieval operations. They do not contain domain-specific business logic. One handler per use case it's generally a good practice (e.g., CreateUser, UpdateUser, etc.).

Note: instead of using handler you can also use an application service to handle commands/queries/events.

Using this pattern has several advantages:

  • You can implement middlewares in between the route and the handler. This way you can achieve things like authorization, rate limiting, caching, profiling, etc. It's easy to granular apply these middlewares to specific commands/queries by using simple regex i.e. by looking at users/* if you want to hit every command in the user module or users/create for specific ones. Example file: middlewares.ts
  • Reduce coupling between modules. Instead of explicitly defining dependencies between modules you can use commands/queries. At the moment you want to extract a module into a separate microservice you can just implement the GRPC request logic in the handler, and you are good to go.

Example file: find-users.handler.ts

Domain Service: Contains the core business logic. For example, how to compose a new entity, calculate its own properties and how to change them. In this specific project there are no entities/aggregates classes (see Domain-Driven Design) and data is generally composed by objects/arrays/primitives therefore domain services are the responsible for handling the surrounding business. The domain should represent (in code) what the business is or does (in real life).

Example file: user.domain.ts

Repository: Adapts data to its internal format, retrieves or persists data from/to a database as needed. Repositories decouple the infrastructure or technology used to access databases from the other layers (i.e. for example handler/domains should not know if the data is stored in a SQL or NoSQL database). They should not contain business logic.

Example file: user.repository.ts

General recommendation: The optimal project structure balances complexity with maintainability. Carefully consider the project's anticipated size and intricacy. Utilize as many layers and building blocks as necessary to ensure efficient development, while avoiding unnecessary complexity.

๐Ÿ—„๏ธ Folder Structure and Code Organization

The vertical slice architecture is the recommended structure. Each feature encapsulates commands, queries, repositories, etc.

.
โ”œโ”€โ”€ db/
โ”‚   โ”œโ”€โ”€ migrations
โ”‚   โ””โ”€โ”€ seeds
โ”œโ”€โ”€ tests
โ””โ”€โ”€ src/
    โ”œโ”€โ”€ config
    โ”œโ”€โ”€ modules/
    โ”‚   โ””โ”€โ”€ feature/
    โ”‚       โ”œโ”€โ”€ commands/
    โ”‚       โ”‚   โ””โ”€โ”€ command-example/
    โ”‚       โ”‚       โ”œโ”€โ”€ command.handler.ts        โ†’ Route command handler/service
    โ”‚       โ”‚       โ”œโ”€โ”€ command.route.ts          โ†’ Fastify http route
    โ”‚       โ”‚       โ”œโ”€โ”€ command.graphql-schema.ts โ†’ Graphql schema
    โ”‚       โ”‚       โ”œโ”€โ”€ command.resolver.ts       โ†’ Graphql resolver
    โ”‚       โ”‚       โ””โ”€โ”€ command.schema.ts         โ†’ Schemas for request and response validation
    โ”‚       โ”œโ”€โ”€ database/
    โ”‚       โ”‚   โ”œโ”€โ”€ feature.repository.port.ts    โ†’ Fastify repository port
    โ”‚       โ”‚   โ””โ”€โ”€ feature.repository.ts         โ†’ Feature repository
    โ”‚       โ”œโ”€โ”€ domain/
    โ”‚       โ”‚   โ”œโ”€โ”€ feature.domain.ts             โ†’ Domain services
    โ”‚       โ”‚   โ”œโ”€โ”€ feature.errors.ts             โ†’ Domain-specific errors
    โ”‚       โ”‚   โ””โ”€โ”€ feature.types.ts              โ†’ Domain-specific types
    โ”‚       โ”œโ”€โ”€ dtos/
    โ”‚       โ”‚   โ”œโ”€โ”€ feature.graphql-schema.ts     โ†’ Common Graphql schema
    โ”‚       โ”‚   โ””โ”€โ”€ feature.response.dto.ts       โ†’ Common DTO definition used across feature commands/queries
    โ”‚       โ”œโ”€โ”€ queries/
    โ”‚       โ”‚   โ””โ”€โ”€ query-example/
    โ”‚       โ”‚       โ”œโ”€โ”€ query.handler.ts          โ†’ Route command handler/service
    โ”‚       โ”‚       โ”œโ”€โ”€ query.graphql-schema.ts   โ†’ Graphql schema
    โ”‚       โ”‚       โ”œโ”€โ”€ query.resolver.ts         โ†’ Graphql resolver
    โ”‚       โ”‚       โ”œโ”€โ”€ query.route.ts            โ†’ Fastify http route
    โ”‚       โ”‚       โ””โ”€โ”€ query.schema.ts           โ†’ Schemas for request and response validation
    โ”‚       โ”œโ”€โ”€ index.ts                          โ†’ Module entrypoint, dependencies definitions, command/query base definition
    โ”‚       โ””โ”€โ”€ feature.mapper.ts                 โ†’ Mapper util to map entities between layers (controller, domain, repositories)
    โ”œโ”€โ”€ server/
    โ”‚   โ””โ”€โ”€ plugins                               โ†’ Fastify plugins
    โ””โ”€โ”€ shared/
        โ”œโ”€โ”€ utils                                 โ†’ Generic functions that don't belong to any specific feature
        โ””โ”€โ”€ db                                    โ†’ DB configuration and helpers

Useful resources

This boilerplate draws inspiration from Domain-Driven Hexagon, but prioritizes functional programming paradigms over traditional Java-style backend practices. Also, while acknowledging the value of Domain-Driven Design (DDD), this project aims for a more approachable structure with a lower knowledge barrier for onboarding new team members. Despite these adjustments, the core principles of Domain-Driven Hexagon remain a valuable resource. I highly recommend exploring it for further knowledge acquisition.

Frontend

react-redux boilerplate: A meticulously crafted, extensible, and robust architecture for constructing production-grade React applications.

Telemetry

While including a specific application instrumentation example is avoided in this project due to configuration and provider variations, I strongly recommend considering OpenTelemetry. It offers significant benefits:

  • Vendor Independence: OpenTelemetry is an open standard, freeing you from vendor lock-in. This flexibility allows you to choose and swap backend tools as needed without rewriting instrumentation code.
  • Simplified Instrumentation: OpenTelemetry provides language-specific SDKs and automatic instrumentation features that significantly reduce the complexity of adding tracing, metrics, and logs to your codebase.
  • Unified Observability: By offering a consistent way to collect and export telemetry data, OpenTelemetry facilitates a more holistic view of your application's performance.
  • Reduced Development Time: OpenTelemetry allows you to write instrumentation code once and export it to any compatible backend system, streamlining development efforts.

Load testing

Load testing is a powerful tool to mitigate performance risks by verifying an API's ability to manage anticipated traffic. By simulating real-world user interactions with an API under development, businesses can pinpoint potential bottlenecks before they impact production environments. These bottlenecks might otherwise go unnoticed during development due to the absence of production-level loads. Example tools:

Client types generation

To generate client types for your API based on you schemas, you can use the following command:

// Be sure to have the server running
npx openapi-typescript http://127.0.0.1:3000/api-docs/json -o ./client.schema.d.ts

With a little effort you can add this process in the pipeline and have a package published with each version of the backend. Same concept apply for graphql schemas using graphql-code-generator.

Contributing

Contributions are always welcome! If you have any ideas, suggestions, fixes, feel free to contribute. You can do that by going through the following steps:

  1. Clone this repo
  2. Create a branch: git checkout -b your-feature
  3. Make some changes
  4. Test your changes
  5. Push your branch and open a Pull Request

License

MIT

fastify-boilerplate's People

Contributors

marcoturi avatar renovate[bot] avatar semantic-release-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

fastify-boilerplate's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

docker-compose
docker-compose.yml
github-actions
.github/workflows/codeql-analysis.yml
  • actions/checkout v4
  • github/codeql-action v3
  • github/codeql-action v3
.github/workflows/release.yml
  • actions/checkout v4
  • actions/setup-node v4
  • actions/setup-node v4
  • actions/upload-artifact v4
npm
package.json
  • @fastify/autoload 5.10.0
  • @fastify/awilix 5.1.0
  • @fastify/cors 9.0.1
  • @fastify/helmet 11.1.1
  • @fastify/request-context 5.1.0
  • @fastify/swagger 8.14.0
  • @fastify/swagger-ui 4.0.0
  • @fastify/type-provider-json-schema-to-ts 3.0.0
  • @fastify/type-provider-typebox 4.0.0
  • @fastify/under-pressure 8.5.0
  • @gquittet/graceful-server 5.1.0
  • @graphql-tools/load-files 7.0.0
  • @graphql-tools/merge 9.0.4
  • @sinclair/typebox 0.32.33
  • ajv-formats 3.0.1
  • awilix 10.0.2
  • env-schema 5.2.1
  • fastify 4.28.0
  • fastify-plugin 4.5.1
  • graphql 16.8.2
  • helmet 7.1.0
  • mercurius 14.1.0
  • pino 9.2.0
  • postgres 3.4.4
  • ramda 0.30.1
  • @commitlint/cli 19.3.0
  • @commitlint/config-conventional 19.2.2
  • @cucumber/cucumber 10.8.0
  • @cucumber/html-formatter 21.3.1
  • @cucumber/messages 25.0.1
  • @cucumber/pretty-formatter 1.0.1
  • @semantic-release/changelog 6.0.3
  • @semantic-release/commit-analyzer 13.0.0
  • @semantic-release/git 10.0.1
  • @semantic-release/github 10.0.6
  • @semantic-release/npm 12.0.1
  • @semantic-release/release-notes-generator 14.0.0
  • @trivago/prettier-plugin-sort-imports 4.3.0
  • @tsconfig/node20 20.1.4
  • @types/node 20.14.7
  • @types/ramda 0.30.0
  • @typescript-eslint/eslint-plugin 7.13.1
  • @typescript-eslint/parser 7.13.1
  • artillery 2.0.15
  • artillery-plugin-faker 5.0.2
  • dbmate 2.17.0
  • dependency-cruiser 16.3.3
  • eslint 8.57.0
  • eslint-config-prettier 9.1.0
  • eslint-plugin-import 2.29.1
  • eslint-plugin-promise 6.2.0
  • eslint-plugin-unicorn 54.0.0
  • husky 9.0.11
  • lint-staged 15.2.7
  • pino-pretty 11.2.1
  • pinst 3.0.0
  • prettier 3.3.2
  • semantic-release 24.0.0
  • ts-node 10.9.2
  • tsc-alias 1.8.10
  • tsconfig-paths 4.2.0
  • tsx 4.15.6
  • typescript 5.4.5
  • vitest 1.6.0
  • node >=20.6.0
  • yarn >=4.0.0
  • yarn 4.3.0
nvm
.nvmrc
  • node 20.*

  • Check this box to trigger a request for Renovate to run again on this repository

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.