BaseController 与 BaseService

1.BaseController

主要用来统一分页返回:
return this.paginationResult(items, total, queryDto);
返回:
{"items":[],"total":100,"page":1,"pageSize":15,"totalPages":7}

2.BaseService<T>

主程序的大多数 CRUD service 都建议继承它。
基础写法:
@Injectable
export class ArticleService extends BaseService<Article> { constructor( @InjectRepository(Article) private readonly articleRepository: Repository<Article>, ) { super(articleRepository); }
}
最常用方法:
create(dto, options?)
createMany(dtos, options?)
findOne(options?)
findOneById(id, options?)
findAll(options?)
paginate(paginationDto, options?)
paginateQueryBuilder(queryBuilder, paginationDto, ...)
updateById(id, dto, options?)
delete(id)
deleteMany(ids)
restore(id)
count(options?)

create

await this.create({ title: "Hello", content: "World",
});

paginate

return this.paginate(queryDto, { where, relations: ["author"], order: { createdAt: "DESC" },
});

paginateQueryBuilder

适合复杂查询:
const qb = this.repository.createQueryBuilder("article");
return this.paginateQueryBuilder(qb, queryDto);

字段过滤

await this.findOneById(id, { excludeFields: ["password", "author.password"],
}); await this.findOneById(id, { includeFields: ["id", "title", "author.id", "author.nickname"],
});

事务

return this.withTransaction(async (manager) => { const articleRepo = manager.getRepository(Article); const categoryRepo = manager.getRepository(Category); const article = articleRepo.create(dto); await articleRepo.save(article); await categoryRepo.increment({ id: dto.categoryId }, "articleCount", 1); return article;
});

PostgreSQL 辅助条件

可在子类里复用:
ilike(field, value)
textSearch(field, value)
jsonQuery(jsonField, path, value)
arrayContains(field, value)

319 篇文档 · 内容同步自官方帮助中心