Skip to content

mgalen007/BlogAPI

Repository files navigation

Blog API

A REST API for a blog platform built with NestJS, Prisma, PostgreSQL, and JWT-based authentication.

This API currently supports:

  • user registration and login
  • protected user lookup
  • post creation, lookup, update, and deletion
  • comment creation, lookup, update, and deletion
  • tag creation, lookup, update, and deletion
  • role-based access for selected admin-only routes
  • ownership-based access for user, post, and comment resources

All routes are served under the global /api prefix.

Stack

  • NestJS
  • TypeScript
  • Prisma ORM
  • PostgreSQL
  • JWT authentication
  • bcryptjs for password hashing

Project Structure

src/
  auth/         Authentication, login, register, JWT service
  comments/     Comment controllers, DTOs, service
  decorators/   Custom decorators such as roles metadata
  exceptions/   Custom exception classes
  filters/      Exception filters
  guards/       JWT, role, and ownership guards
  posts/        Post controllers, DTOs, service
  prisma/       Prisma service and module
  shared/       Shared types
  tags/         Tag controllers, DTOs, service
  users/        User controllers, DTOs, service

Data Model

The database contains four main models:

  • User
  • Post
  • Comment
  • Tag

User

  • id
  • username
  • email
  • role
  • bio
  • passwordHash
  • createdAt
  • updatedAt

Post

  • id
  • authorId
  • content
  • attachments
  • createdAt
  • updatedAt

Comment

  • id
  • authorId
  • content
  • createdAt
  • updatedAt

Tag

  • id
  • content
  • postId

Roles

The API currently uses two roles:

  • ADMIN
  • USER

Newly created users default to USER.

Authentication

Authentication is token-based.

Register

POST /api/auth/register

Creates a new user account. Passwords are hashed before storage.

Request body:

{
  "username": "alice",
  "email": "alice@example.com",
  "bio": "Software writer",
  "password": "strong-password"
}

Response shape:

{
  "success": true,
  "message": "User created successfully",
  "data": {
    "id": "uuid",
    "username": "alice",
    "bio": "Software writer",
    "email": "alice@example.com"
  }
}

Login

POST /api/auth/login

Authenticates a user with username and password, then returns a JWT.

Request body:

{
  "username": "alice",
  "password": "strong-password"
}

Response shape:

{
  "success": true,
  "message": "Successfully logged in",
  "data": {
    "token": "jwt-token"
  }
}

Using the Token

Pass the token in the Authorization header:

Authorization: Bearer <token>

Most routes in this API are protected by JwtAuthGuard.

Authorization Rules

The API currently uses two authorization patterns:

1. Role-based authorization

Some routes require the ADMIN role. These routes use:

  • @Roles(...)
  • RolesGuard

2. Ownership-based authorization

Some routes can only be accessed by:

  • the resource owner
  • or an admin

These routes use ownership guards such as:

  • UserOwnershipGuard
  • PostOwnershipGuard
  • CommentOwnershipGuard

Endpoints

Auth

  • POST /api/auth/register
  • POST /api/auth/login

Users

  • GET /api/users/:id Returns one user. Access: owner or admin.

  • GET /api/users?limit=10 Returns a list of users. Access: admin only.

Posts

  • GET /api/posts/:id Returns one post. Access: post owner or admin.

  • GET /api/posts?limit=10 Returns posts. Access: admin only.

  • POST /api/posts Creates a post for the authenticated user.

  • PUT /api/posts/:id Updates a post. Access: post owner or admin.

  • DELETE /api/posts/:id Deletes a post. Access: post owner or admin.

Comments

  • GET /api/comments/:id Returns one comment. Access: comment owner or admin.

  • GET /api/comments?limit=10 Returns comments. Access: admin only.

  • POST /api/comments Creates a comment for the authenticated user.

  • PUT /api/comments/:id Updates a comment. Access: comment owner or admin.

  • DELETE /api/comments/:id Deletes a comment. Access: comment owner or admin.

Tags

  • GET /api/tags Returns tags for authenticated users.

  • GET /api/tags/:id Returns one tag for authenticated users.

  • POST /api/tags Creates a tag for authenticated users.

  • PUT /api/tags/:id Updates a tag for authenticated users.

  • DELETE /api/tags/:id Deletes a tag. Access: admin only.

Environment Variables

Create an .env file in the api directory.

Required variables:

DATABASE_URL=postgresql://USER:PASSWORD@HOST:PORT/DATABASE
JWT_SECRET_KEY=your-secret-key
BCRYPT_SALT_ROUNDS=10
PORT=3000

Installation

npm install

Database Setup

Generate the Prisma client:

npx prisma generate

Run database migrations:

npx prisma migrate dev

If you already have migrations and only want to apply them:

npx prisma migrate deploy

Running the API

Development

npm run start:dev

Standard start

npm run start

Production build

npm run build
npm run start:prod

Available Scripts

npm run build
npm run format
npm run start
npm run start:dev
npm run start:debug
npm run start:prod
npm run lint
npm run test
npm run test:watch
npm run test:cov
npm run test:e2e

Example Workflow

  1. Register a user with POST /api/auth/register
  2. Log in with POST /api/auth/login
  3. Copy the returned JWT
  4. Send the token in the Authorization header
  5. Create posts or comments as the authenticated user
  6. Use an admin account to access admin-only listing and delete routes

Error Handling

The API uses a mix of:

  • NestJS built-in exceptions
  • custom exceptions such as PostNotFoundException
  • exception filters for selected cases

Examples of possible responses include:

  • 401 Unauthorized
  • 403 Forbidden
  • 404 Not Found
  • 409 Conflict

Notes About Current Behavior

  • all routes are prefixed with /api
  • post and comment creation use the authenticated user as the author
  • the JWT payload includes id, username, email, and role
  • Prisma is used directly inside service classes

Future Improvements

Possible next improvements for this API:

  • add Swagger or OpenAPI documentation
  • add pagination metadata to list endpoints
  • add refresh tokens
  • improve request validation globally
  • standardize all error response shapes
  • expand automated test coverage

License

This project has an MIT license.

About

A blogging API built with NestJS + Prisma. It lets you create posts, add tags, and comment on other posts.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors