Membangun aplikasi web di era modern memerlukan pondasi yang kokoh. Framework modern memberikan fleksibilitas luar biasa bagi developer untuk menghadirkan fitur kompleks secara cepat tanpa mengabaikan aspek keamanan dan keandalan sistem.
Tahapan Implementasi & Walkthrough Kode
Berikut adalah langkah demi langkah teknis yang dapat Anda ikuti langsung pada codebase Anda:
Tahap 1: Penulisan Kode & Konfigurasi
//import context
import { Context } from 'hono'
//import prisma client
import prisma from "../../prisma/client";
/**
* Getting all posts
*/
export const getPosts = async (c: Context) => {
try {
//get all posts
const posts = await prisma.post.findMany({ orderBy: { id: 'desc' } });
//return JSON
return c.json({
success: true,
message: 'List Data Posts!',
data: posts
}, 200);
} catch (e: unknown) {
console.error(`Error getting posts: ${e}`);
}
}
/**
* Creating a post
*/
export async function createPost(c: Context) {
try {
//get body request
const body = await c.req.parseBody();
//check if title and content is string
const title = typeof body['title'] === 'string' ? body['title'] : '';
const content = typeof body['content'] === 'string' ? body['content'] : '';
//create post
const post = await prisma.post.create({
data: {
title: title,
content: content,
}
});
//return JSON
return c.json({
success: true,
message: 'Post Created Successfully!',
data: post
}, 201);
} catch (e: unknown) {
console.error(`Error creating post: ${e}`);
}
}
/**
* Getting a post by ID
*/
export async function getPostById(c: Context) {
try {
// Konversi tipe id menjadi number
const postId = parseInt(c.req.param('id'));
//get post by id
const post = await prisma.post.findUnique({
where: { id: postId },
});
//if post not found
if (!post) {
//return JSON
return c.json({
success: false,
message: 'Post Not Found!',
}, 404);
}
//return JSON
return c.json({
success: true,
message: `Detail Data Post By ID : ${postId}`,
data: post
}, 200);
} catch (e: unknown) {
console.error(`Error finding post: ${e}`);
}
}
/**
* Updating a post
*/
export async function updatePost(c: Context) {
try {
// Konversi tipe id menjadi number
const postId = parseInt(c.req.param('id'));
//get body request
const body = await c.req.parseBody();
//check if title and content is string
const title = typeof body['title'] === 'string' ? body['title'] : '';
const content = typeof body['content'] === 'string' ? body['content'] : '';
//update post with prisma
const post = await prisma.post.update({
where: { id: postId },
data: {
title: title,
content: content,
updatedAt: new Date(),
},
});
//return JSON
return c.json({
success: true,
message: 'Post Updated Successfully!',
data: post
}, 200);
} catch (e: unknown) {
console.error(`Error updating post: ${e}`);
}
}
/**
* Deleting a post
*/
export async function deletePost(c: Context) {
try {
// Konversi tipe id menjadi number
const postId = parseInt(c.req.param('id'));
//delete post with prisma
await prisma.post.delete({
where: { id: postId },
});
//return JSON
return c.json({
success: true,
message: 'Post Deleted Successfully!',
}, 200);
} catch (e: unknown) {
console.error(`Error deleting post: ${e}`);
}
}
Tahap 2: Penulisan Kode & Konfigurasi
export async function deletePost(c: Context) {
//...
}
Tahap 3: Penulisan Kode & Konfigurasi
// Konversi tipe id menjadi number
const postId = parseInt(c.req.param('id'));
Tahap 4: Penulisan Kode & Konfigurasi
//delete post with prisma
await prisma.post.delete({
where: { id: postId },
});
Tahap 5: Penulisan Kode & Konfigurasi
//return JSON
return c.json({
success: true,
message: 'Post Deleted Successfully!',
}, 200);
Tahap 6: Penulisan Kode & Konfigurasi
//import hono
import { Hono } from 'hono';
//import controller
import { getPosts, createPost, getPostById, updatePost, deletePost } from '../controllers/PostController';
//inistialize router
const router = new Hono()
//routes posts index
router.get('/', (c) => getPosts(c));
//routes posts create
router.post('/', (c) => createPost(c));
//routes posts detail
router.get('/:id', (c) => getPostById(c));
//route post update
router.patch('/:id', (c) => updatePost(c));
//route post delete
router.delete('/:id', (c) => deletePost(c));
export const Routes = router;
Tahap 7: Penulisan Kode & Konfigurasi
//import controller
import { getPosts, createPost, getPostById, updatePost, deletePost } from '../controllers/PostController';
Tahap 8: Penulisan Kode & Konfigurasi
//route post delete
router.delete('/:id', (c) => deletePost(c));
Tahap 9: Penulisan Kode & Konfigurasi
{
"success": true,
"message": "Post Deleted Successfully!"
}
Selalu gunakan pendekatan deklaratif, validasi input seawal mungkin di boundary layer, dan lakukan logging terstruktur untuk memudahkan observability ketika sistem dijalankan di lingkungan cloud produksi.
Kesimpulan
Dengan mengikuti langkah-langkah terstruktur di atas, implementasi modul Anda akan jauh lebih rapi, aman dari bug umum, serta siap diskalakan ke lingkungan produksi.
Nantikan artikel tutorial praktis lainnya seputar fullstack development, microservices, dan otomasi AI di Blog Engineering SiHubung. Selamat mencoba!