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';
|
||||
import { ShowsService } from './shows.service';
|
||||
import { ShowDto } from './dto/show.dto';
|
||||
import { PaginationDto } from 'src/pagination.dto';
|
||||
|
||||
@Controller('shows')
|
||||
export class ShowsController {
|
||||
|
|
@ -36,10 +37,15 @@ export class ShowsController {
|
|||
}
|
||||
|
||||
@Get()
|
||||
async findAll() {
|
||||
async findAll(@Query() pagination: PaginationDto) {
|
||||
try {
|
||||
const shows = await this.showsService.findAll();
|
||||
return { status: 'Ok', shows, totalShows: shows.length };
|
||||
const { page, limit } = pagination;
|
||||
const serviceResponse = await this.showsService.findAll(page, limit);
|
||||
return {
|
||||
status: 'Ok',
|
||||
shows: serviceResponse.shows,
|
||||
showCount: serviceResponse.showCount,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new InternalServerErrorException({
|
||||
status: error.name,
|
||||
|
|
|
|||
|
|
@ -13,8 +13,22 @@ export class ShowsService {
|
|||
return show.save();
|
||||
}
|
||||
|
||||
async findAll(): Promise<Show[]> {
|
||||
return this.showModel.find();
|
||||
async findAll(page: number, showsPerPage: number): Promise<any> {
|
||||
// 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> {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue