@teacinema/contracts (1.4.0)

Published 2026-04-18 08:36:39 +03:00 by ksv741 in teacinema/contracts

Installation

@teacinema:registry=
npm install @teacinema/contracts@1.4.0
"@teacinema/contracts": "1.4.0"

About this package

@teacinema/contracts

npm-пакет с контрактами для межсервисного взаимодействия: gRPC (протобафы) и события (message broker).

Установка

yarn add @teacinema/contracts

gRPC сервисы

Для подключения gRPC клиента используй PROTO_PATHS и соответствующее имя пакета.

Сервис Пакет proto Описание
AuthService auth.v1 Аутентификация (OTP, токены, Telegram)
AccountService account.v1 Управление аккаунтом (email, телефон)
UsersService users.v1 Профили пользователей

AuthService — auth.v1

Метод Запрос Ответ Описание
SendOtp SendOtpRequest SendOtpResponse Отправить OTP-код
VerifyOtp VerifyOtpRequest VerifyOtpResponse Проверить OTP, получить токены
Refresh RefreshRequest RefreshResponse Обновить access/refresh токены
TelegramInit Empty TelegramInitResponse Получить ссылку для Telegram-авторизации
TelegramVerify TelegramVerifyRequest TelegramVerifyResponse Верифицировать данные от Telegram
TelegramComplete TelegramCompleteRequest TelegramCompleteResponse Привязать телефон к Telegram-сессии
TelegramConsume TelegramConsumeRequest TelegramConsumeResponse Получить токены из Telegram-сессии

AccountService — account.v1

Метод Запрос Ответ Описание
GetAccount GetAccountRequest GetAccountResponse Получить данные аккаунта по ID
InitEmailChange InitEmailChangeRequest InitEmailChangeResponse Инициировать смену email
ConfirmEmailChange ConfirmEmailChangeRequest ConfirmEmailChangeResponse Подтвердить смену email
InitPhoneChange InitPhoneChangeRequest InitPhoneChangeResponse Инициировать смену телефона
ConfirmPhoneChange ConfirmPhoneChangeRequest ConfirmPhoneChangeResponse Подтвердить смену телефона

UsersService — users.v1

Метод Запрос Ответ Описание
GetMe GetMeRequest GetMeResponse Получить профиль пользователя по ID
CreateUser CreateUserRequest CreateUserResponse Создать нового пользователя
PatchUser PatchUserRequest PatchUserResponse Обновить данные пользователя (частичное обновление)

Использование в NestJS

1. Регистрация gRPC клиента

import { ClientsModule, Transport } from '@nestjs/microservices';
import { PROTO_PATHS } from '@teacinema/contracts';

@Module({
  imports: [
    ClientsModule.register([
      {
        name: 'AUTH_SERVICE',
        transport: Transport.GRPC,
        options: {
          protoPath: PROTO_PATHS.AUTH,
          package: 'auth.v1',
          url: 'localhost:5000',
        },
      },
      {
        name: 'ACCOUNT_SERVICE',
        transport: Transport.GRPC,
        options: {
          protoPath: PROTO_PATHS.ACCOUNT,
          package: 'account.v1',
          url: 'localhost:5001',
        },
      },
      {
        name: 'USERS_SERVICE',
        transport: Transport.GRPC,
        options: {
          protoPath: PROTO_PATHS.USERS,
          package: 'users.v1',
          url: 'localhost:5002',
        },
      },
    ]),
  ],
})
export class AppModule {}

2. Использование gRPC клиента

Типы клиентов генерируются из proto-файлов и находятся в gen/:

import { Inject, Injectable, OnModuleInit } from '@nestjs/common';
import { ClientGrpc } from '@nestjs/microservices';
import { AuthServiceClient } from '@teacinema/contracts/gen/ts/auth';

@Injectable()
export class AuthProxy implements OnModuleInit {
  private authService: AuthServiceClient;

  constructor(@Inject('AUTH_SERVICE') private client: ClientGrpc) {}

  onModuleInit() {
    this.authService = this.client.getService<AuthServiceClient>('AuthService');
  }

  sendOtp(identifier: string, type: string) {
    return this.authService.sendOtp({ identifier, type });
  }
}

3. Реализация gRPC сервера

import { Controller } from '@nestjs/common';
import { GrpcMethod } from '@nestjs/microservices';
import { AuthServiceController, AuthServiceControllerMethods } from '@teacinema/contracts/gen/ts/auth';

@Controller()
@AuthServiceControllerMethods()
export class AuthController implements AuthServiceController {
  @GrpcMethod('AuthService', 'SendOtp')
  sendOtp(request: SendOtpRequest): SendOtpResponse {
    // ...
  }
}

События (Message Broker)

Интерфейсы событий для типизированного обмена через брокер сообщений (RabbitMQ, Kafka и др.).

Интерфейс Источник Описание
OtpRequestedEvent auth-service Запрос на отправку OTP-кода
EmailChangedEvent account-service Инициация смены email
PhoneChangedEvent account-service Инициация смены телефона

Публикация события

import { OtpRequestedEvent } from '@teacinema/contracts';

client.emit<OtpRequestedEvent>('auth.otp_requested', {
  identifier: '+79001234567',
  code: '123456',
  type: 'phone',
});

Подписка на событие

import { EventPattern } from '@nestjs/microservices';
import { OtpRequestedEvent } from '@teacinema/contracts';

@Controller()
export class NotificationController {
  @EventPattern('auth.otp_requested')
  handleOtpRequested(data: OtpRequestedEvent) {
    // отправить SMS или email с кодом
  }
}

Обновление типов из proto

После изменения .proto файлов — пересгенерировать TypeScript типы:

yarn generate

Документация

Сгенерировать HTML-документацию и открыть в браузере:

yarn docs
open docs/index.html

Dependencies

Dependencies

ID Version
@nestjs/microservices ^11.1.12
protoc 33.4.0
rxjs ^7.8.2
ts-proto 2.11.0

Development Dependencies

ID Version
@types/node ^25.0.10
typedoc ^0.28.17
typescript ^5.9.3
Details
npm
2026-04-18 08:36:39 +03:00
4
16 KiB
Assets (1)
Versions (29) View all
1.6.0 2026-04-26
1.5.0 2026-04-25
1.4.1 2026-04-18
1.4.0 2026-04-18
1.3.2 2026-04-17