# SocketUseBefore Decorator

Module
import { SocketUseBefore } from "@tsed/socketio"
Source/packages/socketio/src/decorators/socketUseBefore.ts

# Overview

function SocketUseBefore(...middlewares: Type<any>[]): (target: any, propertyKey?: string | undefined, descriptor?: PropertyDescriptor | undefined) => void;

# Description

Attach a Socket Middleware to a method or a class.

# Example

A middleware can be also used on a SocketService either on a class or on a method.

Here an example of a middleware:

@SocketMiddleware()
export class UserConverterSocketMiddleware {
    constructor(private converterService: ConverterService) {
    }
    async use(@Args() args: any[]) {

        let [user] = args;
        // update Arguments
        user = ConverterService.deserialize(user, User);

        return [user];
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

The user instance will be forwarded to the next middleware and to your decorated method.

Then:

import {SocketService, SocketUseAfter, SocketUseBefore, Emit, Input, Args} from "@tsed/socketio";
import {UserConverterSocketMiddleware} from "../middlewares";
import {User} from "../models/User";

@SocketService("/my-namespace")
@SocketUseBefore(UserConverterSocketMiddleware) // global version
export class MySocketService {

   @Input("eventName")
   @Emit("responseEventName") // or Broadcast or BroadcastOthers
   @SocketUseBefore(UserConverterSocketMiddleware)
   async myMethod(@Args(0) user: User) {

       console.log(user);

       return user;
   }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18