https://github.com/darinelescobar/graphql-template-hexagonal-architecture
A boilerplate to kickstart GraphQL APIs using NestJS, Prisma, and MySQL. Includes Docker setup, Prisma migrations and client generation, and an example seed script. Perfect for quickly launching clean, scalable backend projects.
https://github.com/darinelescobar/graphql-template-hexagonal-architecture
api backend boilerplate clean-architecture db-migration docker graphql hexagonal-architecture mysql nestjs prisma template typescript
Last synced: about 2 months ago
JSON representation
A boilerplate to kickstart GraphQL APIs using NestJS, Prisma, and MySQL. Includes Docker setup, Prisma migrations and client generation, and an example seed script. Perfect for quickly launching clean, scalable backend projects.
- Host: GitHub
- URL: https://github.com/darinelescobar/graphql-template-hexagonal-architecture
- Owner: DarinelEscobar
- Created: 2025-04-11T00:01:03.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2025-04-11T00:08:39.000Z (about 1 year ago)
- Last Synced: 2025-04-11T01:20:30.602Z (about 1 year ago)
- Topics: api, backend, boilerplate, clean-architecture, db-migration, docker, graphql, hexagonal-architecture, mysql, nestjs, prisma, template, typescript
- Language: TypeScript
- Homepage:
- Size: 122 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# GraphQL API Template with NestJS, Prisma, and MySQL
This project is a boilerplate to build a GraphQL API using NestJS and Prisma, connected to a MySQL database. It includes a Docker setup for the database and an example `seed` script for initial data population.
---
## π₯ Features (Updated)
- β
JWT Authentication (Access + Refresh Tokens)
- β
Role-Based Access Control using `@Roles` decorator and `RolesGuard`
- β
Create Account and Login mutations with secure password hashing (bcrypt)
- β
Refresh Token Mutation
- β
Public GraphQL Queries: `users`, `user(id)`
- β
Protected Queries:
- `products`: Requires `CHEF` role
- `productsByUser`: Requires `USER` or `CHEF` role
- β
Global Rate Limiting via Throttler (custom `GqlThrottlerGuard`)
## Prerequisites
- [Node.js](https://nodejs.org/en/) (recommended LTS version, 16+)
- [Nest CLI](https://docs.nestjs.com/cli/overview) (optional, for quick scaffolding)
- [Docker and Docker Compose](https://docs.docker.com/compose/) (for the MySQL database)
- [MySQL Workbench](https://www.mysql.com/products/workbench/) or any other DB GUI tool (optional)
---
## Folder Structure (Example)
```
graphql-api-template
βββ docker-compose.yml
βββ .env
βββ package.json
βββ prisma
β βββ schema.prisma
β βββ seed.ts
βββ src
β βββ app.module.ts
β βββ main.ts
β βββ user
β βββ user.module.ts
β βββ user.resolver.ts
β βββ user.service.ts
β βββ user.type.ts
βββ tsconfig.json
βββ ...
```
---
## Environment Variables
In the root directory, create a `.env` file with your database connection URL, for example:
```bash
DATABASE_URL="mysql://root:@localhost:3306/graphql-db"
```
---
## Prisma Setup
### 1. Define the schema in prisma/schema.prisma
```prisma
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
name String
email String @unique
password String
rol String @default("USER")
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
products Product[]
}
model Product {
id Int @id @default(autoincrement())
name String
userId Int
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id])
}
```
### 2. Run Database Migration
```bash
npx prisma migrate dev --name init
```
### 3. Generate Prisma Client
```bash
npx prisma generate
```
### 4. Seed Initial Data
**prisma/seed.ts**
```ts
import { PrismaClient } from '@prisma/client'
import * as bcrypt from 'bcryptjs'
const prisma = new PrismaClient()
async function main() {
const salt = await bcrypt.genSalt(10)
const user = await prisma.user.create({
data: {
name: 'Juan PΓ©rez',
email: 's@user.com',
password: await bcrypt.hash('12', salt),
rol: 'USER',
},
})
const chef = await prisma.user.create({
data: {
name: 'MarΓa Cocina',
email: 's@chef.com',
password: await bcrypt.hash('12', salt),
rol: 'CHEF',
},
})
await prisma.product.createMany({
data: [
{ name: 'Taco Supremo', userId: user.id },
{ name: 'Burrito Deluxe', userId: user.id },
{ name: 'Paella Gourmet', userId: chef.id },
{ name: 'Sopa Azteca', userId: chef.id },
],
})
}
main()
.catch((e) => {
console.error(e)
process.exit(1)
})
.finally(async () => {
await prisma.$disconnect()
})
```
Run the seed:
```bash
npx ts-node prisma/seed.ts
```
---
## Project Setup
```bash
npm install
```
---
## Run the Project
```bash
# development
npm run start
# watch mode
npm run start:dev
# production
npm run start:prod
```
The app will be running at `http://localhost:3000`.
---
## GraphQL Playground
Go to `http://localhost:3000/graphql`.
---
## Example Auth Mutations
### π Create Account
```graphql
mutation {
createAccount(data: { name: "Juan", email: "juan@example.com", password: "1234" }) {
accessToken
userId
rol
refreshToken
}
}
```
### π Login
```graphql
mutation {
login(data: { email: "juan@example.com", password: "1234" }) {
accessToken
userId
rol
refreshToken
}
}
```
### π Refresh Token
```graphql
mutation {
refreshToken(refreshToken: "yourRefreshTokenHere") {
accessToken
userId
rol
refreshToken
}
}
```
## Role-based GraphQL Query Protection
| Query | Roles Required | Description |
|-------------------|----------------|-------------------------------------|
| `users` | β Public | Get all users |
| `user(id)` | β Public | Get user by ID |
| `products` | β
CHEF only | Get all products |
| `productsByUser` | β
USER, CHEF | Get products by user ID |
> β οΈ `products` and `productsByUser` require an `Authorization` header with a valid token. Donβt even try without it:
```json
{
"Authorization": "Bearer YOUR_ACCESS_TOKEN"
}
```
---
## Run Tests
```bash
# unit tests
npm run test
# e2e tests
npm run test:e2e
# test coverage
npm run test:cov
```
---
## Deployment
```bash
npm install -g @nestjs/mau
mau deploy
```
---
## Final Notes
Make sure to customize the `.env` configuration and never commit sensitive credentials. For production, use secret management tools and containerize the API if needed alongside the DB.