contracts/README.md

200 lines
6.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# @teacinema/contracts
npm-пакет с контрактами для межсервисного взаимодействия: gRPC (протобафы) и события (message broker).
## Установка
```bash
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 клиента
```ts
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/`:
```ts
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 сервера
```ts
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 | Инициация смены телефона |
### Публикация события
```ts
import { OtpRequestedEvent } from '@teacinema/contracts';
client.emit<OtpRequestedEvent>('auth.otp_requested', {
identifier: '+79001234567',
code: '123456',
type: 'phone',
});
```
### Подписка на событие
```ts
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 типы:
```bash
yarn generate
```
---
## Документация
Сгенерировать HTML-документацию и открыть в браузере:
```bash
yarn docs
open docs/index.html
```