Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | 4x 4x 4x 4x 4x 4x 16x 2x 2x 2x 1x 1x 1x 4x 4x 2x 6x 6x 5x 5x 1x 5x 2x 1x 1x 5x 5x 5x 2x 1x 1x | import {
Injectable,
NotFoundException,
BadRequestException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from '../entities/user.entity';
import { Repository } from 'typeorm';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import * as bcrypt from 'bcryptjs';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private userRepo: Repository<User>,
) {}
async findByUsername(username: string): Promise<User | null> {
return this.userRepo.findOne({ where: { username, status_aktif: true } });
}
async create(dto: CreateUserDto): Promise<User> {
const exist = await this.userRepo.findOne({
where: { username: dto.username },
});
if (exist) throw new BadRequestException('Username sudah terdaftar');
const user = this.userRepo.create({
...dto,
password: await bcrypt.hash(dto.password, 10),
status_aktif: true,
});
return this.userRepo.save(user);
}
async findAll(): Promise<User[]> {
return this.userRepo.find();
}
async findOne(id: number): Promise<User> {
const user = await this.userRepo.findOne({ where: { id } });
if (!user) throw new NotFoundException('User tidak ditemukan');
return user;
}
async update(id: number, dto: UpdateUserDto): Promise<User> {
const user = await this.userRepo.findOne({ where: { id } });
if (!user) throw new NotFoundException('User tidak ditemukan');
// Terapkan perubahan field selain password dulu
Object.assign(user, dto);
// Jika ada password baru, hash dan timpa field password
if (dto.password) {
user.password = await bcrypt.hash(dto.password, 10);
}
if (dto.status_aktif !== undefined) {
if (typeof dto.status_aktif === 'string') {
user.status_aktif = dto.status_aktif === 'aktif';
} else {
user.status_aktif = !!dto.status_aktif;
}
}
const saved = await this.userRepo.save(user);
// Jangan return password ke client
const { password, ...result } = saved;
return result as User;
}
async softDelete(id: number): Promise<User> {
const user = await this.findOne(id);
user.status_aktif = false;
return this.userRepo.save(user);
}
}
|