@mttickets12/common
v1.0.25
Published
Shared code package for microservices in the ticketing system.
Readme
Common Package
Shared code package for microservices in the ticketing system.
Overview
The @mttickets12/common package contains shared code used across all microservices, including error classes, event definitions, middleware, and base classes for event handling.
Installation
This package is published to npm. Install it in your service:
npm install @mttickets12/commonFor local development, use npm link:
# In common directory
npm link
# In service directory
npm link @mttickets12/commonBuilding
Build the package:
npm run buildThis compiles TypeScript to JavaScript in the build/ directory.
Publishing
Publish to npm:
npm run pubThis will:
- Clean the build directory
- Build the package
- Increment patch version
- Publish to npm
Contents
Errors
Custom error classes for consistent error handling:
BadRequestError- 400 status codeNotAuthorizedError- 401 status codeNotFoundError- 404 status codeRequestValidationError- 400 status code (validation errors)DatabaseValidationError- 400 status code (database errors)CustomError- Base error class
Middleware
Express middleware functions:
currentUser- Extracts and validates JWT token, setsreq.currentUserrequireAuth- Ensures user is authenticatedvalidateRequest- Validates request using express-validatorerrorHandler- Centralized error handling middleware
Events
Event-driven architecture components:
Base Classes
BaseListener- Abstract base class for event listenersBasePublisher- Abstract base class for event publishers
Event Types
TicketCreatedEventTicketUpdatedEventOrderCreatedEventOrderCancelledEventExpirationCompleteEventPaymentCreatedEvent
Subjects
Type-safe event subject constants:
Subject.TicketCreatedSubject.TicketUpdatedSubject.OrderCreatedSubject.OrderCancelledSubject.ExpirationCompleteSubject.PaymentCreated
Usage Examples
Using Middleware
import { requireAuth, currentUser } from '@mttickets12/common';
import express from 'express';
const router = express.Router();
// Protected route
router.get('/api/orders', currentUser, requireAuth, async (req, res) => {
// req.currentUser is available here
res.send({ userId: req.currentUser!.id });
});Using Error Classes
import { NotFoundError, BadRequestError } from '@mttickets12/common';
if (!ticket) {
throw new NotFoundError();
}
if (price < 0) {
throw new BadRequestError('Price must be positive');
}Creating Event Listeners
import { Listener, TicketCreatedEvent, Subjects } from '@mttickets12/common';
import { Message } from 'node-nats-streaming';
class TicketCreatedListener extends Listener<TicketCreatedEvent> {
readonly subject = Subjects.TicketCreated;
queueGroupName = 'orders-service';
async onMessage(data: TicketCreatedEvent['data'], msg: Message) {
// Handle event
console.log('Ticket created:', data);
msg.ack();
}
}Creating Event Publishers
import { Publisher, TicketCreatedEvent, Subjects } from '@mttickets12/common';
class TicketCreatedPublisher extends Publisher<TicketCreatedEvent> {
readonly subject = Subjects.TicketCreated;
}
// Usage
await new TicketCreatedPublisher(natsClient).publish({
id: 'ticket_id',
title: 'Concert',
price: 50,
userId: 'user_id',
version: 0
});Using Validation Middleware
import { validateRequest } from '@mttickets12/common';
import { body } from 'express-validator';
router.post(
'/api/tickets',
[
body('title').notEmpty().withMessage('Title is required'),
body('price').isFloat({ gt: 0 }).withMessage('Price must be greater than 0')
],
validateRequest,
async (req, res) => {
// Request is validated here
}
);Type Safety
The package is written in TypeScript and provides full type safety:
- Event data types
- Error types
- Middleware request types
Versioning
The package follows semantic versioning:
- Patch (1.0.x) - Bug fixes, no breaking changes
- Minor (1.x.0) - New features, backward compatible
- Major (x.0.0) - Breaking changes
When updating the package:
- Make changes
- Update version:
npm version patch|minor|major - Build:
npm run build - Publish:
npm publish --access public
Dependencies
- express - Web framework types
- express-validator - Request validation
- jsonwebtoken - JWT types
- cookie-session - Session types
- node-nats-streaming - NATS types
Development
- Make changes to TypeScript files in
src/ - Build the package:
npm run build - Test in consuming services
- Publish when ready:
npm run pub
Contributing
When adding new shared code:
- Ensure it's truly shared across services
- Maintain backward compatibility
- Add proper TypeScript types
- Update this README
- Test in at least one consuming service
