Shows: add pagination to findAll
This commit is contained in:
parent
fd2f2091ee
commit
a2b747a823
2 changed files with 25 additions and 5 deletions
|
|
@ -13,6 +13,7 @@ import {
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { ShowsService } from './shows.service';
|
import { ShowsService } from './shows.service';
|
||||||
import { ShowDto } from './dto/show.dto';
|
import { ShowDto } from './dto/show.dto';
|
||||||
|
import { PaginationDto } from 'src/pagination.dto';
|
||||||
|
|
||||||
@Controller('shows')
|
@Controller('shows')
|
||||||
export class ShowsController {
|
export class ShowsController {
|
||||||
|
|
@ -36,10 +37,15 @@ export class ShowsController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
async findAll() {
|
async findAll(@Query() pagination: PaginationDto) {
|
||||||
try {
|
try {
|
||||||
const shows = await this.showsService.findAll();
|
const { page, limit } = pagination;
|
||||||
return { status: 'Ok', shows, totalShows: shows.length };
|
const serviceResponse = await this.showsService.findAll(page, limit);
|
||||||
|
return {
|
||||||
|
status: 'Ok',
|
||||||
|
shows: serviceResponse.shows,
|
||||||
|
showCount: serviceResponse.showCount,
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new InternalServerErrorException({
|
throw new InternalServerErrorException({
|
||||||
status: error.name,
|
status: error.name,
|
||||||
|
|
|
||||||
|
|
@ -13,8 +13,22 @@ export class ShowsService {
|
||||||
return show.save();
|
return show.save();
|
||||||
}
|
}
|
||||||
|
|
||||||
async findAll(): Promise<Show[]> {
|
async findAll(page: number, showsPerPage: number): Promise<any> {
|
||||||
return this.showModel.find();
|
// Default value is 1 and I can't think any reason why you would want
|
||||||
|
// a single item per page, so if showsPerPage is 1 then just don't do
|
||||||
|
// any pagination at all
|
||||||
|
let shows;
|
||||||
|
if (showsPerPage != 1) {
|
||||||
|
const skip = (page - 1) * showsPerPage;
|
||||||
|
shows = await this.showModel.find().skip(skip).limit(showsPerPage);
|
||||||
|
} else {
|
||||||
|
shows = await this.showModel.find();
|
||||||
|
}
|
||||||
|
const total = await this.showModel.countDocuments();
|
||||||
|
return {
|
||||||
|
shows: shows,
|
||||||
|
showCount: total,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async findId(id: string): Promise<any> {
|
async findId(id: string): Promise<any> {
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue