Skip to content

3. Memperbaharui Profile

1. Membuat Module, Controller, Service

terminal
npx nest g module app/profile
npx nest g controller app/profile
npx nest g service app/profile

2. Import Entity User pada module

profile.module.ts
import { Module } from '@nestjs/common';
import { ProfileController } from './profile.controller';
import { ProfileService } from './profile.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from '../auth/auth.entity';

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  controllers: [ProfileController],
  providers: [ProfileService],
})
export class ProfileModule {}

3. Membuat DTO pada profile

profile.dto.ts
import { PickType } from '@nestjs/mapped-types';
import { UserDto } from '../auth/auth.dto';

export class UpdateProfileDto extends PickType(UserDto, [
  'avatar',
  'nama',
  'id',
]) {}

4. Membuat Service Update Profile

profile.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import BaseResponse from 'src/utils/response/base.response';
import { User } from '../auth/auth.entity';
import { ResponseSuccess } from 'src/interface/response';
import { Repository } from 'typeorm';
import { UpdateProfileDto } from './profile.dto';

@Injectable()
export class ProfileService extends BaseResponse {
  constructor(
    @InjectRepository(User)
    private readonly profileRepository: Repository<User>,
  ) {
    super();
  }

  async updateProfile(
    id: number,
    payload: UpdateProfileDto,
  ): Promise<ResponseSuccess> {
    const update = await this.profileRepository.save({
      nama: payload.nama,
      avatar: payload.avatar,
      id: id,
    });

    return this._success('Update Success', update);
  }
}

5. Membuat Controller Update Profile

profile.controller.ts
import { Body, Controller, Put, Req, UseGuards } from '@nestjs/common';
import { ProfileService } from './profile.service';
import { UpdateProfileDto } from './profile.dto';
import { JwtGuard } from '../auth/auth.guard';

@UseGuards(JwtGuard)
@Controller('profile')
export class ProfileController {
  constructor(private profileService: ProfileService) {}

  @Put('update')
  async updateProfile(@Body() payload: UpdateProfileDto, @Req() req) {
    const { id } = req.user;
    return this.profileService.updateProfile(+id, payload);
  }
}

6. Testing Update Profile

a. Testing update profile pada Postman

Alt text

Alt text

payload
{
    "id": 1,
    "avatar": "http://facebook.png",
    "nama": "ihsan santana w"
}

Alt text