32 lines
1.3 KiB
TypeScript
32 lines
1.3 KiB
TypeScript
import { BadRequestException } from '@nestjs/common';
|
|
|
|
const dayFormatter = new Intl.DateTimeFormat('en-CA', {
|
|
timeZone: 'Asia/Shanghai',
|
|
year: 'numeric',
|
|
month: '2-digit',
|
|
day: '2-digit',
|
|
});
|
|
export const todayKey = (now = new Date()) => dayFormatter.format(now);
|
|
export const databaseDay = (key: string) => new Date(`${key}T00:00:00.000Z`);
|
|
export const startOfDay = (key: string) => new Date(`${key}T00:00:00+08:00`);
|
|
export const addDays = (key: string, days: number) =>
|
|
new Date(databaseDay(key).getTime() + days * 86_400_000).toISOString().slice(0, 10);
|
|
export function analyticsDate(value?: string, now = new Date()) {
|
|
const key = value || todayKey(now);
|
|
if (
|
|
!/^\d{4}-\d{2}-\d{2}$/.test(key) ||
|
|
!Number.isFinite(databaseDay(key).getTime()) ||
|
|
databaseDay(key).toISOString().slice(0, 10) !== key ||
|
|
key > todayKey(now)
|
|
) {
|
|
throw new BadRequestException('统计日期必须为有效的北京时间日期,不能晚于今天');
|
|
}
|
|
return key;
|
|
}
|
|
export function analyticsPage(page = 1, pageSize = 25) {
|
|
if (!Number.isInteger(page) || page < 1 || ![10, 25, 50, 100].includes(pageSize))
|
|
throw new BadRequestException('分页参数无效');
|
|
return { page, pageSize };
|
|
}
|
|
export const mutableDay = (day: string, now = new Date()) => day < todayKey(now) && day >= addDays(todayKey(now), -3);
|