universo-platform-3d

Форк
0
60 строк · 1.7 Кб
1
import {
2
  CallHandler,
3
  ExecutionContext,
4
  Injectable,
5
  NestInterceptor
6
} from '@nestjs/common'
7
import { Logger } from '@nestjs/common'
8
import { catchError, map, Observable, throwError } from 'rxjs'
9
import { WsException } from '@nestjs/websockets'
10
import { PaginationInterface } from '../util/pagination/pagination.interface'
11

12
interface GodotWsSuccessResponse extends PaginationInterface {
13
  eventId: string
14
  status: number
15
  result: any
16
}
17

18
/**
19
 * Transforms every websocket response to GodotWsSuccessResponse type.
20
 * If response is paginated, this pulls nested data object to root level
21
 * 'result' property. If result is an array, add pagination props.
22
 */
23
@Injectable()
24
export class GodotSocketInterceptor implements NestInterceptor {
25
  constructor(private readonly logger: Logger) {}
26
  public intercept(
27
    context: ExecutionContext,
28
    next: CallHandler<GodotWsSuccessResponse>
29
  ): Observable<GodotWsSuccessResponse> {
30
    const { eventId } = context.switchToWs().getData()
31
    return next.handle().pipe(
32
      map((response: any) => {
33
        /** Pull data and pagination off, set data to result */
34
        const { data, ...pagination } = response
35
        const result = data ?? response
36

37
        return {
38
          eventId,
39
          status: 200,
40
          result,
41

42
          /** If result is an array, add pagination */
43
          ...(Array.isArray(result) && { ...pagination })
44
        }
45
      }),
46
      catchError((error) =>
47
        throwError(() => {
48
          this.logger.error(
49
            'WSError: ',
50
            error,
51
            'context: ',
52
            context,
53
            GodotSocketInterceptor.name
54
          )
55
          return new WsException(error.message)
56
        })
57
      )
58
    )
59
  }
60
}
61

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

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.