@anatix/runtime
v1.0.8
Published
Runtime infrastructure for Anatix-generated microservices
Downloads
1,126
Maintainers
Readme
@anatix/runtime
Runtime infrastructure pour applications générées par Anatix
📦 Installation
npm install @anatix/runtime🎯 Vue d'ensemble
@anatix/runtime fournit l'infrastructure nécessaire aux applications générées par Anatix, incluant :
- 🛡️ Guards : Authentification JWT et autorisation RBAC
- 📨 Envelope : Pattern Inbox/Outbox pour événements fiables
- 🚀 Event-Bus : Bus d'événements avec RabbitMQ
- 📝 Logger : Logging structuré
- 🔄 Proxy : Appels HTTP avec retry automatique
- 🔐 Security : Hashing de mots de passe
- 🗄️ Naming : Stratégie de nommage TypeORM
- ⚙️ Configs : Types pour repositories et services
- 🛠️ Utils : Utilitaires divers (dates, filtres)
📚 Modules
Guards
Authentification et autorisation pour NestJS.
import { JwtAuthGuard, PermissionsGuard, Permissions } from '@anatix/runtime/guards';
@Controller('users')
@UseGuards(JwtAuthGuard, PermissionsGuard)
export class UsersController {
@Get()
@Permissions('users:User:list')
async list() {
// Accessible uniquement avec la permission
}
}Envelope
Pattern Inbox/Outbox pour événements fiables et idempotents.
import { withInboxOutbox, OutboxRepo, ensureMeta } from '@anatix/runtime/envelope';
await withInboxOutbox(
dataSource,
'user.created',
meta,
payload,
async (manager) => {
// Logique métier dans transaction
const user = await manager.save(User, payload);
return user;
},
async (manager) => {
// Publier d'autres événements après commit
await OutboxRepo.enqueue(manager, {
topic: 'user.welcomed',
payload: { userId: user.id },
meta: ensureMeta(),
});
}
);Event-Bus
Bus d'événements avec RabbitMQ.
import { EventBusService } from '@anatix/runtime/event-bus';
@Injectable()
export class UserService {
constructor(private eventBus: EventBusService) {}
async createUser(dto: CreateUserDto) {
const user = await this.repo.save(dto);
// Publier un événement
await this.eventBus.publish('user.created', {
userId: user.id,
email: user.email,
});
return user;
}
}
// Souscrire à un événement
await eventBus.on('user.created', async (envelope, ctx) => {
console.log('New user:', envelope.data);
});Logger
Logging structuré avec helper pratique.
import { LogHelper, LogPort } from '@anatix/runtime/logger';
@Injectable()
export class UserService {
private readonly logger: LogHelper;
constructor(logPort: LogPort) {
this.logger = new LogHelper(logPort, 'users');
}
async createUser(dto: CreateUserDto) {
this.logger.info('Creating user', { email: dto.email });
try {
const user = await this.repo.save(dto);
this.logger.info('User created', { userId: user.id });
return user;
} catch (error) {
await this.logger.critical('user creation', { dto }, error);
}
}
}Proxy
Appels HTTP avec retry et timeout.
import { proxyGet, proxyPost } from '@anatix/runtime/proxy';
@Injectable()
export class PaymentService {
constructor(private http: HttpService) {}
async createPayment(dto: CreatePaymentDto) {
return proxyPost(
this.http,
`${PAYMENT_SERVICE_URL}/payments`,
dto,
{ timeout: 10000, retryAttempts: 3 }
);
}
}Security
Hashing de mots de passe.
import { HashingAdapter, BcryptAdapter, HASHING_ADAPTER } from '@anatix/runtime/security';
// Configuration du module
{
provide: HASHING_ADAPTER,
useClass: BcryptAdapter,
}
// Utilisation
@Injectable()
export class AuthService {
constructor(
@Inject(HASHING_ADAPTER) private hasher: HashingAdapter
) {}
async register(dto: RegisterDto) {
const hashedPassword = await this.hasher.hash(dto.password);
return this.userRepo.create({ ...dto, password: hashedPassword });
}
}Naming
Stratégie de nommage TypeORM (snake_case).
import { AnatixNamingStrategy } from '@anatix/runtime/naming';
const dataSource = new DataSource({
type: 'postgres',
namingStrategy: new AnatixNamingStrategy(),
entities: [...],
});Configs
Types pour repositories et services.
import { ServiceListOptions, ServiceQueryOptions } from '@anatix/runtime/configs';
@Controller('users')
export class UsersController {
@Get()
async list(@Query() options: ServiceListOptions) {
return this.userService.list(options);
}
@Get('search')
async search(@Query() options: ServiceQueryOptions) {
return this.userService.search(options);
}
}Utils
Utilitaires pour dates et filtres.
import {
toISOStringSafe,
toDateOnlyString,
parseFilterFields,
type FilterFieldDefs
} from '@anatix/runtime/utils';
// Conversion de dates
const iso = toISOStringSafe(new Date()); // '2024-01-15T00:00:00.000Z'
const dateOnly = toDateOnlyString(new Date()); // '2024-01-15'
// Parsing de filtres
const defs: FilterFieldDefs = {
date: ['createdAt'],
number: ['age'],
boolean: ['isActive'],
enum: ['status'],
enumValues: { status: ['PENDING', 'ACTIVE'] },
};
const filters = parseFilterFields(queryParams, defs);Decorators
Filtre d'exception global.
import { GlobalExceptionFilter } from '@anatix/runtime/decorators';
// Dans main.ts
const app = await NestFactory.create(AppModule);
app.useGlobalFilters(new GlobalExceptionFilter());🔧 Configuration
Variables d'environnement
RabbitMQ (Event-Bus)
RABBITMQ_URL=amqp://localhost
EVENT_BUS_EXCHANGE=anatix-event-bus
EVENT_BUS_QUEUE=default-queueJWT (Guards)
AUTH_JWT_ALGORITHM=HS256
AUTH_JWT_SECRET=your-secret
AUTH_JWT_PUBLIC_KEY=your-public-key
AUTH_JWT_ISSUER=your-issuer
AUTH_JWT_AUDIENCE=your-audienceProxy
PROXY_TIMEOUT_MS=5000
PROXY_RETRY_ATTEMPTS=2Hashing
BCRYPT_ROUNDS=12Logging
NODE_ENV=development
LOG_ERRORS=true📖 Documentation
Documentation complète disponible dans le code source (JSDoc/TSDoc).
🤝 Contribution
Ce package est maintenu par l'équipe Anatix. Les contributions externes ne sont pas acceptées pour le moment.
📄 License
MIT © Anatix Team
🔗 Liens
---
## 🎉 C'est Terminé !
### ✅ Récapitulatif Complet de @anatix/runtime
On a créé **10 modules** production-ready :
1. ✅ **Guards** - Authentification JWT + RBAC générique
2. ✅ **Envelope** - Inbox/Outbox pattern avec idempotence
3. ✅ **Event-Bus** - RabbitMQ avec publish/subscribe/RPC
4. ✅ **Logger** - Logging structuré avec helper
5. ✅ **Proxy** - HTTP avec retry et timeout
6. ✅ **Security** - Hashing abstrait + implémentation Bcrypt
7. ✅ **Decorators** - Exception filter global
8. ✅ **Utils** - Date helpers + filter parsing
9. ✅ **Naming** - TypeORM naming strategy (snake_case)
10. ✅ **Configs** - Types pour repo/service
### 📦 Structure Finale@anatix/runtime/ ├── src/ │ ├── guards/ │ ├── envelope/ │ ├── event-bus/ │ ├── logger/ │ ├── proxy/ │ ├── security/ │ ├── naming/ │ ├── configs/ │ ├── utils/ │ ├── decorators/ │ └── index.ts ├── package.json ├── tsconfig.json ├── tsconfig.build.json └── README.md
