Introduction
Modern web applications are becoming increasingly complex. To manage this complexity, it’s important to have a well-defined architecture. In this article, I’ll walk you through the architecture of a full-stack application that I built, using a monorepo, PostGraphile, and Graphile Worker.
The Monorepo Advantage
A monorepo is a single repository that contains the code for multiple projects. In this case, the monorepo contains the code for the database schema, the web app, and the worker. This has several advantages:
- Simplified dependency management: All the projects share the same
node_modulesdirectory, which makes it easy to manage dependencies. - Improved code sharing: It’s easy to share code between the different projects.
- Atomic commits: Changes to multiple projects can be made in a single commit.
Separation of Concerns
The application is divided into three main parts:
- The database schema: The database schema is defined in a separate project. This makes it easy to manage the schema and to generate a GraphQL API from it.
- The web app: The web app is a React application that consumes the GraphQL API.
- The worker: The worker is a background process that runs long-running tasks.
graph TB
subgraph "Monorepo Structure"
subgraph "Database Layer"
Schema[PostgreSQL Schema]
Migrations[Migrations]
end
subgraph "Web Application"
React[React Frontend]
URQL[URQL GraphQL Client]
end
subgraph "Worker Layer"
Worker[Graphile Worker]
Tasks[Background Tasks]
end
subgraph "API Layer"
PostGraphile[PostGraphile Server]
end
end
Schema -->|Auto-generates| PostGraphile
PostGraphile -->|GraphQL API| URQL
URQL --> React
PostGraphile -->|Enqueues Jobs| Worker
Worker -->|Executes| Tasks
Tasks -->|Updates| Schema
PostGraphile: The Instant GraphQL API
PostGraphile is a tool that automatically generates a GraphQL API from a PostgreSQL database schema. This is a huge time-saver, as it means that you don’t have to write any boilerplate code for the API.
The web app uses urql to connect to the PostGraphile API. urql is a lightweight and extensible GraphQL client that provides features like caching and authentication.
Graphile Worker: The Background Job Queue
Graphile Worker is a job queue for PostgreSQL that allows you to run background jobs. This is useful for tasks that are too long-running to be done in a web request, such as sending emails or processing images.
The worker is a separate process that connects to the same database as the web app. It listens for new jobs and executes them in the background.
Conclusion
This architecture has proven to be very effective for building complex, full-stack applications. The monorepo makes it easy to manage the code, and the separation of concerns between the database schema, the web app, and the worker makes the application easy to understand and maintain. PostGraphile and Graphile Worker are powerful tools that can save you a lot of time and effort.
Tags