@echoes-of-order/grpc-service
v1.0.0
Published
gRPC Service library for Echoes of Order backend services
Maintainers
Readme
@echoes-of-order/grpc-service
A high-performance, reusable gRPC service library for Echoes of Order backend services. This package provides a complete gRPC infrastructure with error handling, type conversion, and modular architecture.
Features
- 🚀 High Performance: Built on gRPC with HTTP/2 multiplexing
- 🔧 Modular Architecture: Base classes for controllers, converters, and error handling
- 🛡️ Type Safety: Full TypeScript support with strict typing
- 🧪 Comprehensive Testing: Unit, integration, E2E, and mutation tests
- 📊 Code Quality: ESLint, Prettier, and automated quality gates
- 🔄 ESM Support: Modern ES modules throughout
- 📦 Reusable: Designed as an npm package for multiple services
Installation
# Install as dependency in your service
yarn add @echoes-of-order/grpc-service
# For development (includes all testing dependencies)
yarn add -D @echoes-of-order/grpc-serviceQuick Start
Basic Usage
import { GrpcModule, BaseGrpcController, BaseGrpcConverter, ErrorHandler } from '@echoes-of-order/grpc-service';
import { Module } from '@nestjs/common';
@Module({
imports: [
GrpcModule.forRoot({
providers: [YourService, YourConverter]
})
],
controllers: [YourGrpcController]
})
export class YourGrpcModule {}
class YourGrpcController extends BaseGrpcController {
constructor(converter: YourConverter, private service: YourService) {
super(converter);
}
@GrpcMethod('YourService', 'YourMethod')
async yourMethod(request: YourRequest) {
return this.executeServiceCall(async () => {
// Your business logic here
const result = await this.service.process(request);
return { success: true, data: result };
}, 'YourGrpcController.yourMethod');
}
}Advanced Usage
import { GrpcModule, BaseGrpcConverter } from '@echoes-of-order/grpc-service';
class YourConverter extends BaseGrpcConverter {
grpcToEnum(value: string, enumType: any, fieldName: string): string {
return this.grpcToEnum(value, enumType, fieldName);
}
validateRequiredString(value: string, fieldName: string): string {
return this.validateRequiredString(value, fieldName);
}
}Architecture
Core Components
GrpcModule: NestJS module for gRPC service configurationBaseGrpcController: Base class for gRPC controllers with error handlingBaseGrpcConverter: Base class for type conversion between gRPC and business logicErrorHandler: Centralized error handling and gRPC status code mapping
Project Structure
grpc-service/
├── src/
│ ├── controllers/BaseGrpcController.ts
│ ├── converters/BaseGrpcConverter.ts
│ ├── modules/GrpcModule.ts
│ ├── utils/ErrorHandler.ts
│ └── proto/character.proto
├── __tests__/
│ ├── unit/ # Unit tests (100% coverage)
│ ├── integration/ # Integration tests
│ ├── e2e/ # End-to-end tests
│ └── utils/ # Test utilities and helpers
├── .github/workflows/ # CI/CD pipelines
├── vitest.config.ts # Test configuration
├── stryker.conf.json # Mutation testing config
├── eslint.config.js # Linting configuration
└── tsconfig.test.json # Test TypeScript configTesting
Test Setup
This package includes comprehensive testing with multiple layers:
- Unit Tests: Isolated testing of individual components
- Integration Tests: Testing component interactions
- E2E Tests: Full request-response cycle testing
- Mutation Tests: Code quality validation with Stryker
Running Tests
# Run all tests
yarn test
# Run with coverage
yarn test:coverage
# Run specific test types
yarn test:unit
yarn test:integration
yarn test:e2e
# Run mutation tests
yarn test:mutation
# Run quality checks
yarn qualityTest Structure
Unit Tests
Located in __tests__/unit/ - test individual components in isolation.
Integration Tests
Located in __tests__/integration/ - test component interactions and module setup.
E2E Tests
Located in __tests__/e2e/ - test complete request flows from gRPC to business logic.
Test Utilities
Located in __tests__/utils/ - shared testing utilities, mocks, and fixtures.
Coverage Requirements
- Branches: ≥ 80%
- Functions: ≥ 80%
- Lines: ≥ 80%
- Statements: ≥ 80%
Coverage reports are generated in coverage/ directory with HTML, LCOV, and JSON formats.
Mutation Testing
Mutation testing with Stryker validates code quality by introducing artificial bugs and ensuring tests catch them.
- Mutation Score: ≥ 80%
- Configuration:
stryker.conf.json - Reports: Generated in
reports/mutation/
Code Quality
ESLint Configuration
Uses @echoes-of-order/eslint-config with NestJS rules:
import config from '@echoes-of-order/eslint-config';
export default config.nestjs;Quality Gates
- Linting: 0 errors, 0 warnings
- Type Checking: 0 TypeScript errors
- Build: Successful compilation
- Tests: All tests pass
- Coverage: ≥ 80% thresholds
- Mutation Score: ≥ 80% (on PRs)
Code Standards
- TypeScript: Strict mode enabled
- Imports: Absolute imports with
@/alias - Naming: Consistent naming conventions
- Documentation: JSDoc for public APIs
- Error Handling: Centralized error handling patterns
CI/CD Pipeline
GitHub Actions
The package includes comprehensive CI/CD with quality gates:
# .github/workflows/ci.yml
jobs:
quality-gates: # Linting, TypeScript, Build
tests: # Unit, Integration, E2E tests
coverage-check: # Coverage threshold validation
mutation-testing: # Mutation testing (PRs only)Pipeline Stages
Quality Gates
- ESLint validation
- TypeScript type checking
- Build verification
Testing
- Unit test execution
- Integration test execution
- E2E test execution
- Coverage report generation
Coverage Validation
- Threshold checking (80%)
- Artifact upload
Mutation Testing (PRs)
- Stryker execution
- Mutation score validation
Caching
- Yarn cache based on
yarn.lock - Node modules cache
- Test result caching
API Reference
GrpcModule
class GrpcModule {
static forRoot(options: GrpcModuleOptions): DynamicModule
static forFeature(): DynamicModule
}
interface GrpcModuleOptions {
providers?: any[];
imports?: any[];
exports?: any[];
}BaseGrpcController
abstract class BaseGrpcController {
constructor(converter?: BaseGrpcConverter);
protected executeServiceCall<T>(
operation: () => Promise<T>,
context?: string
): Promise<T>;
protected createSuccessResponse<T>(
data: T,
metadata?: Record<string, unknown>
): SuccessResponse<T>;
protected createErrorResponse(
message: string,
errorCode: string,
details?: Record<string, unknown>
): ErrorResponse;
protected validateRequest<T>(
request: T,
requiredFields: (keyof T)[]
): void;
}BaseGrpcConverter
abstract class BaseGrpcConverter {
protected enumToGrpc(
value: string,
enumType: Record<string, string>,
fieldName: string
): string;
protected grpcToEnum(
value: string,
enumType: Record<string, string>,
fieldName: string
): string;
protected validateRequiredString(value: string, fieldName: string): string;
protected validateOptionalString(value?: string): string | undefined;
protected validateRequiredUuid(value: string, fieldName: string): string;
protected createValidationError(message: string, details?: Record<string, unknown>): RpcException;
}ErrorHandler
class ErrorHandler {
static handleServiceError(error: unknown): RpcException;
static createRpcException(code: number, message: string, errorCode?: string, details?: any): RpcException;
static badRequest(message: string, errorCode?: string): RpcException;
static notFound(message: string, errorCode?: string): RpcException;
static conflict(message: string, errorCode?: string): RpcException;
static internal(message: string, errorCode?: string): RpcException;
}Development
Prerequisites
- Node.js 22.x
- Yarn
- Git
Setup
# Clone and install
git clone <repository-url>
cd grpc-service
yarn install
# Run tests
yarn test
# Run quality checks
yarn quality
# Build package
yarn buildDevelopment Scripts
# Testing
yarn test # Run all tests
yarn test:watch # Run tests in watch mode
yarn test:coverage # Run tests with coverage
yarn test:unit # Run unit tests only
yarn test:integration # Run integration tests only
yarn test:e2e # Run E2E tests only
# Quality
yarn lint # Run ESLint
yarn lint:fix # Fix ESLint issues
yarn type-check # Run TypeScript checking
yarn quality # Run all quality checks
# Build
yarn build # Build package
yarn build:watch # Build in watch mode
# Mutation Testing
yarn test:mutation # Run mutation tests
yarn test:mutation:ci # Run mutation tests for CI
# Protobuf
yarn proto:generate # Generate TypeScript from .proto filesContributing
Code Style
- Follow TypeScript strict mode guidelines
- Use absolute imports (
@/) - Write comprehensive tests for new features
- Update documentation for API changes
- Ensure all tests pass before submitting PRs
Testing Requirements
- Add unit tests for new utilities
- Add integration tests for new features
- Add E2E tests for complete flows
- Maintain ≥ 80% coverage
- Ensure mutation score ≥ 80%
Pull Request Process
- Create feature branch
- Implement changes with tests
- Run quality checks:
yarn quality - Ensure CI passes
- Submit PR with description
License
MIT License - see LICENSE file for details.
Support
For questions and support:
- Create an issue in the repository
- Check existing documentation
- Review test examples for usage patterns
Changelog
v1.0.0
- Initial release
- Base gRPC infrastructure
- Comprehensive testing suite
- CI/CD pipeline with quality gates
- ESM support
- TypeScript strict mode
- Mutation testing integration
