npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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/base

Import

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ư:

  • required
  • requiredId
  • minLen(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=3600

Lư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.