Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement banUser function #8

Merged
merged 5 commits into from
Sep 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
} from './auth.pb';
import { RpcException } from '@nestjs/microservices';
import { status } from '@grpc/grpc-js';
import { GrpcPermissionDeniedException } from 'nestjs-grpc-exceptions';

Check warning on line 18 in src/auth/auth.service.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'GrpcPermissionDeniedException' is defined but never used
import { v4 as uuidv4 } from 'uuid';
import { Role } from '@prisma/client';

Expand Down Expand Up @@ -48,7 +48,7 @@
}

const { accessToken, refreshToken } = await this.getTokens(user.id);
user = await this.userRepo.updateRefreshToken(user.id, refreshToken);
user = await this.userRepo.update(user.id, { refreshToken: refreshToken });
if (!user) {
throw new RpcException({
code: status.INTERNAL,
Expand Down Expand Up @@ -79,7 +79,7 @@
public async refreshToken(
request: RefreshTokenRequest,
): Promise<RefreshTokenResponse> {
return null;

Check warning on line 82 in src/auth/auth.service.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'request' is defined but never used
}

private async getTokens(userId: string) {
Expand Down
13 changes: 13 additions & 0 deletions src/model/user.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Status } from "@prisma/client";

export interface User{
id: string;
createdAt: Date;
updatedAt: Date;
firstName: string;
lastName: string;
email: string;
phoneNumber: string;
role: string;
status: Status;
}
36 changes: 21 additions & 15 deletions src/repository/user.repository.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,16 @@
import { Injectable } from '@nestjs/common';
import { PrismaClient, User } from '@prisma/client';
import { Injectable, NotFoundException } from '@nestjs/common';

Check warning on line 1 in src/repository/user.repository.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'NotFoundException' is defined but never used
import { PrismaClient, Status, User } from '@prisma/client';

Check warning on line 2 in src/repository/user.repository.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'PrismaClient' is defined but never used

Check warning on line 2 in src/repository/user.repository.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'Status' is defined but never used
import { PrismaService } from '../prisma/service/prisma.service';
import { Prisma } from '@prisma/client';

@Injectable()
export class UserRepository {
constructor(private db: PrismaService) { }
constructor(private db: PrismaService) {}

async getUserByEmail(email: string): Promise<User> {
return this.db.user.findUnique({ where: { email: email } });
}

async updateRefreshToken(
userId: string,
refreshToken: string,
): Promise<User> {
return await this.db.user.update({
where: { id: userId },
data: { refreshToken: refreshToken },
});
}

async create(createUser: Prisma.UserCreateInput): Promise<User> {
return await this.db.user.create({
data: {
Expand All @@ -35,6 +25,22 @@
});
}

async findUserById(userId: string): Promise<User> {
return await this.db.user.findUnique({
where: { id: userId },
});
}

async update(
userId: string,
updateUser: Prisma.UserUpdateInput,
): Promise<User> {
return await this.db.user.update({
where: { id: userId },
data: updateUser,
});
}

async getAllUsers(): Promise<object[]> {
return this.db.user.findMany({
select: {
Expand All @@ -46,8 +52,8 @@
role: true,
password: false,
refreshToken: false,
status: true
}
status: true,
},
});
}

Expand Down
9 changes: 5 additions & 4 deletions src/user/user.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@ import { UserService } from './user.service';
describe('UserController', () => {
let controller: UserController;
const mockUserService = {
findUserById: jest.fn(),
update: jest.fn(),
exclude: jest.fn(),
findAllUsers: jest.fn(),
banUser: jest.fn(),
unbanUser: jest.fn(),
};

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UserController],
providers: [{ provide: UserService, useValue: mockUserService }]
providers: [{ provide: UserService, useValue: mockUserService }],
}).compile();

controller = module.get<UserController>(UserController);
Expand Down
7 changes: 4 additions & 3 deletions src/user/user.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Controller, Get, Patch } from '@nestjs/common';
import { Controller, Get, Param, Patch } from '@nestjs/common';
import { UserService } from './user.service';
import { User } from 'src/model/user.dto';

@Controller('user')
export class UserController {
Expand All @@ -11,8 +12,8 @@ export class UserController {
}

@Patch('ban/:userId')
banUser() {
return null;
banUser(@Param('userId') userId: string) : Promise<User>{
return this.userService.banUser(userId);
}

@Patch('unban/:userId')
Expand Down
11 changes: 7 additions & 4 deletions src/user/user.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,13 @@ describe('UserService', () => {

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UserService, {
provide: UserRepository,
useValue: mockUserRepository,
},],
providers: [
UserService,
{
provide: UserRepository,
useValue: mockUserRepository,
},
],
}).compile();

service = module.get<UserService>(UserService);
Expand Down
25 changes: 19 additions & 6 deletions src/user/user.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Injectable, InternalServerErrorException } from '@nestjs/common';
import { Injectable, NotFoundException, InternalServerErrorException } from '@nestjs/common';
import { UserRepository } from '../repository/user.repository';
import { Status } from '@prisma/client';

@Injectable()
export class UserService {
Expand All @@ -15,15 +16,27 @@ export class UserService {
}
}

banUser() {
return null;
async banUser(userId: string) {
try {
const user = await this.userRepo.findUserById(userId);
if(!user){
throw new NotFoundException(`User with id ${userId} not found`);
}
if(user.status === Status.BANNED){
return this.userRepo.exclude(user, ['password', 'refreshToken']);;
}
const bannedUser = await this.userRepo.update(userId, {
status: Status.BANNED,
});
return this.userRepo.exclude(bannedUser, ['password', 'refreshToken']);
} catch (e) {
console.log(e);
throw e;
}
}

unbanUser() {
return null;
}
}
function exclude(allUsers: Promise<{ id: string; createdAt: Date; updatedAt: Date; firstName: string; lastName: string; email: string; phoneNumber: string; password: string; role: import(".prisma/client").$Enums.Role; refreshToken: string; }[]>) {
throw new Error('Function not implemented.');
}

Loading