fix: add pagination to words findAll, fix getDailyWords performance
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 39s
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 39s
This commit is contained in:
parent
03ed93d462
commit
7be273b3a2
@ -6,8 +6,12 @@ export class WordsController {
|
|||||||
constructor(private readonly service: WordsService) {}
|
constructor(private readonly service: WordsService) {}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
findAll(@Query('category') category?: string) {
|
findAll(
|
||||||
return this.service.findAll(category);
|
@Query('category') category?: string,
|
||||||
|
@Query('page') page?: string,
|
||||||
|
@Query('limit') limit?: string,
|
||||||
|
) {
|
||||||
|
return this.service.findAll(category, page ? +page : 1, limit ? +limit : 50);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get('daily')
|
@Get('daily')
|
||||||
|
|||||||
@ -7,9 +7,15 @@ import { Word } from './entities/word.entity';
|
|||||||
export class WordsService {
|
export class WordsService {
|
||||||
constructor(@InjectRepository(Word) private repo: Repository<Word>) {}
|
constructor(@InjectRepository(Word) private repo: Repository<Word>) {}
|
||||||
|
|
||||||
findAll(category?: string) {
|
async findAll(category?: string, page = 1, limit = 50) {
|
||||||
if (category) return this.repo.find({ where: { category } });
|
const where = category ? { category } : {};
|
||||||
return this.repo.find();
|
const [data, total] = await this.repo.findAndCount({
|
||||||
|
where,
|
||||||
|
skip: (page - 1) * limit,
|
||||||
|
take: limit,
|
||||||
|
order: { id: 'ASC' },
|
||||||
|
});
|
||||||
|
return { data, total, page, limit, totalPages: Math.ceil(total / limit) };
|
||||||
}
|
}
|
||||||
|
|
||||||
findByIds(ids: number[]): Promise<Word[]> {
|
findByIds(ids: number[]): Promise<Word[]> {
|
||||||
@ -29,8 +35,12 @@ export class WordsService {
|
|||||||
.where('daily_date = :today AND is_daily = true', { today })
|
.where('daily_date = :today AND is_daily = true', { today })
|
||||||
.execute();
|
.execute();
|
||||||
|
|
||||||
const all = await this.repo.find();
|
const shuffled = await this.repo
|
||||||
const shuffled = all.sort(() => Math.random() - 0.5).slice(0, 10);
|
.createQueryBuilder('w')
|
||||||
|
.orderBy('RAND()')
|
||||||
|
.limit(10)
|
||||||
|
.getMany();
|
||||||
|
|
||||||
for (const w of shuffled) {
|
for (const w of shuffled) {
|
||||||
w.is_daily = true;
|
w.is_daily = true;
|
||||||
w.daily_date = today;
|
w.daily_date = today;
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user