@fastify-core/base
v1.0.2
Published
Fastify Core là một library backend dùng cho ứng dụng Fastify, tập trung vào các thành phần thường gặp trong hệ thống API: model layer, request handling, file upload, JWT, validation, route và utility helpers.
Readme
Fastify Core
Fastify Core là một library backend dùng cho ứng dụng Fastify, tập trung vào các thành phần thường gặp trong hệ thống API: model layer, request handling, file upload, JWT, validation, route và utility helpers.
Dự án này được thiết kế để dùng như một package npm cho các ứng dụng Node.js / Fastify, đặc biệt là khi bạn cần một nền tảng backend nhanh, gọn và có sẵn các helper phổ biến.
Tính năng
- BaseModel cho truy vấn MySQL CRUD, where builder, pagination, query raw
- FastRequest để đọc request, xử lý form-data, export file upload
- FileUpload để upload, resize/check type, move file giữa thư mục
- JWTApp để tạo và verify token
- Validation để validate dữ liệu theo rule
- Route để quản lý danh sách route theo module
- Common utilities cho password, slug, date, random, keyword, v.v.
- CSRF protection helper cho request có thay đổi state
Yêu cầu
- Node.js >= 24
- Fastify >= 5
- MySQL / mysql2
- TypeScript (khuyến nghị)
Cài đặt
npm install @fastify-core/baseImport
import {
BaseModel,
FastRequest,
FileUpload,
JWTApp,
Route,
Validation,
makePassword,
checkPassword,
slugify,
ensureCsrfProtection,
} from '@fastify-core/base';Ví dụ sử dụng
1. Tạo model
import { BaseModel } from '@fastify-core/base';
import type { Pool } from 'mysql2/promise';
export class UserModel extends BaseModel<any> {
table = 'users';
constructor(pool: Pool) {
super(pool);
}
}2. Validate dữ liệu
import { Validation } from '@fastify-core/base';
const payload = {
email: '[email protected]',
password: '123456',
};
const rules = {
email: 'required|minLen(5)',
password: 'required|minLen(6)',
};
try {
await new Validation().runValidate(payload, rules);
console.log('Valid');
} catch (error: any) {
console.error(error.message);
}3. Xử lý request
import { FastRequest } from '@fastify-core/base';
fastify.post('/user', async (request) => {
const req = new FastRequest(request as any);
await req.start();
const name = req.getPost('name', '', 'stripTags');
const age = req.getPost('age', 0, 'int');
await req.end();
return { name, age };
});4. Upload file
import { FileUpload } from '@fastify-core/base';
const files = { avatar: [/* file object */] } as any;
const uploader = new FileUpload(files, 'static');
const uploaded = await uploader.uploadFile('avatar', 'users');
console.log(uploaded);5. JWT
import { JWTApp } from '@fastify-core/base';
const token = JWTApp.createToken({ id: 1, fullname: 'Admin' }, request);
const payload = JWTApp.verifyToken(request);6. CSRF
import { ensureCsrfProtection } from '@fastify-core/base';
const result = ensureCsrfProtection(request, session);
if (!result.allowed) {
throw new Error(result.reason || 'csrf_invalid');
}API chính
BaseModel
BaseModel hỗ trợ các method cơ bản như:
findOne(filter)find(filter)save(item, conn?)update(data, filter, conn?)query(sql, params?, conn?)buildWhere(filter, als?)getConnection()
FastRequest
start()end()isPost()isGet()getPost(name, defaultValue, type)getParam(name, defaultValue, type)get(name, defaultValue, type)getHeader(key)
FileUpload
uploadFile(fieldName, folders)uploadFiles(fieldName, folders)checkFile(fieldName, type)copyFiles(files)removeFile(fileName, uploadType)removeFiles(paths, uploadType)
Validation
Validation hỗ trợ rule như:
requiredrequiredIdminLen(6)maxLen(255)equalLen(10)rangeNum(1, 50)min(10)max(100)integer
Common helpers
Một số utility có sẵn:
makePassword(value)checkPassword(value, hash)randomText(length)removeVietnameseTones(str)slugify(text)generateKeywords(text)parseDate(date)formatDate(date, format)toMySQLDateNowVN()sumArrCol(items, col)
Route
Route giúp quản lý route tập trung và sinh CRUD nhanh:
const route = new Route();
route.add('/admin/user', [
{ link: '/list', module: 'user', controller: UserController, action: 'index' },
{ link: '/detail/:id', module: 'user', controller: UserController, action: 'detail' },
]);
route.addGS('/admin/product', ProductController, 'product');Environment variables
Một số tính năng JWT hoặc session cần biến môi trường:
JWT_SECRET_KEY=your_secret_key
JWT_KEY=your_verify_token
JWT_AUD=your_audience
JWT_ISS=your_issuer
JWT_TIMEOUT=3600Lưu ý về publish package
Package hiện đang cấu hình export theo kiểu ESM, nên khi dùng trong môi trường Node/TypeScript cần đảm bảo project của bạn hỗ trợ ESM nếu import theo kiểu module.
