Added parseDateRangeQuery function.

This commit is contained in:
Mike Cao 2023-07-25 23:59:08 -07:00
parent a0aaeeeb57
commit 09af33c77e
15 changed files with 139 additions and 98 deletions

View file

@ -13,7 +13,7 @@ import {
import { getTeamUser } from 'queries';
import { getTeamWebsite, getTeamWebsiteByTeamMemberId } from 'queries/admin/teamWebsite';
import { validate } from 'uuid';
import { loadWebsite } from './query';
import { loadWebsite } from './load';
import { Auth } from './types';
const log = debug('umami:auth');

View file

@ -26,9 +26,20 @@ import {
differenceInCalendarMonths,
differenceInCalendarYears,
format,
max,
min,
isDate,
} from 'date-fns';
import { getDateLocale } from 'lib/lang';
const dateFuncs = {
minute: [differenceInMinutes, addMinutes, startOfMinute],
hour: [differenceInHours, addHours, startOfHour],
day: [differenceInCalendarDays, addDays, startOfDay],
month: [differenceInCalendarMonths, addMonths, startOfMonth],
year: [differenceInCalendarYears, addYears, startOfYear],
};
export function getTimezone() {
return moment.tz.guess();
}
@ -155,10 +166,12 @@ export function parseDateRange(value, locale = 'en-US') {
}
}
export function getAllowedUnits(unit) {
export function getAllowedUnits(startDate, endDate) {
const units = ['minute', 'hour', 'day', 'month', 'year'];
const minUnit = getMinimumUnit(startDate, endDate);
const index = units.indexOf(minUnit);
return units.splice(units.indexOf(unit));
return index >= 0 ? units.splice(index) : [];
}
export function getMinimumUnit(startDate, endDate) {
@ -196,14 +209,6 @@ export function getDateFromString(str) {
return new Date(year, month - 1, day);
}
const dateFuncs = {
minute: [differenceInMinutes, addMinutes, startOfMinute],
hour: [differenceInHours, addHours, startOfHour],
day: [differenceInCalendarDays, addDays, startOfDay],
month: [differenceInCalendarMonths, addMonths, startOfMonth],
year: [differenceInCalendarYears, addYears, startOfYear],
};
export function getDateArray(data, startDate, endDate, unit) {
const arr = [];
const [diff, add, normalize] = dateFuncs[unit];
@ -249,3 +254,11 @@ export function dateFormat(date, str, locale = 'en-US') {
locale: getDateLocale(locale),
});
}
export function maxDate(...args) {
return max(args.filter(n => isDate(n)));
}
export function minDate(...args) {
return min(args.filter(n => isDate(n)));
}

51
lib/load.ts Normal file
View file

@ -0,0 +1,51 @@
import cache from 'lib/cache';
import { getWebsite, getSession, getUser } from 'queries';
import { User, Website, Session } from '@prisma/client';
export async function loadWebsite(websiteId: string): Promise<Website> {
let website;
if (cache.enabled) {
website = await cache.fetchWebsite(websiteId);
} else {
website = await getWebsite({ id: websiteId });
}
if (!website || website.deletedAt) {
return null;
}
return website;
}
export async function loadSession(sessionId: string): Promise<Session> {
let session;
if (cache.enabled) {
session = await cache.fetchSession(sessionId);
} else {
session = await getSession({ id: sessionId });
}
if (!session) {
return null;
}
return session;
}
export async function loadUser(userId: string): Promise<User> {
let user;
if (cache.enabled) {
user = await cache.fetchUser(userId);
} else {
user = await getUser({ id: userId });
}
if (!user || user.deletedAt) {
return null;
}
return user;
}

View file

@ -73,5 +73,6 @@ export const useAuth = createMiddleware(async (req, res, next) => {
}
(req as any).auth = { user, token, shareToken, authKey };
next();
});

View file

@ -1,51 +1,30 @@
import cache from 'lib/cache';
import { getWebsite, getSession, getUser } from 'queries';
import { User, Website, Session } from '@prisma/client';
import { NextApiRequest } from 'next';
import { getAllowedUnits, getMinimumUnit } from './date';
import { getWebsiteDateRange } from '../queries';
export async function loadWebsite(websiteId: string): Promise<Website> {
let website;
export async function parseDateRangeQuery(req: NextApiRequest) {
const { id: websiteId, startAt, endAt, unit } = req.query;
if (cache.enabled) {
website = await cache.fetchWebsite(websiteId);
} else {
website = await getWebsite({ id: websiteId });
// All-time
if (+startAt === 0 && +endAt === 1) {
const { min, max } = await getWebsiteDateRange(websiteId as string);
return {
websiteId,
startDate: min,
endDate: max,
unit: getMinimumUnit(min, max),
};
}
if (!website || website.deletedAt) {
return null;
}
const startDate = new Date(+startAt);
const endDate = new Date(+endAt);
const minUnit = getMinimumUnit(startDate, endDate);
return website;
}
export async function loadSession(sessionId: string): Promise<Session> {
let session;
if (cache.enabled) {
session = await cache.fetchSession(sessionId);
} else {
session = await getSession({ id: sessionId });
}
if (!session) {
return null;
}
return session;
}
export async function loadUser(userId: string): Promise<User> {
let user;
if (cache.enabled) {
user = await cache.fetchUser(userId);
} else {
user = await getUser({ id: userId });
}
if (!user || user.deletedAt) {
return null;
}
return user;
return {
websiteId,
startDate,
endDate,
unit: getAllowedUnits(startDate, endDate).includes(unit as string) ? unit : minUnit,
};
}

View file

@ -5,7 +5,7 @@ import { CollectRequestBody, NextApiRequestCollect } from 'pages/api/send';
import { createSession } from 'queries';
import { validate } from 'uuid';
import cache from './cache';
import { loadSession, loadWebsite } from './query';
import { loadSession, loadWebsite } from './load';
export async function findSession(req: NextApiRequestCollect) {
const { payload } = getJsonBody<CollectRequestBody>(req);