Thư viện tiện ích cho NestJS với TypeORM base entities, decorators và các công cụ hỗ trợ phổ biến.
bun add dev4fun-utilshoặc
npm install dev4fun-utilsBase entity cho TypeORM với các trường tự động:
id: Primary key tự động tăngcreatedAt: Thời gian tạo (timestamp)updatedAt: Thời gian cập nhật (timestamp)deletedAt: Thời gian xóa (soft delete, timestamp)
import { BaseTypeormEntity } from 'dev4fun-utils';
import { Entity } from 'typeorm';
@Entity()
export class User extends BaseTypeormEntity {
// Các trường của bạn
}Class exception mở rộng từ HttpException với mã lỗi tùy chỉnh:
import { BaseException } from 'dev4fun-utils';
// Sử dụng các exception có sẵn
throw BaseException.NOT_FOUND;
throw BaseException.BAD_REQUEST;
throw BaseException.UNAUTHORIZED;
throw BaseException.FORBIDDEN;
throw BaseException.INTERNAL_SERVER_ERROR;
throw BaseException.SERVICE_UNAVAILABLE;
throw BaseException.GATEWAY_TIMEOUT;
throw BaseException.PRECONDITION_FAILED;
throw BaseException.PAYLOAD_TOO_LARGE;
throw BaseException.UNPROCESSABLE_ENTITY;
throw BaseException.TOO_MANY_REQUESTS;
// Hoặc tạo exception tùy chỉnh
throw new BaseException('Custom message', 400, 'CUSTOM_ERROR');Thử lại method khi gặp lỗi:
import { Retry } from 'dev4fun-utils';
class MyService {
@Retry(3, 1000) // Thử lại 3 lần, mỗi lần cách nhau 1 giây
async fetchData() {
// Code của bạn
}
}Thiết lập timeout cho method:
import { Timeout } from 'dev4fun-utils';
class MyService {
@Timeout(5000) // Timeout sau 5 giây
async fetchData() {
// Code của bạn
}
}Cache kết quả của method:
import { Cache } from 'dev4fun-utils';
class MyService {
@Cache(60000) // Cache trong 60 giây
async getData() {
// Code của bạn
}
}Log thông tin khi method được gọi:
import { Watch } from 'dev4fun-utils';
class MyService {
@Watch()
async processData(data: any) {
// Code của bạn
}
}Validate tham số không được null:
import { Validate, NonNull } from 'dev4fun-utils';
class MyService {
@Validate()
async processData(@NonNull data: string) {
// Code của bạn
}
}DTO cho ID:
import { IdDto } from 'dev4fun-utils';
class MyController {
@Get(':id')
async getById(@Param() params: IdDto) {
// params.id là number
}
}DTO cho phân trang:
import { PageDto } from 'dev4fun-utils';
class MyController {
@Get()
async getList(@Query() query: PageDto) {
// query.page, query.size, query.search, query.sort
}
}DTO cho khoảng thời gian:
import { TimeDto } from 'dev4fun-utils';
class MyController {
@Get()
async getByTime(@Query() query: TimeDto) {
// query.startDate, query.endDate
}
}Struct cho phân trang với TypeORM:
import { Page, PageDto } from 'dev4fun-utils';
import { SelectQueryBuilder } from 'typeorm';
async function getUsers(dto: PageDto) {
const page = new Page(dto, 0);
page.queryBuilder = userRepository.createQueryBuilder('user');
await page.execute();
return page; // page.data, page.total, page.totalPages, etc.
}Xử lý dữ liệu theo batch:
import { Batch } from 'dev4fun-utils';
const batch = Batch.fromArray([1, 2, 3, 4, 5], 2); // Chia thành batch 2 phần tử
await batch.runAsync(async (items, index) => {
console.log(`Batch ${index}:`, items);
}, false, 1000); // Chạy tuần tự, delay 1 giây giữa các batchHàng đợi (FIFO):
import { Queue } from 'dev4fun-utils';
const queue = Queue.fromArray([1, 2, 3]);
queue.enqueue(4); // Thêm vào cuối
const item = queue.dequeue(); // Lấy phần tử đầu tiên
const peek = queue.peek(); // Xem phần tử đầu tiên không xóaNgăn xếp (LIFO):
import { Stack } from 'dev4fun-utils';
const stack = Stack.fromArray([1, 2, 3]);
stack.push(4); // Thêm vào đầu
const item = stack.pop(); // Lấy phần tử đầu tiên
const top = stack.top(); // Xem phần tử đầu tiên không xóaCấu trúc cây:
import { Tree, TreeNode } from 'dev4fun-utils';
const tree = new Tree('root');
const node1 = tree.addNode('node1');
const node2 = tree.addNode('node2');
node1.addChild(new TreeNode('child1', node1));Các tiện ích cho method:
import { MethodUtil } from 'dev4fun-utils';
// Delay
await MethodUtil.delay(1000); // Delay 1 giây
// Execute với timeout
await MethodUtil.executeWithTimeout(promise, 5000);
// Execute với retry
await MethodUtil.executeWithRetry(promise, 3, 1000);
// Execute command
const output = await MethodUtil.cmdExecute('ls -la');Các tiện ích cho số:
import { NumberUtil } from 'dev4fun-utils';
// Random integer
const num = NumberUtil.nextInt(1, 100);
// Random float
const float = NumberUtil.nextFloat(0, 1);
// Format VND
const formatted = NumberUtil.formatVND(1000000); // "1,000,000"Các tiện ích cho chuỗi:
import { StringUtil } from 'dev4fun-utils';
// Hash password
const hash = await StringUtil.hashValue('password', 16);
// Verify hash
const isValid = await StringUtil.verifyHash('password', hash);
// Random string
const random = StringUtil.randomString(10);Import CommonModule vào ứng dụng NestJS của bạn:
import { CommonModule } from 'dev4fun-utils';
import { Module } from '@nestjs/common';
@Module({
imports: [CommonModule],
})
export class AppModule {}MIT
Nguyen Chau Tuan