From ded3f0fd83720f7e133e90df136fd854a6251d2d Mon Sep 17 00:00:00 2001 From: Evert Prants Date: Sun, 17 Sep 2023 10:05:52 +0300 Subject: [PATCH] history query --- src/app.controller.ts | 8 +++++++- src/app.service.ts | 27 ++++++++++++++++++++++++++- src/dtos/history-query.dto.ts | 5 +++++ 3 files changed, 38 insertions(+), 2 deletions(-) create mode 100644 src/dtos/history-query.dto.ts 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; +}