universo-platform-3d
60 строк · 1.7 Кб
1import {2CallHandler,3ExecutionContext,4Injectable,5NestInterceptor
6} from '@nestjs/common'7import { Logger } from '@nestjs/common'8import { catchError, map, Observable, throwError } from 'rxjs'9import { WsException } from '@nestjs/websockets'10import { PaginationInterface } from '../util/pagination/pagination.interface'11
12interface GodotWsSuccessResponse extends PaginationInterface {13eventId: string14status: number15result: any16}
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()24export class GodotSocketInterceptor implements NestInterceptor {25constructor(private readonly logger: Logger) {}26public intercept(27context: ExecutionContext,28next: CallHandler<GodotWsSuccessResponse>29): Observable<GodotWsSuccessResponse> {30const { eventId } = context.switchToWs().getData()31return next.handle().pipe(32map((response: any) => {33/** Pull data and pagination off, set data to result */34const { data, ...pagination } = response35const result = data ?? response36
37return {38eventId,39status: 200,40result,41
42/** If result is an array, add pagination */43...(Array.isArray(result) && { ...pagination })44}45}),46catchError((error) =>47throwError(() => {48this.logger.error(49'WSError: ',50error,51'context: ',52context,53GodotSocketInterceptor.name54)55return new WsException(error.message)56})57)58)59}60}
61