A microservice for managing blog posts and content in the NestJS microservices architecture.
- Post Management: Full CRUD operations for blog posts
- User Integration: Integration with Auth Service for user authentication
- Search & Filtering: Advanced search and filtering capabilities
- Pagination: Efficient pagination for large datasets
- Soft Delete: Soft delete functionality with audit trails
- gRPC Microservice: Inter-service communication via gRPC
- REST API: HTTP endpoints for post operations
- Database Integration: PostgreSQL with Prisma ORM
- Caching: Redis-based caching for performance
- Internationalization: Multi-language support with nestjs-i18n
- API Documentation: Swagger/OpenAPI documentation
- Health Checks: Built-in health monitoring
- Security: JWT authentication and authorization
- Framework: NestJS 10.x
- Language: TypeScript 5.x
- Database: PostgreSQL with Prisma ORM
- Cache: Redis with cache-manager
- Authentication: JWT with Passport.js
- API Documentation: Swagger/OpenAPI
- Microservice: gRPC communication
- Validation: class-validator and class-transformer
- Testing: Jest
src/
βββ app/ # Application bootstrap
βββ common/ # Shared modules and utilities
β βββ config/ # Configuration management
β βββ constants/ # Application constants
β βββ decorators/ # Custom decorators
β βββ dtos/ # Data Transfer Objects
β βββ enums/ # Application enums
β βββ filters/ # Exception filters
β βββ guards/ # Authentication guards
β βββ interceptors/ # Response interceptors
β βββ interfaces/ # TypeScript interfaces
β βββ middlewares/ # Request middlewares
β βββ services/ # Shared services
βββ generated/ # gRPC generated code
βββ languages/ # i18n translation files
βββ modules/ # Feature modules
β βββ post/ # Post management module
βββ services/ # External service integrations
β βββ auth/ # Auth service integration
βββ protos/ # gRPC protocol buffers
- Node.js >= 18.0.0
- npm >= 9.0.0
- PostgreSQL
- Redis
- Auth Service (for authentication)
-
Clone the repository
git clone <repository-url> cd post
-
Install dependencies
npm install
-
Environment Configuration Create
.env
and.env.docker
files with the following variables:# App Configuration NODE_ENV=development APP_NAME=NestJS Post Service APP_DEBUG=false APP_CORS_ORIGINS=http://localhost:3000 # HTTP Configuration HTTP_ENABLE=true HTTP_HOST=0.0.0.0 HTTP_PORT=9002 HTTP_VERSIONING_ENABLE=false HTTP_VERSION=1 # Database Configuration DATABASE_URL=postgresql://username:password@localhost:5432/post_db # Redis Configuration REDIS_URL=redis://localhost:6379 REDIS_KEY_PREFIX=post: REDIS_TTL=3600 # gRPC Configuration GRPC_URL=0.0.0.0:50052 GRPC_PACKAGE=post # Auth Service Configuration (for gRPC communication) AUTH_SERVICE_URL=0.0.0.0:50051 # Monitoring (Optional) SENTRY_DSN=your-sentry-dsn
-
Database Setup
# Generate Prisma client npm run prisma:generate # Run migrations npm run prisma:migrate # (Optional) Open Prisma Studio npm run prisma:studio
-
Generate gRPC code
npm run proto:generate
npm run dev
npm run build
npm start
docker build -t post-service .
docker run -p 9002:9002 post-service
GET /posts
- List all posts (paginated)GET /posts/:id
- Get post by ID
POST /posts
- Create new postPUT /posts/:id
- Update postDELETE /posts/:id
- Delete postPOST /posts/bulk-delete
- Bulk delete posts
page
(number): Page number (default: 1)limit
(number): Items per page (default: 10, max: 100)
search
(string): Search in title and contentsortBy
(string): Sort field (default: createdAt)sortOrder
(string): Sort order - 'asc' or 'desc' (default: desc)
authorId
(string): Filter by author IDpage
(number): Page numberlimit
(number): Items per page
GET /health
- Service health statusGET /
- Service information
CreatePost
- Create a new postGetPost
- Get a single post by IDGetPosts
- Get paginated list of postsUpdatePost
- Update an existing postDeletePost
- Delete a post
CREATE TABLE posts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
title VARCHAR NOT NULL,
content TEXT NOT NULL,
images TEXT[] DEFAULT '{}',
created_by UUID NOT NULL,
updated_by UUID,
deleted_by UUID,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
deleted_at TIMESTAMP,
is_deleted BOOLEAN DEFAULT false
);
The service uses a modular configuration system with environment-specific settings:
- Name: Service name and display information
- Environment: Development, staging, production
- Debug: Debug mode settings
- CORS: Cross-origin resource sharing settings
- Port: HTTP server port (default: 9002)
- Host: HTTP server host
- Versioning: API versioning settings
- URL: PostgreSQL connection string
- Migrations: Database migration settings
- URL: Redis connection string
- Key Prefix: Cache key prefix
- TTL: Cache time-to-live
- URL: gRPC server address
- Package: Protocol buffer package name
- URL: Auth service gRPC address for token validation
interface Post {
id: string;
title: string;
content: string;
images: string[];
createdBy: string;
updatedBy?: string;
deletedBy?: string;
createdAt: Date;
updatedAt: Date;
deletedAt?: Date;
isDeleted: boolean;
}
interface PostResponseDto {
id: string;
title: string;
content: string;
createdBy: UserResponseDto;
images: string[];
createdAt: Date;
updatedAt: Date;
updatedBy?: UserResponseDto;
deletedBy?: UserResponseDto;
deletedAt?: Date;
isDeleted: boolean;
}
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:cov
When running in development mode, Swagger documentation is available at:
http://localhost:9002/docs
- JWT Authentication: Secure token-based authentication
- Role-based Access Control: User authorization
- Input Validation: Request validation with class-validator
- Helmet Security: Security headers
- CORS Protection: Cross-origin request protection
- Soft Delete: Audit trail for deleted posts
- Health Checks: Built-in health monitoring endpoints
- Sentry Integration: Error tracking and monitoring
- Logging: Structured logging
- Metrics: Performance metrics collection
The Post Service integrates with the Auth Service via gRPC for:
- Token Validation: Validate JWT tokens
- User Information: Get user details for post creation/updates
- Authorization: Check user permissions
- gRPC Client: Connects to Auth Service for authentication
- User Context: Extracts user information from JWT tokens
- Audit Trail: Tracks user actions on posts
Ensure all required environment variables are set in your deployment environment.
Run database migrations before starting the service:
npm run prisma:migrate:prod
The service provides health check endpoints for load balancers and monitoring systems.
Ensure the Auth Service is running and accessible before starting the Post Service.
# Development
npm run dev # Start in development mode
npm run build # Build the application
npm run start # Start in production mode
# Database
npm run prisma:generate # Generate Prisma client
npm run prisma:migrate # Run migrations
npm run prisma:studio # Open Prisma Studio
# gRPC
npm run proto:generate # Generate gRPC code
# Code Quality
npm run lint # Run ESLint
npm run format # Format code with Prettier
# Testing
npm test # Run tests
npm run test:watch # Run tests in watch mode
The service follows a modular architecture with clear separation of concerns:
- Controllers: Handle HTTP requests and responses
- Services: Business logic and data processing
- DTOs: Data transfer objects for API contracts
- Interfaces: TypeScript interfaces for type safety
- Guards: Authentication and authorization guards
- Interceptors: Response transformation and logging
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
This project is licensed under the MIT License.
For support and questions, please contact the development team or create an issue in the repository.