diff --git a/src/words/words.controller.ts b/src/words/words.controller.ts index a5cf8f5..5cad236 100644 --- a/src/words/words.controller.ts +++ b/src/words/words.controller.ts @@ -6,8 +6,12 @@ export class WordsController { constructor(private readonly service: WordsService) {} @Get() - findAll(@Query('category') category?: string) { - return this.service.findAll(category); + findAll( + @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') diff --git a/src/words/words.service.ts b/src/words/words.service.ts index fec5683..aa4e395 100644 --- a/src/words/words.service.ts +++ b/src/words/words.service.ts @@ -7,9 +7,15 @@ import { Word } from './entities/word.entity'; export class WordsService { constructor(@InjectRepository(Word) private repo: Repository) {} - findAll(category?: string) { - if (category) return this.repo.find({ where: { category } }); - return this.repo.find(); + async findAll(category?: string, page = 1, limit = 50) { + const where = category ? { category } : {}; + 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 { @@ -29,8 +35,12 @@ export class WordsService { .where('daily_date = :today AND is_daily = true', { today }) .execute(); - const all = await this.repo.find(); - const shuffled = all.sort(() => Math.random() - 0.5).slice(0, 10); + const shuffled = await this.repo + .createQueryBuilder('w') + .orderBy('RAND()') + .limit(10) + .getMany(); + for (const w of shuffled) { w.is_daily = true; w.daily_date = today;