Из-за чего Get-запрос в insomnia выдает ошибку 401, если я авторизовался?
работаю со стеком React + Nest + PostgreSQL + Prisma + TS. При попытке получить профиль моего юзера мне выдает, что профиля юзера не существует.
Подозреваю, что метод byId
где-то не передает юзера, но найти не могу, где. Помогите пж.
Файл user.controller
, где происходит этот гет запрос:
import { Body, Controller, Get, HttpCode, Param, Patch, Post, Put, UsePipes, ValidationPipe } from '@nestjs/common';
import { UserService } from './user.service';
import { Auth } from 'src/auth/decorators/auth.decorator';
import { AuthDto } from 'src/auth/dto/auth.dto';
import { RefreshTokenDto } from 'src/auth/dto/refresh-token.dto';
import { CurrentUser } from 'src/auth/decorators/user.decorator';
import { UserDto } from './user.dto';
@Controller('user')
export class UserController {
constructor(private readonly userService: UserService) {}
@Get('profile')
@Auth()
async getProfile(@CurrentUser('id') id: number) {
return this.userService.byId(id)
}
@UsePipes(new ValidationPipe())
@HttpCode(200)
@Auth()
@Put('profile')
async getNewTokens(@CurrentUser('id') id: number, @Body()
dto: UserDto) {
return this.userService.updateProfile(id, dto)
}
@UsePipes(new ValidationPipe())
@HttpCode(200)
@Patch('profile/favorites/:productId')
async toggleFavorite(
@CurrentUser('id') id: number,
@Param('productId') productId: string) {
return this.userService.toggleFavorite(id, +productId)
}
}
Файл user.service
, где по айдишнику insomnia и должна получать пользователя:
import { BadRequestException, NotFoundException, Injectable } from '@nestjs/common';
import { PrismaService } from 'src/prisma.service';
import { returnUserObject } from './return-user.object';
import { Prisma } from '@prisma/client';
import { UserDto } from './user.dto';
import { hash } from 'argon2';
@Injectable()
export class UserService {
constructor(private prisma: PrismaService) {}
async byId(id: number, selectObject: Prisma.UserSelect =
{}) {
const user = await this.prisma.user.findUnique({where: {
id
},
select: {
id: true,
email: true,
name: true,
password: true,
phone: true,
favorites: {
select: {
id: true,
name: true,
price: true,
images: true,
slug: true
}
},
...selectObject
}
})
if (!user) { throw new Error('User not found.') }
return user
}
async updateProfile(id: number, dto: UserDto){
const isSameUser = await this.prisma.user.findUnique({
where: {email: dto.email }
})
if (isSameUser && id != isSameUser.id)
throw new BadRequestException('Email already in use.')
const user = await this.byId(id)
return this.prisma.user.update ({
where: {id},
data: {
email: dto.email,
name: dto.name,
phone: dto.phone,
password: dto.password ? await hash(dto.password) :
user.password
}
})
}
async toggleFavorite(userId: number, productId: number) {
const user = await this.byId(userId)
if (!user) throw new NotFoundException('User not found.')
const isExists = user.favorites.some(product => product.id === productId)
await this.prisma.user.update({
where: {id: user.id},
data: {
favorites: {
[isExists ? 'disconnect' : 'connect']: {
id: productId
}
}
}
})
return 'Success'
}
}
Помогите пж, когда найдете ошибку.
UPD: Поменял /api/users/profile на /api/user/profile, инсомния здесь пишет такое:
Товарищи специалисты, нужна ваша помощь...
Источник: Stack Overflow на русском