Skip to content

A. Membuat REST API

Pada Materi ini kita akan berlatih untuk membuat rest api dengan database sementara berupa array. Setelah latihan ini diharapkan peserta didik dapat lebih memahami workflow ketika membuat endponint rest api dari NestJs.

Kita akan berlatih untuk membuat rest api yang bertujuan untuk menambah data , menghapus data, mengupdate data, dan menampilkan data. Adapun studi kasus kita adalah menambah, menghapus, mengupdate dan menampilkan buku.

Adapun tipe data untuk array books adalah seperti berikut

const books = {
    id : number,
    titile : string,
    author : string,
    year : number
}[]

1. Membuat Module, Service dan Controller Book

ihsanabuhanifah@ihsanabuhanifah-MacBook-Pro backend-nestjs % npx nest g mo book
ihsanabuhanifah@ihsanabuhanifah-MacBook-Pro backend-nestjs % npx nest g service  book
ihsanabuhanifah@ihsanabuhanifah-MacBook-Pro backend-nestjs % npx nest g controller  book

2. Membuat property book pada Service dan membuat service getAllBook

book.service.ts

import { Injectable } from "@nestjs/common";

@Injectable()
export class BookService {
  private books: {
    id?: number;
    title: string;
    author: string;
    year: number;
  }[] = [
    {
      id: 1,
      titile: "HTML CSS",
      author: "ihsanabuhanifah",
      year: 2023,
    },
  ];

  getAllBooks(): {
    id?: number;
    title: string;
    author: string;
    year: number;
  }[] {
    return this.books;
  }
}

3. Inject Service ke dalam Controller dan membuat routing Get

book.controller.ts

import { Controller, Get } from "@nestjs/common";
import { BookService } from "./book.service";

@Controller("book")
export class BookController {
  constructor(private bookService: BookService) {}

  @Get("/list")
  findAllBook() {
    return this.bookService.getAllBooks();
  }
}

Selanjutkan kita akan uji pada postman untuk menampilkan seluruh buku pada array books

Alt text Alt text

4. Membuat api create book

book.service.ts

...

createBook(
    title: string,
    author: string,
    year: number,
  ): {
    status: string;
    message: string;
  } {
    this.books.push({
      id: new Date().getTime(),
      title: title,
      author: author,
      year: year,
    });

    return {
      status: 'Success',
      message: 'Berhasil menambakan buku',
    };
  }

...

book.controller.ts

...

@Post('/create')
  createBook(
    @Body('title') title: string,
    @Body('author') author: string,
    @Body('year') year: number,
  ) {
    return this.bookService.createBook(title, author, year);
  }

...

Pengujian ketika create

Alt text

Pengujian ketika get

Alt text

5. Membuat api get detail by id

book.service.ts

 findBookById(id: number): number {
    const bookIndex = this.books.findIndex((book) => book.id === id);

    if (bookIndex === -1) {
      throw new NotFoundException(`Buku dengan id ${id} tidak ditemukan`);
    }

    return bookIndex;
  }

  getDetail(id: number): {
    id?: number;
    title: string;
    author: string;
    year: number;
  } {
    const bookIndex = this.findBookById(id);
    const book = this.books[bookIndex];

    return book;
  }

pada koding di atas, kita membaut method findBookById sebagai method yang akan di panggil pada method lain yang bertujuan untuk mencari index ke berapa berdasarkan id buku

book.controller.ts

...

@Get('detail/:id')
  findOneBook(@Param('id') id: string) {
    return this.bookService.getDetail(Number(id));
  }

...

Pengujian detail by Id

Alt text

Membuat api update buku

book.service.ts

...

 updateBook(
    id: number,
    title: string,
    author: string,
    year: number,
  ): {
    status: string;
    message: string;
  } {
    const bookIndex = this.books.findIndex((book) => book.id === id);
    this.books[bookIndex].title = title;
    this.books[bookIndex].author = author;
    this.books[bookIndex].year = year;

    return {
      status: 'Success',
      message: 'Berhasil update buku',
    };
  }

  ...

book.controller.ts

...

@Put('update/:id')
  updateBook(
    @Param('id') id: string,
    @Body('title') title: string,
    @Body('author') author: string,
    @Body('year') year: number,
  ) {
    return this.bookService.updateBook(Number(id), title, author, year);
  }

...

Pengujian update buku

Alt text

7. Menghapus api delete buku

book.service.ts

...

deleteBook(id: number): {
    status: string;
    message: string;
  } {
    const bookIndex = this.findBookById(id);
    this.books.splice(bookIndex, 1);
    return {
      status: `Success ${bookIndex}`,
      message: 'Berhasil menghapus buku',
    };
  }

...
book.controller.ts

...

 @Delete('delete/:id')
  deleteBook(@Param('id') id: string) {
    return this.bookService.deleteBook(+id);
  }
...

Pengujian delete buku

Alt text