diff --git a/src/app.controller.ts b/src/app.controller.ts index 3d6d7f5..dd4e321 100644 --- a/src/app.controller.ts +++ b/src/app.controller.ts @@ -1,6 +1,7 @@ -import { Controller, Get, UseInterceptors } from '@nestjs/common'; +import { Controller, Get, Query, UseInterceptors } from '@nestjs/common'; import { AppService } from './app.service'; import { CacheInterceptor, CacheTTL } from '@nestjs/cache-manager'; +import { HistoryQueryDto } from './dtos/history-query.dto'; @Controller() export class AppController { @@ -12,4 +13,9 @@ export class AppController { getWeather() { return this.appService.getWeather(); } + + @Get('history') + getWeatherHistory(@Query() query: HistoryQueryDto) { + return this.appService.getWeatherHistory(query); + } } diff --git a/src/app.service.ts b/src/app.service.ts index d07ad1c..2f11b6f 100644 --- a/src/app.service.ts +++ b/src/app.service.ts @@ -5,10 +5,11 @@ import { OnApplicationShutdown, } from '@nestjs/common'; import WS1080 from './module/ws1080'; -import { Repository } from 'typeorm'; +import { MoreThan, Repository } from 'typeorm'; import { WeatherEntity } from './entities/weather.entity'; import { InjectRepository } from '@nestjs/typeorm'; import { Cron } from '@nestjs/schedule'; +import { HistoryQueryDto } from './dtos/history-query.dto'; @Injectable() export class AppService implements OnApplicationShutdown { @@ -60,6 +61,30 @@ export class AppService implements OnApplicationShutdown { } } + async getWeatherHistory(query: HistoryQueryDto) { + const pageSize = Number(query.pageSize) || 100; + const page = Number(query.page) || 1; + const [list, rowCount] = await this.weatherRepository.findAndCount({ + where: query.since + ? { date: MoreThan(new Date(query.since)) } + : undefined, + order: { date: -1 }, + take: pageSize, + skip: (page - 1) * pageSize, + }); + const pageCount = Math.ceil(rowCount / pageSize); + + return { + list, + pagination: { + page, + pageSize, + pageCount, + rowCount, + }, + }; + } + @Cron('0 * * * *') scheduledPulls() { this.getWeather().catch(() => { diff --git a/src/dtos/history-query.dto.ts b/src/dtos/history-query.dto.ts new file mode 100644 index 0000000..99d6012 --- /dev/null +++ b/src/dtos/history-query.dto.ts @@ -0,0 +1,5 @@ +export class HistoryQueryDto { + since?: string; + page?: string; + pageSize?: string; +}