sebelumnya kita sudah berhasil membuat api untuk categories, selanjutnya kita akan membuat api untuk todo-list nya. cara nya masih sama, didalam folder **api,**kita buat terlebih dahulu folder todos nya, nah didalam folder todos ini ****kita buat model ****kita akan membuat model / schema dari todo-list nya , silahkan teman - teman bisa menuliskan code berikut dalam model.js:
const mongoose = require("mongoose");
const { model, Schema } = mongoose;
let todoSchema = Schema(
{
title: {
type: String,
minlength: [3, "Panjang judul todo minimal 3 karakter"],
maxlength: [100, "Panjang judul todo maksimal 100 karakter"],
required: [true, "Judul todo harus diisi"],
},
description: {
type: String,
maxlength: [500, "Panjang deskripsi todo maksimal 500 karakter"],
},
completed: {
type: Boolean,
default: false,
},
dueDate: {
type: Date,
},
category: {
type: Schema.Types.ObjectId,
ref: "Category",
required: [true, "Kategori harus diisi"],
},
},
{ timestamps: true }
);
module.exports = model("Todo", todoSchema);
setelah model / schema dari todos nya kita buat , apa langkah selanjutnya ?? benar , membuat service dari todos nya, di folder service/mongoose , silahkan teman - teman buat file dengan nama todos.js dan tuliskan code berikut :
const Todo = require("../../api/todos/model");
// Service untuk mendapatkan semua todos dengan kategori terkait
const getAllTodos = async () => {
try {
const todos = await Todo.find({}).populate("category");
return todos;
} catch (error) {
throw new Error("Error retrieving todos: " + error.message);
}
};
// Service untuk mendapatkan todo berdasarkan ID
const getTodoById = async (id) => {
try {
const todo = await Todo.findById(id).populate("category");
if (!todo) {
throw new Error("Todo not found");
}
return todo;
} catch (error) {
throw new Error("Error retrieving todo with id: " + id);
}
};
// Service untuk membuat todo baru
const createTodo = async (data) => {
try {
const newTodo = new Todo(data);
await newTodo.save();
return newTodo;
} catch (error) {
throw new Error("Error creating todo: " + error.message);
}
};
// Service untuk memperbarui todo
const updateTodo = async (id, data) => {
try {
const updatedTodo = await Todo.findByIdAndUpdate(id, data, {
new: true,
}).populate("category");
if (!updatedTodo) {
throw new Error("Todo not found");
}
return updatedTodo;
} catch (error) {
throw new Error("Error updating todo: " + error.message);
}
};
// Service untuk menghapus todo
const deleteTodo = async (id) => {
try {
const deletedTodo = await Todo.findByIdAndDelete(id);
if (!deletedTodo) {
throw new Error("Todo not found");
}
return deletedTodo;
} catch (error) {
throw new Error("Error deleting todo: " + error.message);
}
};
module.exports = {
getAllTodos,
getTodoById,
createTodo,
updateTodo,
deleteTodo,
};
Berikut penjelasan untuk kode yang kamu buat terkait dengan service untuk manajemen todo menggunakan Mongoose:
Import Model Todo
const Todo = require("../../api/todos/model");
Todo dari file model yang berada di ../../api/todos/model. Model ini digunakan untuk berinteraksi dengan koleksi todos di database MongoDB.Service untuk Mendapatkan Semua Todos dengan Kategori Terkait
const getAllTodos = async () => {
try {
const todos = await Todo.find({}).populate("category");
return todos;
} catch (error) {
throw new Error("Error retrieving todos: " + error.message);
}
};
Todo dari koleksi..populate("category"): Menggunakan metode populate untuk mengisi field category dengan data lengkap dari koleksi categories (relasi antar koleksi).Service untuk Mendapatkan Todo Berdasarkan ID
const getTodoById = async (id) => {
try {
const todo = await Todo.findById(id).populate("category");
if (!todo) {
throw new Error("Todo not found");
}
return todo;
} catch (error) {
throw new Error("Error retrieving todo with id: " + id);
}
};
Todo berdasarkan ID yang diberikan..populate("category"): Mengisi field category dengan data lengkap dari koleksi categories.Service untuk Membuat Todo Baru
const createTodo = async (data) => {
try {
const newTodo = new Todo(data);
await newTodo.save();
return newTodo;
} catch (error) {
throw new Error("Error creating todo: " + error.message);
}
};
new Todo(data): Membuat instance baru dari model Todo dengan data yang diberikan..save(): Menyimpan todo baru ke database.Service untuk Memperbarui Todo
const updateTodo = async (id, data) => {
try {
const updatedTodo = await Todo.findByIdAndUpdate(id, data, {
new: true,
}).populate("category");
if (!updatedTodo) {
throw new Error("Todo not found");
}
return updatedTodo;
} catch (error) {
throw new Error("Error updating todo: " + error.message);
}
};
findByIdAndUpdate(id, data, { new: true }): Mencari dan memperbarui dokumen berdasarkan ID. Parameter new: true memastikan hasil yang dikembalikan adalah dokumen yang telah diperbarui..populate("category"): Mengisi field category dengan data lengkap dari koleksi categories.Service untuk Menghapus Todo
const deleteTodo = async (id) => {
try {
const deletedTodo = await Todo.findByIdAndDelete(id);
if (!deletedTodo) {
throw new Error("Todo not found");
}
return deletedTodo;
} catch (error) {
throw new Error("Error deleting todo: " + error.message);
}
};
findByIdAndDelete(id): Mencari dan menghapus dokumen berdasarkan ID.Ekspor Fungsi-fungsi Service
module.exports = {
getAllTodos,
getTodoById,
createTodo,
updateTodo,
deleteTodo,
};
nah teman - teman sudah membuat logika dari todosnya, langkah selanjutnya apa ?? ya benar, menggunakan logika bisnis ini di controller categories.silahkan teman - teman ketikan code berikut dalam controller.js dalam folder server/app/api/todos
const Todos = require("../../services/mongoose/todos");
const index = async (req, res) => {
try {
const todos = await Todos.getAllTodos();
return res.status(200).json(todos);
} catch (err) {
return res.status(err.status || 500).json({ error: err.message });
}
};
const find = async (req, res) => {
const { id } = req.params;
try {
const todo = await Todos.getTodoById(id);
return res.status(200).json(todo);
} catch (err) {
return res.status(err.status || 500).json({ error: err.message });
}
};
const create = async (req, res) => {
const { title, description, category } = req.body;
try {
const todo = await Todos.createTodo({ title, description, category });
return res.status(201).json(todo);
} catch (err) {
return res.status(err.status || 500).json({ error: err.message });
}
};
const update = async (req, res) => {
const { id } = req.params;
const { title, description, category } = req.body;
try {
const todo = await Todos.updateTodo(id, { title, description, category });
return res.status(200).json(todo);
} catch (err) {
return res.status(err.status || 500).json({ error: err.message });
}
};
const destroy = async (req, res) => {
const { id } = req.params;
try {
const todo = await Todos.deleteTodo(id);
return res.status(200).json(todo);
} catch (err) {
return res.status(err.status || 500).json({ error: err.message });
}
};
module.exports = {
index,
find,
create,
update,
destroy,
}
Berikut adalah penjelasan untuk kode dalam file controller.js di folder server/app/api/todos yang berfungsi menghubungkan logika bisnis dengan rute API:
Mengimpor Service Todos
const Todos = require("../../services/mongoose/todos");
Todos dari file yang terletak di ../../services/mongoose/todos. Service ini berisi logika bisnis untuk operasi CRUD pada todos.Controller untuk Mendapatkan Semua Todos
const index = async (req, res) => {
try {
const todos = await Todos.getAllTodos();
return res.status(200).json(todos);
} catch (err) {
return res.status(err.status || 500).json({ error: err.message });
}
};
index menangani permintaan GET untuk mendapatkan semua todos.await Todos.getAllTodos(): Memanggil fungsi service untuk mendapatkan semua todos.Controller untuk Mendapatkan Todo Berdasarkan ID
const find = async (req, res) => {
const { id } = req.params;
try {
const todo = await Todos.getTodoById(id);
return res.status(200).json(todo);
} catch (err) {
return res.status(err.status || 500).json({ error: err.message });
}
};
find menangani permintaan GET untuk mendapatkan todo berdasarkan ID.const { id } = req.params;: Mengambil ID dari parameter URL.await Todos.getTodoById(id): Memanggil fungsi service untuk mendapatkan todo dengan ID tersebut.Controller untuk Membuat Todo Baru
const create = async (req, res) => {
const { title, description, category } = req.body;
try {
const todo = await Todos.createTodo({ title, description, category });
return res.status(201).json(todo);
} catch (err) {
return res.status(err.status || 500).json({ error: err.message });
}
};
create menangani permintaan POST untuk membuat todo baru.const { title, description, category } = req.body;: Mengambil data dari body request.await Todos.createTodo({ title, description, category }): Memanggil fungsi service untuk membuat todo baru dengan data tersebut.