Toidicode.com

Toidicode.com

BASIC TO ADVANCE

Bài 14: Cấu trúc ứng dụng theo MVC trong Express

Ở bài trước MiniBlog đã CRUD được bài viết trên MySQL, nhưng câu SQL, tạo slug, báo 404 và render view đều nằm chung trong route. Tiếp tục với series, bài này mình sẽ giới thiệu với mọi người cách cấu trúc ứng dụng theo MVC trong Express: tách model, service, controller, cùng migration và seed dữ liệu.

1. MVC là gì?

MVC (Model - View - Controller) chia code theo nhiệm vụ: model làm việc với dữ liệu, view hiển thị (các file .ejs từ Bài 8), controller nhận request, lấy dữ liệu rồi render view hoặc redirect.

Mình thêm lớp service chứa quy tắc nghiệp vụ (tạo slug, báo 404...) và không dùng tới req, res, nên script dòng lệnh hay API sau này đều gọi lại được.

Express không quy định cấu trúc thư mục (xem FAQ của Express), nên mình tổ chức MiniBlog như sau:

miniblog/
├── controllers/   # nhận request, render/redirect
├── services/      # quy tắc nghiệp vụ
├── models/        # câu SQL
├── routes/        # nối URL với controller
├── database/      # migration và seed
├── lib/, middlewares/, validators/, views/, public/
├── app.js
└── server.js

Các lớp gọi theo một chiều: route → controller → service → model → lib/db.js. Mỗi file import thẳng file nó cần (ESM chỉ chạy mỗi module một lần nên vẫn chung một pool), quản lý dependency đơn giản vậy là đủ cho MiniBlog.

2. Tách model.

Model gom các câu SQL của bảng posts, mỗi hàm trả về dữ liệu thay vì [rows, fields]:

- models/post.js

import pool from '../lib/db.js';

export async function findAll() {
    const [rows] = await pool.query('SELECT id, title, slug FROM posts ORDER BY id DESC');
    return rows;
}

export async function findBySlug(slug) {
    const [rows] = await pool.execute('SELECT * FROM posts WHERE slug = ?', [slug]);
    return rows[0] ?? null;
}

export async function findById(id) {
    const [rows] = await pool.execute('SELECT * FROM posts WHERE id = ?', [id]);
    return rows[0] ?? null;
}

// Có bài khác (trừ exceptId) trùng tiêu đề hoặc slug không
export async function existsByTitleOrSlug(title, slug, exceptId) {
    const [rows] = await pool.execute(
        'SELECT id FROM posts WHERE (title = ? OR slug = ?) AND id <> ?',
        [title, slug, exceptId],
    );
    return rows.length > 0;
}

export async function create({ title, slug, content }) {
    await pool.execute(
        'INSERT INTO posts (title, slug, content, published_at) VALUES (?, ?, ?, NOW())',
        [title, slug, content],
    );
}

export async function update(id, { title, content }) {
    await pool.execute('UPDATE posts SET title = ?, content = ? WHERE id = ?', [title, content, id]);
}

export async function remove(id) {
    const [result] = await pool.execute('DELETE FROM posts WHERE id = ?', [id]);
    return result.affectedRows > 0;
}

3. Service và controller.

Model không biết gì về HTTP, không tìm thấy thì trả null. Service gọi model và throw HttpError 404 khi đó:

- services/post-service.js

import * as Post from '../models/post.js';
import HttpError from '../lib/http-error.js';
import slugify from '../lib/slugify.js';

// Không có dữ liệu (null hoặc false) thì báo lỗi 404
function ensureFound(value) {
    if (!value) {
        throw new HttpError(404, 'Không tìm thấy bài viết');
    }
    return value;
}

export function listPosts() {
    return Post.findAll();
}

export async function getPostBySlug(slug) {
    return ensureFound(await Post.findBySlug(slug));
}

export async function getPostById(id) {
    return ensureFound(await Post.findById(id));
}

export function isTitleTaken(title, exceptId = 0) {
    return Post.existsByTitleOrSlug(title, slugify(title), exceptId);
}

export async function createPost({ title, content }) {
    const slug = slugify(title);
    await Post.create({ title, slug, content });
    return slug;
}

export function updatePost(id, { title, content }) {
    return Post.update(id, { title, content });
}

export async function deletePost(id) {
    ensureFound(await Post.remove(id));
}

Controller là các handler cũ của route, giờ gọi service thay vì pool:

- controllers/post-controller.js (đoạn chính)

import { validationResult, matchedData } from 'express-validator';
import * as postService from '../services/post-service.js';

// ...

export async function store(req, res) {
    const result = validationResult(req);
    if (!result.isEmpty()) {
        return res.status(422).render('posts/form', {
            title: 'Viết bài mới',
            action: '/posts',
            errors: result.mapped(),
            old: matchedData(req, { onlyValidData: false }),
        });
    }
    const slug = await postService.createPost(matchedData(req));
    res.redirect(303, `/posts/${slug}`);
}

export async function show(req, res) {
    const post = await postService.getPostBySlug(req.params.slug);
    res.render('posts/show', { title: post.title, post });
}

Các handler newForm, edit, update, destroy chuyển nguyên từ Bài 13, chỗ dùng findPostById() hay pool thay bằng postService.getPostById(), updatePost(), deletePost(). Lỗi service throw tự tới error handler (Bài 7).

File route chỉ còn nối URL với controller, cùng router.param('id') kiểm tra id từ Bài 13:

- routes/posts.js

import express from 'express';
import * as postController from '../controllers/post-controller.js';
import { postRules } from '../validators/post.js';
import HttpError from '../lib/http-error.js';

const router = express.Router();

// MySQL tự ép '2abc' thành 2, nên :id không phải số nguyên dương thì báo 404 luôn
router.param('id', (req, res, next, id) => {
    next(/^[1-9]\d*$/.test(id) ? undefined : new HttpError(404, 'Không tìm thấy bài viết'));
});

router.get('/new', postController.newForm); // phải đặt trước /:slug
router.post('/', postRules, postController.store);
router.get('/:slug', postController.show);
router.get('/:id/edit', postController.edit);
router.put('/:id', postRules, postController.update);
router.delete('/:id', postController.destroy);

export default router;

Tương tự, controllers/page-controller.js có home (render index với await postService.listPosts()) và about, routes/pages.js gọi hai hàm này. Trong validators/post.js, custom() gọi isTitleTaken(value, req.params.id) của service thay cho câu SQL, quy tắc chặn slug rỗng hoặc new giữ nguyên.

4. Migration.

File schema.sql ở Bài 12 xoá hết bảng rồi tạo lại, thêm một bảng là mất dữ liệu. Migration là các file SQL đánh số, mỗi file là một lần thay đổi cấu trúc database và chỉ chạy một lần.

Các bạn chuyển database/schema.sql thành database/migrations/001-create-tables.sql, chỉ giữ ba câu CREATE TABLE (bỏ SET NAMES, DROP TABLE, INSERT). Script chạy migration:

- database/migrate.js

import fs from 'node:fs/promises';
import mysql from 'mysql2/promise';
import { dbConfig } from '../lib/db.js';

const dir = import.meta.dirname + '/migrations';

// Kết nối riêng, cho phép chạy cả file nhiều câu SQL một lần
const db = await mysql.createConnection({ ...dbConfig, multipleStatements: true });

// Bảng ghi lại các migration đã chạy
await db.query(`CREATE TABLE IF NOT EXISTS migrations (
    name VARCHAR(255) PRIMARY KEY,
    run_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
)`);
const [rows] = await db.query('SELECT name FROM migrations');
const done = rows.map((row) => row.name);

// Chạy lần lượt (theo tên file) các migration chưa chạy
const files = (await fs.readdir(dir)).filter((file) => file.endsWith('.sql')).sort();
for (const file of files) {
    if (done.includes(file)) {
        continue;
    }
    await db.query(await fs.readFile(`${dir}/${file}`, 'utf8'));
    await db.execute('INSERT INTO migrations (name) VALUES (?)', [file]);
    console.log(`Đã chạy ${file}`);
}
console.log('Database đã cập nhật');

await db.end();

Trong lib/db.js, mình tách object cấu hình thành export const dbConfig = { host: process.env.DB_HOST, ... } và tạo pool bằng mysql.createPool({ ...dbConfig, connectionLimit: 10 }). multipleStatements (mặc định tắt) chỉ bật cho script này, pool của ứng dụng vẫn tắt để hạn chế hậu quả của SQL injection.

Trong package.json, các bạn thêm script "db:migrate": "node --env-file=.env database/migrate.js" và "db:seed": "node --env-file=.env database/seed.js". Database từ Bài 12 đã có ba bảng, nên các bạn xoá chúng một lần rồi chạy migration:

docker exec miniblog-mysql mysql -u miniblog -psecret --default-character-set=utf8mb4 miniblog -e 'DROP TABLE IF EXISTS comments, posts, users'

npm run db:migrate
# ...
# Đã chạy 001-create-tables.sql
# Database đã cập nhật

npm run db:migrate
# ...
# Database đã cập nhật

Lần thứ hai không làm gì vì 001-create-tables.sql đã có trong bảng migrations, bài sau cần thay đổi thì thêm file 002-...sql. Dự án lớn có thể dùng thư viện như Knex hay Umzug, cũng ghi lại các migration đã chạy.

5. Seed dữ liệu mẫu.

Seed là script thêm dữ liệu mẫu để phát triển, thử nghiệm. Bài mẫu thêm qua service nên slug tạo giống khi viết bài trên web:

- database/seed.js

import pool from '../lib/db.js';
import { createPost } from '../services/post-service.js';

const posts = [
    { title: 'Những tính năng mới trong Express 5', content: 'Giới thiệu Express 5...' },
    { title: 'Route trong Express 5', content: 'Route trong Express...' },
];

// Xoá bài viết cũ (bình luận bị xoá theo) và cho id đếm lại từ 1
await pool.query('DELETE FROM posts');
await pool.query('ALTER TABLE posts AUTO_INCREMENT = 1');

for (const post of posts) {
    await createPost(post);
}
console.log(`Đã thêm ${posts.length} bài viết`);

await pool.end();

Chạy npm run db:seed sẽ in ra Đã thêm 2 bài viết. Từ giờ, muốn đưa bài viết về ban đầu thì các bạn chạy lại lệnh này thay cho import schema.sql. Chạy npm run dev thử lại thêm, sửa, xoá như Bài 13, mọi thứ vẫn như cũ.

Code đầy đủ của MiniBlog sau bài này nằm ở tag bai-14 trên GitHub; các thay đổi của riêng bài này: so sánh bai-13...bai-14.

6. Lời kết.

Như vậy là chúng ta đã cấu trúc ứng dụng theo MVC trong Express: model chứa SQL, service chứa nghiệp vụ, controller xử lý request, view hiển thị, cùng migration và seed cho database. Bài sau mình sẽ giới thiệu với mọi người về session và cookie trong Express, dùng flash message để báo sau khi lưu bài viết.

Đăng ký nhận tin.

Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!

Vũ Thanh Tài

About author
The best way to learn is to share
Xem tất cả bài đăng

0 Comments

Bài viết chưa có ai bình luận, hãy là người đầu tiên đi bạn!

Bình luận

Captcha