There is case where I'm trying to handle session for user. I have different controllers for handling different auth methods, but all of them at the end should do the same - add/update req.session variable.
Here is the example of my code for auth on "twitch" platform (and for all other code looks similar):
import { Controller, Get, Req, Res, UseGuards } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
@Controller('auth/twitch')
export class TwitchController {
@Get('finishAuth')
async finishAuth(
@Req() req,
@Query('code') code,
) {
const profile = await this.authTwitchService.getProfile(code);
req.session = profile;
}
}
Would it be a good idea to move this req.session = profile; code to some service? Or is it a bad practice because we modify things that should be modified only on controller level?
My suggestion is to do something like this:
import { Injectable } from '@nestjs/common';
@Injectable()
export class SessionManager {
updateProfile(
profile: {id: string, username: string, email: string},
req: Request,
) {
req.session = profile;
}
}
And then rework controller:
import { Controller, Get, Req, Res, UseGuards } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
@Controller('auth/twitch')
export class TwitchController {
constructor(private sessionManager: SessionManager) {}
@Get('finishAuth')
async finishAuth(
@Req() req,
@Query('code') code,
) {
const profile = await this.authTwitchService.getProfile(code);
this.sessionManager.update(profile, req);
}
}