Initial Typescript models.

This commit is contained in:
Brian Cao 2022-11-15 13:21:14 -08:00
parent 04e9f06e93
commit 0aaba8cbd1
74 changed files with 1144 additions and 768 deletions

View File

@ -19,6 +19,7 @@ CREATE TABLE event
url String,
referrer String,
--event
event_type UInt32,
event_name String,
event_data JSON,
created_at DateTime('UTC')
@ -41,6 +42,7 @@ CREATE TABLE event_queue (
screen LowCardinality(String),
language LowCardinality(String),
country LowCardinality(String),
event_type UInt32,
event_name String,
event_data String,
created_at DateTime('UTC')
@ -67,6 +69,7 @@ SELECT website_id,
screen,
language,
country,
event_type,
event_name,
event_data,
created_at

View File

@ -69,8 +69,9 @@ model WebsiteEvent {
createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
url String @db.VarChar(500)
referrer String? @db.VarChar(500)
eventName String @map("event_name") @db.VarChar(50)
eventData Json @map("event_data")
eventType Int @default(1) @map("event_type") @db.Integer
eventName String? @map("event_name") @db.VarChar(50)
eventData Json? @map("event_data")
@@index([createdAt])
@@index([sessionId])

8
interface/api/auth.d.ts vendored Normal file
View File

@ -0,0 +1,8 @@
export interface Auth {
user: {
id: string;
username: string;
isAdmin: boolean;
};
shareToken: string;
}

73
interface/api/models.d.ts vendored Normal file
View File

@ -0,0 +1,73 @@
export interface User {
id: string;
username: string;
isAdmin: boolean;
createdAt: string;
}
export interface Website {
id: string;
userId: string;
revId: number;
name: string;
domain: string;
shareId: string;
createdAt: Date;
}
export interface Share {
id: string;
token: string;
}
export interface Empty {}
export interface WebsiteActive {
x: number;
}
export interface WebsiteEventDataMetric {
[key: string]: number;
}
export interface WebsiteMetric {
x: string;
y: number;
}
export interface WebsiteEventMetric {
x: string;
t: string;
y: number;
}
export interface WebsitePageviews {
pageviews: {
t: string;
y: number;
};
sessions: {
t: string;
y: number;
};
}
export interface WebsiteStats {
pageviews: { value: number; change: number };
uniques: { value: number; change: number };
bounces: { value: number; change: number };
totalTime: { value: number; change: number };
}
export interface RealtimeInit {
websites: Website[];
token: string;
data: RealtimeUpdate;
}
export interface RealtimeUpdate {
pageviews: any[];
sessions: any[];
events: any[];
timestamp: number;
}

14
interface/api/nextApi.d.ts vendored Normal file
View File

@ -0,0 +1,14 @@
import { NextApiRequest } from 'next';
import { Auth } from './auth';
export interface NextApiRequestQueryBody<TQuery = any, TBody = any> extends NextApiRequest {
auth?: Auth;
query: TQuery & { [key: string]: string | string[] };
body: TBody;
headers: any;
}
export interface NextApiRequestAuth extends NextApiRequest {
auth?: Auth;
headers: any;
}

5
interface/auth.d.ts vendored
View File

@ -1,5 +0,0 @@
export interface Auth {
id: number;
email?: string;
teams?: string[];
}

22
interface/base.d.ts vendored
View File

@ -1,22 +0,0 @@
import { NextApiRequest } from 'next';
import { Auth } from './auth';
export interface NextApiRequestQueryBody<TQuery, TBody> extends NextApiRequest {
auth: Auth;
query: TQuery;
body: TBody;
}
export interface NextApiRequestQuery<TQuery> extends NextApiRequest {
auth: Auth;
query: TQuery;
}
export interface NextApiRequestBody<TBody> extends NextApiRequest {
auth: Auth;
body: TBody;
}
export interface ObjectAny {
[key: string]: any;
}

7
interface/enum.d.ts vendored Normal file
View File

@ -0,0 +1,7 @@
/* eslint-disable no-unused-vars */
export namespace UmamiApi {
enum EventType {
Pageview = 1,
Event = 2,
}
}

22
interface/index.d.ts vendored
View File

@ -1,22 +0,0 @@
import { NextApiRequest } from 'next';
import { Auth } from './auth';
export interface NextApiRequestQueryBody<TQuery, TBody> extends NextApiRequest {
auth: Auth;
query: TQuery;
body: TBody;
}
export interface NextApiRequestQuery<TQuery> extends NextApiRequest {
auth: Auth;
query: TQuery;
}
export interface NextApiRequestBody<TBody> extends NextApiRequest {
auth: Auth;
body: TBody;
}
export interface ObjectAny {
[key: string]: any;
}

View File

@ -106,7 +106,7 @@ function getEventDataFilterQuery(column, filters) {
return query.join('\nand ');
}
function getFilterQuery(column, filters = {}, params = []) {
function getFilterQuery(filters = {}, params = []) {
const query = Object.keys(filters).reduce((arr, key) => {
const filter = filters[key];
@ -146,7 +146,7 @@ function getFilterQuery(column, filters = {}, params = []) {
return query.join('\n');
}
function parseFilters(column, filters = {}, params = []) {
function parseFilters(filters = {}, params = []) {
const { domain, url, event_url, referrer, os, browser, device, country, event_name, query } =
filters;
@ -159,9 +159,7 @@ function parseFilters(column, filters = {}, params = []) {
sessionFilters,
eventFilters,
event: { event_name },
pageviewQuery: getFilterQuery(column, pageviewFilters, params),
sessionQuery: getFilterQuery(column, sessionFilters, params),
eventQuery: getFilterQuery(column, eventFilters, params),
filterQuery: getFilterQuery(filters, params),
};
}

View File

@ -4,6 +4,7 @@ import moment from 'moment-timezone';
import debug from 'debug';
import { PRISMA, MYSQL, POSTGRESQL, getDatabaseType } from 'lib/db';
import { FILTER_IGNORED } from 'lib/constants';
import { PrismaClientOptions } from '@prisma/client/runtime';
const MYSQL_DATE_FORMATS = {
minute: '%Y-%m-%d %H:%i:00',
@ -37,7 +38,8 @@ function logQuery(e) {
}
function getClient(options) {
const prisma = new PrismaClient(options);
const prisma: PrismaClient<PrismaClientOptions, 'query' | 'error' | 'info' | 'warn'> =
new PrismaClient(options);
if (process.env.LOG_QUERY) {
prisma.$on('query', logQuery);
@ -52,7 +54,7 @@ function getClient(options) {
return prisma;
}
function getDateQuery(field, unit, timezone) {
function getDateQuery(field, unit, timezone?): string {
const db = getDatabaseType(process.env.DATABASE_URL);
if (db === POSTGRESQL) {
@ -73,7 +75,7 @@ function getDateQuery(field, unit, timezone) {
}
}
function getTimestampInterval(field) {
function getTimestampInterval(field): string {
const db = getDatabaseType(process.env.DATABASE_URL);
if (db === POSTGRESQL) {
@ -85,7 +87,7 @@ function getTimestampInterval(field) {
}
}
function getJsonField(column, property, isNumber) {
function getJsonField(column, property, isNumber): string {
const db = getDatabaseType(process.env.DATABASE_URL);
if (db === POSTGRESQL) {
@ -103,7 +105,7 @@ function getJsonField(column, property, isNumber) {
}
}
function getEventDataColumnsQuery(column, columns) {
function getEventDataColumnsQuery(column, columns): string {
const query = Object.keys(columns).reduce((arr, key) => {
const filter = columns[key];
@ -121,7 +123,7 @@ function getEventDataColumnsQuery(column, columns) {
return query.join(',\n');
}
function getEventDataFilterQuery(column, filters) {
function getEventDataFilterQuery(column, filters): string {
const query = Object.keys(filters).reduce((arr, key) => {
const filter = filters[key];
@ -143,7 +145,7 @@ function getEventDataFilterQuery(column, filters) {
return query.join('\nand ');
}
function getFilterQuery(table, column, filters = {}, params = []) {
function getFilterQuery(filters = {}, params = []): string {
const query = Object.keys(filters).reduce((arr, key) => {
const filter = filters[key];
@ -153,48 +155,25 @@ function getFilterQuery(table, column, filters = {}, params = []) {
switch (key) {
case 'url':
if (table === 'pageview' || table === 'event') {
arr.push(`and ${table}.${key}=$${params.length + 1}`);
params.push(decodeURIComponent(filter));
}
break;
case 'os':
case 'browser':
case 'device':
case 'country':
if (table === 'session') {
arr.push(`and ${table}.${key}=$${params.length + 1}`);
params.push(decodeURIComponent(filter));
}
break;
case 'event_name':
if (table === 'event') {
arr.push(`and ${table}.${key}=$${params.length + 1}`);
params.push(decodeURIComponent(filter));
}
arr.push(`and ${key}=$${params.length + 1}`);
params.push(decodeURIComponent(filter));
break;
case 'referrer':
if (table === 'pageview' || table === 'event') {
arr.push(`and ${table}.referrer like $${params.length + 1}`);
params.push(`%${decodeURIComponent(filter)}%`);
}
arr.push(`and referrer like $${params.length + 1}`);
params.push(`%${decodeURIComponent(filter)}%`);
break;
case 'domain':
if (table === 'pageview') {
arr.push(`and ${table}.referrer not like $${params.length + 1}`);
arr.push(`and ${table}.referrer not like '/%'`);
params.push(`%://${filter}/%`);
}
arr.push(`and referrer not like $${params.length + 1}`);
arr.push(`and referrer not like '/%'`);
params.push(`%://${filter}/%`);
break;
case 'query':
if (table === 'pageview') {
arr.push(`and ${table}.url like '%?%'`);
}
arr.push(`and url like '%?%'`);
}
return arr;
@ -203,7 +182,11 @@ function getFilterQuery(table, column, filters = {}, params = []) {
return query.join('\n');
}
function parseFilters(table, column, filters = {}, params = [], sessionKey = 'session_id') {
function parseFilters(
filters: { [key: string]: any } = {},
params = [],
sessionKey = 'session_id',
) {
const { domain, url, event_url, referrer, os, browser, device, country, event_name, query } =
filters;
@ -218,15 +201,13 @@ function parseFilters(table, column, filters = {}, params = [], sessionKey = 'se
event: { event_name },
joinSession:
os || browser || device || country
? `inner join session on ${table}.${sessionKey} = session.${sessionKey}`
? `inner join session on ${sessionKey} = session.${sessionKey}`
: '',
pageviewQuery: getFilterQuery('pageview', column, pageviewFilters, params),
sessionQuery: getFilterQuery('session', column, sessionFilters, params),
eventQuery: getFilterQuery('event', column, eventFilters, params),
filterQuery: getFilterQuery(filters, params),
};
}
async function rawQuery(query, params = []) {
async function rawQuery(query, params = []): Promise<any> {
const db = getDatabaseType(process.env.DATABASE_URL);
if (db !== POSTGRESQL && db !== MYSQL) {
@ -238,12 +219,13 @@ async function rawQuery(query, params = []) {
return prisma.$queryRawUnsafe.apply(prisma, [sql, ...params]);
}
async function transaction(queries) {
async function transaction(queries): Promise<any> {
return prisma.$transaction(queries);
}
// Initialization
const prisma = global[PRISMA] || getClient(PRISMA_OPTIONS);
const prisma: PrismaClient<PrismaClientOptions, 'query' | 'error' | 'info' | 'warn'> =
global[PRISMA] || getClient(PRISMA_OPTIONS);
export default {
client: prisma,

View File

@ -10,8 +10,24 @@ import {
import { getUser } from 'queries';
import { secret } from 'lib/crypto';
import redis from 'lib/redis';
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
import { NextApiResponse } from 'next';
import { User } from 'interface/api/models';
export default async (req, res) => {
export interface LoginRequestBody {
username: string;
password: string;
}
export interface LoginResponse {
token: string;
user: User;
}
export default async (
req: NextApiRequestQueryBody<any, LoginRequestBody>,
res: NextApiResponse<LoginResponse>,
) => {
if (req.method === 'POST') {
const { username, password } = req.body;
@ -19,7 +35,7 @@ export default async (req, res) => {
return badRequest(res);
}
const user = await getUser({ username });
const user = await getUser({ username }, true);
if (user && checkPassword(password, user.password)) {
if (redis.enabled) {

View File

@ -2,8 +2,9 @@ import { methodNotAllowed, ok } from 'next-basics';
import { useAuth } from 'lib/middleware';
import redis from 'lib/redis';
import { getAuthToken } from 'lib/auth';
import { NextApiRequest, NextApiResponse } from 'next';
export default async (req, res) => {
export default async (req: NextApiRequest, res: NextApiResponse) => {
await useAuth(req, res);
if (req.method === 'POST') {

View File

@ -1,8 +0,0 @@
import { useAuth } from 'lib/middleware';
import { ok } from 'next-basics';
export default async (req, res) => {
await useAuth(req, res);
return ok(res, req.auth);
};

10
pages/api/auth/verify.ts Normal file
View File

@ -0,0 +1,10 @@
import { NextApiRequestAuth } from 'interface/api/nextApi';
import { useAuth } from 'lib/middleware';
import { NextApiResponse } from 'next';
import { ok } from 'next-basics';
export default async (req: NextApiRequestAuth, res: NextApiResponse) => {
await useAuth(req, res);
return ok(res, req.auth);
};

View File

@ -6,8 +6,23 @@ import { savePageView, saveEvent } from 'queries';
import { useCors, useSession } from 'lib/middleware';
import { getJsonBody, getIpAddress } from 'lib/request';
import { secret } from 'lib/crypto';
import { NextApiRequest, NextApiResponse } from 'next';
export default async (req, res) => {
export interface NextApiRequestCollect extends NextApiRequest {
session: {
id: string;
websiteId: string;
hostname: string;
browser: string;
os: string;
device: string;
screen: string;
language: string;
country: string;
};
}
export default async (req: NextApiRequestCollect, res: NextApiResponse) => {
await useCors(req, res);
if (isbot(req.headers['user-agent']) && !process.env.DISABLE_BOT_CHECK) {
@ -74,6 +89,7 @@ export default async (req, res) => {
await saveEvent({
...session,
url,
referrer,
eventName,
eventData,
});

View File

@ -1,6 +1,15 @@
import { NextApiRequest, NextApiResponse } from 'next';
import { ok, methodNotAllowed } from 'next-basics';
export default async (req, res) => {
export interface ConfigResponse {
basePath: string;
trackerScriptName: string;
updatesDisabled: boolean;
telemetryDisabled: boolean;
adminDisabled: boolean;
}
export default async (req: NextApiRequest, res: NextApiResponse<ConfigResponse>) => {
if (req.method === 'GET') {
return ok(res, {
basePath: process.env.BASE_PATH || '',

View File

@ -1,5 +0,0 @@
import { ok } from 'next-basics';
export default async (req, res) => {
return ok(res);
};

6
pages/api/heartbeat.ts Normal file
View File

@ -0,0 +1,6 @@
import { NextApiRequest, NextApiResponse } from 'next';
import { ok } from 'next-basics';
export default async (req: NextApiRequest, res: NextApiResponse) => {
return ok(res);
};

View File

@ -1,10 +1,13 @@
import { subMinutes } from 'date-fns';
import { ok, methodNotAllowed, createToken } from 'next-basics';
import { useAuth } from 'lib/middleware';
import { getUserWebsites, getRealtimeData } from 'queries';
import { RealtimeInit } from 'interface/api/models';
import { NextApiRequestAuth } from 'interface/api/nextApi';
import { secret } from 'lib/crypto';
import { useAuth } from 'lib/middleware';
import { NextApiResponse } from 'next';
import { createToken, methodNotAllowed, ok } from 'next-basics';
import { getRealtimeData, getUserWebsites } from 'queries';
export default async (req, res) => {
export default async (req: NextApiRequestAuth, res: NextApiResponse<RealtimeInit>) => {
await useAuth(req, res);
if (req.method === 'GET') {

View File

@ -3,8 +3,18 @@ import { useAuth } from 'lib/middleware';
import { getRealtimeData } from 'queries';
import { SHARE_TOKEN_HEADER } from 'lib/constants';
import { secret } from 'lib/crypto';
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
import { NextApiResponse } from 'next';
import { RealtimeUpdate } from 'interface/api/models';
export default async (req, res) => {
export interface InitUpdateRequestQuery {
start_at: string;
}
export default async (
req: NextApiRequestQueryBody<InitUpdateRequestQuery>,
res: NextApiResponse<RealtimeUpdate>,
) => {
await useAuth(req, res);
if (req.method === 'GET') {

View File

@ -1,8 +1,22 @@
import { getWebsite } from 'queries';
import { ok, notFound, methodNotAllowed, createToken } from 'next-basics';
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
import { secret } from 'lib/crypto';
import { NextApiResponse } from 'next';
import { createToken, methodNotAllowed, notFound, ok } from 'next-basics';
import { getWebsite } from 'queries';
export default async (req, res) => {
export interface ShareRequestQuery {
id: string;
}
export interface ShareResponse {
id: string;
token: string;
}
export default async (
req: NextApiRequestQueryBody<ShareRequestQuery>,
res: NextApiResponse<ShareResponse>,
) => {
const { id: shareId } = req.query;
if (req.method === 'GET') {

View File

@ -1,8 +1,23 @@
import { badRequest, hashPassword, methodNotAllowed, ok, unauthorized } from 'next-basics';
import { getUser, deleteUser, updateUser } from 'queries';
import { useAuth } from 'lib/middleware';
import { NextApiResponse } from 'next';
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
import { User } from 'interface/api/models';
export default async (req, res) => {
export interface UserReqeustQuery {
id: string;
}
export interface UserReqeustBody {
username: string;
password: string;
}
export default async (
req: NextApiRequestQueryBody<UserReqeustQuery, UserReqeustBody>,
res: NextApiResponse<User>,
) => {
await useAuth(req, res);
const {
@ -29,7 +44,7 @@ export default async (req, res) => {
const user = await getUser({ id });
const data = {};
const data: any = {};
if (password) {
data.password = hashPassword(password);

View File

@ -10,8 +10,23 @@ import {
} from 'next-basics';
import { allowQuery } from 'lib/auth';
import { TYPE_USER } from 'lib/constants';
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
import { NextApiResponse } from 'next';
import { User } from 'interface/api/models';
export default async (req, res) => {
export interface UserPasswordRequestQuery {
id: string;
}
export interface UserPasswordRequestBody {
current_password: string;
new_password: string;
}
export default async (
req: NextApiRequestQueryBody<UserPasswordRequestQuery, UserPasswordRequestBody>,
res: NextApiResponse<User>,
) => {
await useAuth(req, res);
const { current_password, new_password } = req.body;

View File

@ -2,8 +2,20 @@ import { ok, unauthorized, methodNotAllowed, badRequest, hashPassword } from 'ne
import { useAuth } from 'lib/middleware';
import { uuid } from 'lib/crypto';
import { createUser, getUser, getUsers } from 'queries';
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
import { NextApiResponse } from 'next';
import { User } from 'interface/api/models';
export default async (req, res) => {
export interface UsersRequestBody {
username: string;
password: string;
id: string;
}
export default async (
req: NextApiRequestQueryBody<UsersRequestBody>,
res: NextApiResponse<User[] | User>,
) => {
await useAuth(req, res);
const {

View File

@ -3,8 +3,18 @@ import { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware';
import { getActiveVisitors } from 'queries';
import { TYPE_WEBSITE } from 'lib/constants';
import { WebsiteActive } from 'interface/api/models';
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
import { NextApiResponse } from 'next';
export default async (req, res) => {
export interface WebsiteActiveRequestQuery {
id: string;
}
export default async (
req: NextApiRequestQueryBody<WebsiteActiveRequestQuery>,
res: NextApiResponse<WebsiteActive>,
) => {
await useCors(req, res);
await useAuth(req, res);

View File

@ -4,8 +4,27 @@ import { ok, badRequest, methodNotAllowed, unauthorized } from 'next-basics';
import { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware';
import { TYPE_WEBSITE } from 'lib/constants';
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
import { NextApiResponse } from 'next';
import { WebsiteMetric } from 'interface/api/models';
export default async (req, res) => {
export interface WebsiteEventDataRequestQuery {
id: string;
}
export interface WebsiteEventDataRequestBody {
start_at: string;
end_at: string;
timezone: string;
event_name: string;
columns: { [key: string]: 'count' | 'max' | 'min' | 'avg' | 'sum' };
filters?: { [key: string]: any };
}
export default async (
req: NextApiRequestQueryBody<WebsiteEventDataRequestQuery, WebsiteEventDataRequestBody>,
res: NextApiResponse<WebsiteMetric>,
) => {
await useCors(req, res);
await useAuth(req, res);

View File

@ -1,13 +1,29 @@
import moment from 'moment-timezone';
import { getEventMetrics } from 'queries';
import { ok, badRequest, methodNotAllowed, unauthorized } from 'next-basics';
import { WebsiteMetric } from 'interface/api/models';
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
import { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware';
import { TYPE_WEBSITE } from 'lib/constants';
import { useAuth, useCors } from 'lib/middleware';
import moment from 'moment-timezone';
import { NextApiResponse } from 'next';
import { badRequest, methodNotAllowed, ok, unauthorized } from 'next-basics';
import { getEventMetrics } from 'queries';
const unitTypes = ['year', 'month', 'hour', 'day'];
export default async (req, res) => {
export interface WebsiteEventsRequestQuery {
id: string;
start_at: string;
end_at: string;
unit: string;
tz: string;
url: string;
event_name: string;
}
export default async (
req: NextApiRequestQueryBody<WebsiteEventsRequestQuery>,
res: NextApiResponse<WebsiteMetric>,
) => {
await useCors(req, res);
await useAuth(req, res);
@ -24,9 +40,15 @@ export default async (req, res) => {
const startDate = new Date(+start_at);
const endDate = new Date(+end_at);
const events = await getEventMetrics(websiteId, startDate, endDate, tz, unit, {
url,
eventName: event_name,
const events = await getEventMetrics(websiteId, {
startDate,
endDate,
timezone: tz,
unit,
filters: {
url,
eventName: event_name,
},
});
return ok(res, events);

View File

@ -3,8 +3,24 @@ import { useAuth, useCors } from 'lib/middleware';
import { methodNotAllowed, ok, serverError, unauthorized } from 'next-basics';
import { deleteWebsite, getWebsite, updateWebsite } from 'queries';
import { TYPE_WEBSITE } from 'lib/constants';
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
import { NextApiResponse } from 'next';
import { Website } from 'interface/api/models';
export default async (req, res) => {
export interface WebsiteReqeustQuery {
id: string;
}
export interface WebsiteReqeustBody {
name: string;
domain: string;
shareId: string;
}
export default async (
req: NextApiRequestQueryBody<WebsiteReqeustQuery, WebsiteReqeustBody>,
res: NextApiResponse<Website | any>,
) => {
await useCors(req, res);
await useAuth(req, res);

View File

@ -1,6 +1,9 @@
import { WebsiteMetric } from 'interface/api/models';
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
import { allowQuery } from 'lib/auth';
import { FILTER_IGNORED, TYPE_WEBSITE } from 'lib/constants';
import { useAuth, useCors } from 'lib/middleware';
import { NextApiResponse } from 'next';
import { badRequest, methodNotAllowed, ok, unauthorized } from 'next-basics';
import { getPageviewMetrics, getSessionMetrics, getWebsite } from 'queries';
@ -33,7 +36,23 @@ function getColumn(type) {
return type;
}
export default async (req, res) => {
export interface WebsiteMetricsReqeustQuery {
id: string;
type: string;
start_at: number;
end_at: number;
url: string;
referrer: string;
os: string;
browser: string;
device: string;
country: string;
}
export default async (
req: NextApiRequestQueryBody<WebsiteMetricsReqeustQuery>,
res: NextApiResponse<WebsiteMetric[]>,
) => {
await useCors(req, res);
await useAuth(req, res);

View File

@ -1,13 +1,34 @@
import moment from 'moment-timezone';
import { getPageviewStats } from 'queries';
import { ok, badRequest, methodNotAllowed, unauthorized } from 'next-basics';
import { WebsitePageviews } from 'interface/api/models';
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
import { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware';
import { TYPE_WEBSITE } from 'lib/constants';
import { useAuth, useCors } from 'lib/middleware';
import moment from 'moment-timezone';
import { NextApiResponse } from 'next';
import { badRequest, methodNotAllowed, ok, unauthorized } from 'next-basics';
import { getPageviewStats } from 'queries';
const unitTypes = ['year', 'month', 'hour', 'day'];
export default async (req, res) => {
export interface WebsitePageviewReqeustQuery {
id: string;
websiteId: string;
start_at: number;
end_at: number;
unit: string;
tz: string;
url?: string;
referrer?: string;
os?: string;
browser?: string;
device?: string;
country?: string;
}
export default async (
req: NextApiRequestQueryBody<WebsitePageviewReqeustQuery>,
res: NextApiResponse<WebsitePageviews>,
) => {
await useCors(req, res);
await useAuth(req, res);
@ -39,8 +60,8 @@ export default async (req, res) => {
const [pageviews, sessions] = await Promise.all([
getPageviewStats(websiteId, {
start_at: startDate,
end_at: endDate,
startDate,
endDate,
timezone: tz,
unit,
count: '*',
@ -54,8 +75,8 @@ export default async (req, res) => {
},
}),
getPageviewStats(websiteId, {
start_at: startDate,
end_at: endDate,
startDate,
endDate,
timezone: tz,
unit,
count: 'distinct pageview.',

View File

@ -3,8 +3,17 @@ import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware';
import { TYPE_WEBSITE } from 'lib/constants';
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
import { NextApiResponse } from 'next';
export default async (req, res) => {
export interface WebsiteResetReqeustQuery {
id: string;
}
export default async (
req: NextApiRequestQueryBody<WebsiteResetReqeustQuery>,
res: NextApiResponse,
) => {
await useCors(req, res);
await useAuth(req, res);

View File

@ -3,8 +3,27 @@ import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware';
import { TYPE_WEBSITE } from 'lib/constants';
import { WebsiteStats } from 'interface/api/models';
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
import { NextApiResponse } from 'next';
export default async (req, res) => {
export interface WebsiteStatsReqeustQuery {
id: string;
type: string;
start_at: number;
end_at: number;
url: string;
referrer: string;
os: string;
browser: string;
device: string;
country: string;
}
export default async (
req: NextApiRequestQueryBody<WebsiteStatsReqeustQuery>,
res: NextApiResponse<WebsiteStats>,
) => {
await useCors(req, res);
await useAuth(req, res);

View File

@ -2,8 +2,23 @@ import { createWebsite, getAllWebsites, getUserWebsites } from 'queries';
import { ok, methodNotAllowed, getRandomChars } from 'next-basics';
import { useAuth, useCors } from 'lib/middleware';
import { uuid } from 'lib/crypto';
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
import { NextApiResponse } from 'next';
export default async (req, res) => {
export interface WebsitesReqeustQuery {
include_all?: boolean;
}
export interface WebsitesReqeustBody {
name: string;
domain: string;
enableShareUrl: boolean;
}
export default async (
req: NextApiRequestQueryBody<WebsitesReqeustQuery, WebsitesReqeustBody>,
res: NextApiResponse,
) => {
await useCors(req, res);
await useAuth(req, res);

View File

@ -1,7 +0,0 @@
import prisma from 'lib/prisma';
export async function createUser(data) {
return prisma.client.user.create({
data,
});
}

View File

@ -0,0 +1,20 @@
import prisma from 'lib/prisma';
export async function createUser(data: {
id: string;
username: string;
password: string;
}): Promise<{
id: string;
username: string;
isAdmin: boolean;
}> {
return prisma.client.user.create({
data,
select: {
id: true,
username: true,
isAdmin: true,
},
});
}

View File

@ -1,7 +1,10 @@
import prisma from 'lib/prisma';
import cache from 'lib/cache';
import { Prisma, User } from '@prisma/client';
export async function deleteUser(userId) {
export async function deleteUser(
userId: string,
): Promise<[Prisma.BatchPayload, Prisma.BatchPayload, Prisma.BatchPayload, User]> {
const { client } = prisma;
const websites = await client.website.findMany({

View File

@ -1,7 +0,0 @@
import prisma from 'lib/prisma';
export async function getUser(where) {
return prisma.client.user.findUnique({
where,
});
}

View File

@ -0,0 +1,25 @@
import prisma from 'lib/prisma';
import { Prisma } from '@prisma/client';
export interface User {
id: string;
username: string;
isAdmin: boolean;
password?: string;
createdAt?: Date;
}
export async function getUser(
where: Prisma.UserWhereUniqueInput,
includePassword = false,
): Promise<User> {
return prisma.client.user.findUnique({
where,
select: {
id: true,
username: true,
isAdmin: true,
password: includePassword,
},
});
}

View File

@ -1,6 +1,7 @@
import prisma from 'lib/prisma';
import { User } from './getUser';
export async function getUsers() {
export async function getUsers(): Promise<User[]> {
return prisma.client.user.findMany({
orderBy: [
{ isAdmin: 'desc' },

View File

@ -1,8 +0,0 @@
import prisma from 'lib/prisma';
export async function updateUser(data, where) {
return prisma.client.user.update({
where,
data,
});
}

View File

@ -0,0 +1,19 @@
import { Prisma } from '@prisma/client';
import prisma from 'lib/prisma';
import { User } from './getUser';
export async function updateUser(
data: Prisma.UserUpdateArgs,
where: Prisma.UserWhereUniqueInput,
): Promise<User> {
return prisma.client.user.update({
where,
data,
select: {
id: true,
username: true,
isAdmin: true,
createdAt: true,
},
});
}

View File

@ -1,7 +1,16 @@
import prisma from 'lib/prisma';
import { Website } from '@prisma/client';
import cache from 'lib/cache';
import prisma from 'lib/prisma';
export async function createWebsite(userId, data) {
export async function createWebsite(
userId: string,
data: {
id: string;
name: string;
domain: string;
shareId?: string;
},
): Promise<Website> {
return prisma.client.website
.create({
data: {

View File

@ -1,22 +1,25 @@
import prisma from 'lib/prisma';
import cache from 'lib/cache';
import { Prisma, Website } from '@prisma/client';
export async function deleteWebsite(id) {
export async function deleteWebsite(
websiteId: string,
): Promise<[Prisma.BatchPayload, Prisma.BatchPayload, Website]> {
const { client, transaction } = prisma;
return transaction([
client.websiteEvent.deleteMany({
where: { websiteId: id },
where: { websiteId },
}),
client.session.deleteMany({
where: { websiteId: id },
where: { websiteId },
}),
client.website.delete({
where: { id },
where: { id: websiteId },
}),
]).then(async data => {
if (cache.enabled) {
await cache.deleteWebsite(id);
await cache.deleteWebsite(websiteId);
}
return data;

View File

@ -1,23 +0,0 @@
import prisma from 'lib/prisma';
export async function getAllWebsites() {
let data = await prisma.client.website.findMany({
orderBy: [
{
userId: 'asc',
},
{
name: 'asc',
},
],
include: {
user: {
select: {
username: true,
},
},
},
});
return data.map(i => ({ ...i, user: i.user.username }));
}

View File

@ -0,0 +1,24 @@
import { Website } from '@prisma/client';
import prisma from 'lib/prisma';
export async function getAllWebsites(): Promise<(Website & { user: string })[]> {
return await prisma.client.website
.findMany({
orderBy: [
{
userId: 'asc',
},
{
name: 'asc',
},
],
include: {
user: {
select: {
username: true,
},
},
},
})
.then(data => data.map(i => ({ ...i, user: i.user.username })));
}

View File

@ -1,6 +1,7 @@
import prisma from 'lib/prisma';
import { Website } from '@prisma/client';
export async function getUserWebsites(userId) {
export async function getUserWebsites(userId): Promise<Website[]> {
return prisma.client.website.findMany({
where: {
userId,

View File

@ -1,7 +0,0 @@
import prisma from 'lib/prisma';
export async function getWebsite(where) {
return prisma.client.website.findUnique({
where,
});
}

View File

@ -0,0 +1,8 @@
import prisma from 'lib/prisma';
import { Prisma, Website } from '@prisma/client';
export async function getWebsite(where: Prisma.WebsiteWhereUniqueInput): Promise<Website> {
return prisma.client.website.findUnique({
where,
});
}

View File

@ -1,20 +1,23 @@
import { Prisma, Website } from '@prisma/client';
import cache from 'lib/cache';
import prisma from 'lib/prisma';
import { getWebsite } from 'queries';
import cache from 'lib/cache';
export async function resetWebsite(id) {
export async function resetWebsite(
websiteId,
): Promise<[Prisma.BatchPayload, Prisma.BatchPayload, Website]> {
const { client, transaction } = prisma;
const { revId } = await getWebsite({ id });
const { revId } = await getWebsite({ id: websiteId });
return transaction([
client.websiteEvent.deleteMany({
where: { websiteId: id },
where: { websiteId },
}),
client.session.deleteMany({
where: { websiteId: id },
where: { websiteId },
}),
client.website.update({ where: { id }, data: { revId: revId + 1 } }),
client.website.update({ where: { id: websiteId }, data: { revId: revId + 1 } }),
]).then(async data => {
if (cache.enabled) {
await cache.storeWebsite(data[2]);

View File

@ -1,10 +0,0 @@
import prisma from 'lib/prisma';
export async function updateWebsite(id, data) {
return prisma.client.website.update({
where: {
id,
},
data,
});
}

View File

@ -0,0 +1,11 @@
import { Prisma, Website } from '@prisma/client';
import prisma from 'lib/prisma';
export async function updateWebsite(websiteId, data: Prisma.WebsiteUpdateInput): Promise<Website> {
return prisma.client.website.update({
where: {
id: websiteId,
},
data,
});
}

View File

@ -2,8 +2,21 @@ import clickhouse from 'lib/clickhouse';
import { CLICKHOUSE, PRISMA, runQuery } from 'lib/db';
import prisma from 'lib/prisma';
import cache from 'lib/cache';
import { WebsiteMetric } from 'interface/api/models';
import { UmamiApi } from 'interface/enum';
export async function getEventData(...args) {
export async function getEventData(
...args: [
websiteId: string,
data: {
startDate: Date;
endDate: Date;
event_name: string;
columns: any;
filters: object;
},
]
): Promise<WebsiteMetric[]> {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
@ -14,31 +27,48 @@ export async function getEventData(...args) {
});
}
async function relationalQuery(websiteId, { startDate, endDate, event_name, columns, filters }) {
async function relationalQuery(
websiteId: string,
data: {
startDate: Date;
endDate: Date;
event_name: string;
columns: any;
filters: object;
},
) {
const { startDate, endDate, event_name, columns, filters } = data;
const { rawQuery, getEventDataColumnsQuery, getEventDataFilterQuery } = prisma;
const params = [startDate, endDate];
return rawQuery(
`select
${getEventDataColumnsQuery('event_data.event_data', columns)}
from event
join website
on event.website_id = website.website_id
join event_data
on event.event_id = event_data.event_id
where website.website_id ='${websiteId}'
and event.created_at between $1 and $2
${getEventDataColumnsQuery('event_data', columns)}
from website_event
where website_id ='${websiteId}'
and created_at between $1 and $2
and event_type = ${UmamiApi.EventType.Event}
${event_name ? `and event_name = ${event_name}` : ''}
${
Object.keys(filters).length > 0
? `and ${getEventDataFilterQuery('event_data.event_data', filters)}`
? `and ${getEventDataFilterQuery('event_data', filters)}`
: ''
}`,
params,
);
}
async function clickhouseQuery(websiteId, { startDate, endDate, event_name, columns, filters }) {
async function clickhouseQuery(
websiteId: string,
data: {
startDate: Date;
endDate: Date;
event_name: string;
columns: any;
filters: object;
},
) {
const { startDate, endDate, event_name, columns, filters } = data;
const { rawQuery, getBetweenDates, getEventDataColumnsQuery, getEventDataFilterQuery } =
clickhouse;
const website = await cache.fetchWebsite(websiteId);
@ -50,6 +80,7 @@ async function clickhouseQuery(websiteId, { startDate, endDate, event_name, colu
from event
where website_id = $1
and rev_id = $2
and event_type = ${UmamiApi.EventType.Event}
${event_name ? `and event_name = ${event_name}` : ''}
and ${getBetweenDates('created_at', startDate, endDate)}
${

View File

@ -1,68 +0,0 @@
import prisma from 'lib/prisma';
import clickhouse from 'lib/clickhouse';
import { runQuery, CLICKHOUSE, PRISMA } from 'lib/db';
import cache from 'lib/cache';
export async function getEventMetrics(...args) {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
});
}
async function relationalQuery(
websiteId,
start_at,
end_at,
timezone = 'utc',
unit = 'day',
filters = {},
) {
const { rawQuery, getDateQuery, getFilterQuery } = prisma;
const params = [start_at, end_at];
return rawQuery(
`select
event_name x,
${getDateQuery('event.created_at', unit, timezone)} t,
count(*) y
from event
join website
on event.website_id = website.website_id
where website.website_id='${websiteId}'
and event.created_at between $1 and $2
${getFilterQuery('event', filters, params)}
group by 1, 2
order by 2`,
params,
);
}
async function clickhouseQuery(
websiteId,
start_at,
end_at,
timezone = 'UTC',
unit = 'day',
filters = {},
) {
const { rawQuery, getDateQuery, getBetweenDates, getFilterQuery } = clickhouse;
const website = await cache.fetchWebsite(websiteId);
const params = [websiteId, website?.revId || 0];
return rawQuery(
`select
event_name x,
${getDateQuery('created_at', unit, timezone)} t,
count(*) y
from event
where event_name != ''
and website_id = $1
and rev_id = $2
and ${getBetweenDates('created_at', start_at, end_at)}
${getFilterQuery('event', filters, params)}
group by x, t
order by t`,
params,
);
}

View File

@ -0,0 +1,105 @@
import prisma from 'lib/prisma';
import clickhouse from 'lib/clickhouse';
import { runQuery, CLICKHOUSE, PRISMA } from 'lib/db';
import cache from 'lib/cache';
import { WebsiteEventMetric } from 'interface/api/models';
import { UmamiApi } from 'interface/enum';
export async function getEventMetrics(
...args: [
websiteId: string,
data: {
startDate: Date;
endDate: Date;
timezone: string;
unit: string;
filters: {
url: string;
eventName: string;
};
},
]
): Promise<WebsiteEventMetric[]> {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
});
}
async function relationalQuery(
websiteId: string,
{
startDate,
endDate,
timezone = 'utc',
unit = 'day',
filters,
}: {
startDate: Date;
endDate: Date;
timezone: string;
unit: string;
filters: {
url: string;
eventName: string;
};
},
) {
const { rawQuery, getDateQuery, getFilterQuery } = prisma;
const params = [startDate, endDate];
return rawQuery(
`select
event_name x,
${getDateQuery('created_at', unit, timezone)} t,
count(*) y
from website_event
where website_id='${websiteId}'
and created_at between $1 and $2
and event_type = ${UmamiApi.EventType.Event}
${getFilterQuery(filters, params)}
group by 1, 2
order by 2`,
params,
);
}
async function clickhouseQuery(
websiteId: string,
{
startDate,
endDate,
timezone = 'utc',
unit = 'day',
filters,
}: {
startDate: Date;
endDate: Date;
timezone: string;
unit: string;
filters: {
url: string;
eventName: string;
};
},
) {
const { rawQuery, getDateQuery, getBetweenDates, getFilterQuery } = clickhouse;
const website = await cache.fetchWebsite(websiteId);
const params = [websiteId, website?.revId || 0];
return rawQuery(
`select
event_name x,
${getDateQuery('created_at', unit, timezone)} t,
count(*) y
from event
where website_id = $1
and rev_id = $2
and event_type = ${UmamiApi.EventType.Event}
and ${getBetweenDates('created_at', startDate, endDate)}
${getFilterQuery(filters, params)}
group by x, t
order by t`,
params,
);
}

View File

@ -1,45 +0,0 @@
import prisma from 'lib/prisma';
import clickhouse from 'lib/clickhouse';
import { runQuery, CLICKHOUSE, PRISMA } from 'lib/db';
export function getEvents(...args) {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
});
}
function relationalQuery(websites, start_at) {
return prisma.client.event.findMany({
where: {
websiteId: {
in: websites,
},
createdAt: {
gte: start_at,
},
},
});
}
function clickhouseQuery(websites, start_at) {
const { rawQuery, getDateFormat, getCommaSeparatedStringFormat } = clickhouse;
return rawQuery(
`select
event_id,
website_id,
session_id,
created_at,
url,
event_name
from event
where event_name != ''
and ${
websites && websites.length > 0
? `website_id in (${getCommaSeparatedStringFormat(websites)})`
: '0 = 0'
}
and created_at >= ${getDateFormat(start_at)}`,
);
}

View File

@ -1,62 +0,0 @@
import { EVENT_NAME_LENGTH, URL_LENGTH } from 'lib/constants';
import { CLICKHOUSE, PRISMA, runQuery } from 'lib/db';
import kafka from 'lib/kafka';
import prisma from 'lib/prisma';
import { uuid } from 'lib/crypto';
import cache from 'lib/cache';
export async function saveEvent(...args) {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
});
}
async function relationalQuery(data) {
const { websiteId, sessionId, url, eventName, eventData } = data;
const eventId = uuid();
const params = {
id: eventId,
websiteId,
sessionId,
url: url?.substring(0, URL_LENGTH),
eventName: eventName?.substring(0, EVENT_NAME_LENGTH),
};
if (eventData) {
params.eventData = {
create: {
id: eventId,
eventData: eventData,
},
};
}
return prisma.client.event.create({
data: params,
});
}
async function clickhouseQuery(data) {
const { websiteId, id: sessionId, url, eventName, eventData, country, ...args } = data;
const { getDateFormat, sendMessage } = kafka;
const website = await cache.fetchWebsite(websiteId);
const params = {
website_id: websiteId,
session_id: sessionId,
event_id: uuid(),
url: url?.substring(0, URL_LENGTH),
event_name: eventName?.substring(0, EVENT_NAME_LENGTH),
event_data: eventData ? JSON.stringify(eventData) : null,
rev_id: website?.revId || 0,
created_at: getDateFormat(new Date()),
country: country ? country : null,
...args,
};
await sendMessage(params, 'event');
return data;
}

View File

@ -0,0 +1,91 @@
import { EVENT_NAME_LENGTH, URL_LENGTH } from 'lib/constants';
import { CLICKHOUSE, PRISMA, runQuery } from 'lib/db';
import kafka from 'lib/kafka';
import prisma from 'lib/prisma';
import { uuid } from 'lib/crypto';
import cache from 'lib/cache';
import { UmamiApi } from 'interface/enum';
export async function saveEvent(args: {
id: string;
websiteId: string;
url: string;
referrer?: string;
eventName?: string;
eventData?: any;
hostname?: string;
browser?: string;
os?: string;
device?: string;
screen?: string;
language?: string;
country?: string;
}) {
return runQuery({
[PRISMA]: () => relationalQuery(args),
[CLICKHOUSE]: () => clickhouseQuery(args),
});
}
async function relationalQuery(data: {
id: string;
websiteId: string;
url: string;
referrer?: string;
eventName?: string;
eventData?: any;
}) {
const { websiteId, id: sessionId, url, eventName, eventData, referrer } = data;
const params = {
id: uuid(),
websiteId,
sessionId,
url: url?.substring(0, URL_LENGTH),
referrer: referrer?.substring(0, URL_LENGTH),
eventType: UmamiApi.EventType.Event,
eventName: eventName?.substring(0, EVENT_NAME_LENGTH),
eventData,
};
return prisma.client.websiteEvent.create({
data: params,
});
}
async function clickhouseQuery(data: {
id: string;
websiteId: string;
url: string;
referrer?: string;
eventName?: string;
eventData?: any;
hostname?: string;
browser?: string;
os?: string;
device?: string;
screen?: string;
language?: string;
country?: string;
}) {
const { websiteId, id: sessionId, url, eventName, eventData, country, ...args } = data;
const { getDateFormat, sendMessage } = kafka;
const website = await cache.fetchWebsite(websiteId);
const params = {
website_id: websiteId,
session_id: sessionId,
event_id: uuid(),
url: url?.substring(0, URL_LENGTH),
event_name: eventName?.substring(0, EVENT_NAME_LENGTH),
event_data: eventData ? JSON.stringify(eventData) : null,
rev_id: website?.revId || 0,
created_at: getDateFormat(new Date()),
country: country ? country : null,
...args,
};
await sendMessage(params, 'event');
return data;
}

View File

@ -1,59 +0,0 @@
import prisma from 'lib/prisma';
import clickhouse from 'lib/clickhouse';
import { runQuery, CLICKHOUSE, PRISMA } from 'lib/db';
import cache from 'lib/cache';
export async function getPageviewMetrics(...args) {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
});
}
async function relationalQuery(websiteId, { startDate, endDate, column, table, filters = {} }) {
const { rawQuery, parseFilters } = prisma;
const params = [startDate, endDate];
const { pageviewQuery, sessionQuery, eventQuery, joinSession } = parseFilters(
table,
column,
filters,
params,
);
return rawQuery(
`select ${column} x, count(*) y
from ${table}
${` join website on ${table}.website_id = website.website_id`}
${joinSession}
where website.website_id='${websiteId}'
and ${table}.created_at between $1 and $2
${pageviewQuery}
${joinSession && sessionQuery}
${eventQuery}
group by 1
order by 2 desc`,
params,
);
}
async function clickhouseQuery(websiteId, { startDate, endDate, column, filters = {} }) {
const { rawQuery, parseFilters, getBetweenDates } = clickhouse;
const website = await cache.fetchWebsite(websiteId);
const params = [websiteId, website?.revId || 0];
const { pageviewQuery, sessionQuery, eventQuery } = parseFilters(column, filters, params);
return rawQuery(
`select ${column} x, count(*) y
from event
where website_id = $1
and rev_id = $2
${column !== 'event_name' ? `and event_name = ''` : `and event_name != ''`}
and ${getBetweenDates('created_at', startDate, endDate)}
${pageviewQuery}
${sessionQuery}
${eventQuery}
group by x
order by y desc`,
params,
);
}

View File

@ -0,0 +1,82 @@
import prisma from 'lib/prisma';
import clickhouse from 'lib/clickhouse';
import { runQuery, CLICKHOUSE, PRISMA } from 'lib/db';
import cache from 'lib/cache';
import { Prisma } from '@prisma/client';
import { UmamiApi } from 'interface/enum';
export async function getPageviewMetrics(
...args: [
websiteId: string,
data: {
startDate: Date;
endDate: Date;
column: Prisma.WebsiteEventScalarFieldEnum | Prisma.SessionScalarFieldEnum;
table: string;
filters: object;
},
]
) {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
});
}
async function relationalQuery(
websiteId: string,
data: {
startDate: Date;
endDate: Date;
column: Prisma.WebsiteEventScalarFieldEnum | Prisma.SessionScalarFieldEnum;
filters: object;
},
) {
const { startDate, endDate, column, filters = {} } = data;
const { rawQuery, parseFilters } = prisma;
const params = [startDate, endDate];
const { filterQuery, joinSession } = parseFilters(filters, params);
return rawQuery(
`select ${column} x, count(*) y
from website_event
${joinSession}
where website_id='${websiteId}'
and website_event.created_at between $1 and $2
and event_type = ${UmamiApi.EventType.Pageview}
${filterQuery}
group by 1
order by 2 desc`,
params,
);
}
async function clickhouseQuery(
websiteId: string,
data: {
startDate: Date;
endDate: Date;
column: Prisma.WebsiteEventScalarFieldEnum | Prisma.SessionScalarFieldEnum;
filters: object;
},
) {
const { startDate, endDate, column, filters = {} } = data;
const { rawQuery, parseFilters, getBetweenDates } = clickhouse;
const website = await cache.fetchWebsite(websiteId);
const params = [websiteId, website?.revId || 0];
const { filterQuery } = parseFilters(filters, params);
return rawQuery(
`select ${column} x, count(*) y
from event
where website_id = $1
and rev_id = $2
and event_type = ${UmamiApi.EventType.Pageview}
${column !== 'event_name' ? `and event_name = ''` : `and event_name != ''`}
and ${getBetweenDates('created_at', startDate, endDate)}
${filterQuery}
group by x
order by y desc`,
params,
);
}

View File

@ -1,41 +0,0 @@
import prisma from 'lib/prisma';
import { runQuery, CLICKHOUSE, PRISMA } from 'lib/db';
export async function getPageviewParams(...args) {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
});
}
async function relationalQuery(websiteId, start_at, end_at, column, table, filters = {}) {
const { parseFilters, rawQuery } = prisma;
const params = [start_at, end_at];
const { pageviewQuery, sessionQuery, eventQuery, joinSession } = parseFilters(
table,
column,
filters,
params,
);
return rawQuery(
`select url x,
count(*) y
from ${table}
${` join website on ${table}.website_id = website.website_id`}
${joinSession}
where website.website_id='${websiteId}'
and ${table}.created_at between $1 and $2
and ${table}.url like '%?%'
${pageviewQuery}
${joinSession && sessionQuery}
${eventQuery}
group by 1
order by 2 desc`,
params,
);
}
function clickhouseQuery() {
return Promise.reject(new Error('Not implemented.'));
}

View File

@ -1,78 +0,0 @@
import prisma from 'lib/prisma';
import clickhouse from 'lib/clickhouse';
import { runQuery, CLICKHOUSE, PRISMA } from 'lib/db';
import cache from 'lib/cache';
export async function getPageviewStats(...args) {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
});
}
async function relationalQuery(
websiteId,
{
start_at,
end_at,
timezone = 'utc',
unit = 'day',
count = '*',
filters = {},
sessionKey = 'session_id',
},
) {
const { getDateQuery, parseFilters, rawQuery } = prisma;
const params = [start_at, end_at];
const { pageviewQuery, sessionQuery, joinSession } = parseFilters(
'pageview',
null,
filters,
params,
);
return rawQuery(
`select ${getDateQuery('pageview.created_at', unit, timezone)} t,
count(${count !== '*' ? `${count}${sessionKey}` : count}) y
from pageview
join website
on pageview.website_id = website.website_id
${joinSession}
where website.website_id='${websiteId}'
and pageview.created_at between $1 and $2
${pageviewQuery}
${sessionQuery}
group by 1`,
params,
);
}
async function clickhouseQuery(
websiteId,
{ start_at, end_at, timezone = 'UTC', unit = 'day', count = '*', filters = {} },
) {
const { parseFilters, rawQuery, getDateStringQuery, getDateQuery, getBetweenDates } = clickhouse;
const website = await cache.fetchWebsite(websiteId);
const params = [websiteId, website?.revId || 0];
const { pageviewQuery, sessionQuery } = parseFilters(null, filters, params);
return rawQuery(
`select
${getDateStringQuery('g.t', unit)} as t,
g.y as y
from
(select
${getDateQuery('created_at', unit, timezone)} t,
count(${count !== '*' ? 'distinct session_id' : count}) y
from event
where event_name = ''
and website_id = $1
and rev_id = $2
and ${getBetweenDates('created_at', start_at, end_at)}
${pageviewQuery}
${sessionQuery}
group by t) g
order by t`,
params,
);
}

View File

@ -0,0 +1,102 @@
import cache from 'lib/cache';
import clickhouse from 'lib/clickhouse';
import { CLICKHOUSE, PRISMA, runQuery } from 'lib/db';
import prisma from 'lib/prisma';
import { UmamiApi } from 'interface/enum';
export async function getPageviewStats(
...args: [
websiteId: string,
data: {
startDate: Date;
endDate: Date;
timezone?: string;
unit?: string;
count?: string;
filters: object;
sessionKey?: string;
},
]
) {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
});
}
async function relationalQuery(
websiteId: string,
data: {
startDate: Date;
endDate: Date;
timezone?: string;
unit?: string;
count?: string;
filters: object;
sessionKey?: string;
},
) {
const {
startDate,
endDate,
timezone = 'utc',
unit = 'day',
count = '*',
filters = {},
sessionKey = 'session_id',
} = data;
const { getDateQuery, parseFilters, rawQuery } = prisma;
const params = [startDate, endDate];
const { filterQuery, joinSession } = parseFilters(filters, params);
return rawQuery(
`select ${getDateQuery('website_event.created_at', unit, timezone)} t,
count(${count !== '*' ? `${count}${sessionKey}` : count}) y
from website_event
${joinSession}
where website.website_id='${websiteId}'
and pageview.created_at between $1 and $2
and event_type = ${UmamiApi.EventType.Pageview}
${filterQuery}
group by 1`,
params,
);
}
async function clickhouseQuery(
websiteId: string,
data: {
startDate: Date;
endDate: Date;
timezone?: string;
unit?: string;
count?: string;
filters: object;
sessionKey?: string;
},
) {
const { startDate, endDate, timezone = 'UTC', unit = 'day', count = '*', filters = {} } = data;
const { parseFilters, rawQuery, getDateStringQuery, getDateQuery, getBetweenDates } = clickhouse;
const website = await cache.fetchWebsite(websiteId);
const params = [websiteId, website?.revId || 0];
const { filterQuery } = parseFilters(filters, params);
return rawQuery(
`select
${getDateStringQuery('g.t', unit)} as t,
g.y as y
from
(select
${getDateQuery('created_at', unit, timezone)} t,
count(${count !== '*' ? 'distinct session_id' : count}) y
from event
where website_id = $1
and rev_id = $2
and event_type = ${UmamiApi.EventType.Pageview}
and ${getBetweenDates('created_at', startDate, endDate)}
${filterQuery}
group by t) g
order by t`,
params,
);
}

View File

@ -1,43 +0,0 @@
import prisma from 'lib/prisma';
import clickhouse from 'lib/clickhouse';
import { runQuery, CLICKHOUSE, PRISMA } from 'lib/db';
export async function getPageviews(...args) {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
});
}
async function relationalQuery(websites, start_at) {
return prisma.client.pageview.findMany({
where: {
websiteId: {
in: websites,
},
createdAt: {
gte: start_at,
},
},
});
}
async function clickhouseQuery(websites, start_at) {
const { rawQuery, getCommaSeparatedStringFormat } = clickhouse;
return rawQuery(
`select
website_id,
session_id,
created_at,
url
from event
where event_name = ''
and ${
websites && websites.length > 0
? `website_id in (${getCommaSeparatedStringFormat(websites)})`
: '0 = 0'
}
and created_at >= ${clickhouse.getDateFormat(start_at)}`,
);
}

View File

@ -4,23 +4,43 @@ import kafka from 'lib/kafka';
import prisma from 'lib/prisma';
import cache from 'lib/cache';
import { uuid } from 'lib/crypto';
import { UmamiApi } from 'interface/enum';
export async function savePageView(...args) {
export async function savePageView(args: {
id: string;
websiteId: string;
url: string;
referrer?: string;
hostname?: string;
browser?: string;
os?: string;
device?: string;
screen?: string;
language?: string;
country?: string;
}) {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
[PRISMA]: () => relationalQuery(args),
[CLICKHOUSE]: () => clickhouseQuery(args),
});
}
async function relationalQuery(data) {
const { websiteId, sessionId, url, referrer } = data;
return prisma.client.pageview.create({
async function relationalQuery(data: {
id: string;
websiteId: string;
url: string;
referrer?: string;
}) {
const { websiteId, id: sessionId, url, referrer } = data;
return prisma.client.websiteEvent.create({
data: {
id: uuid(),
websiteId,
sessionId,
url: url?.substring(0, URL_LENGTH),
referrer: referrer?.substring(0, URL_LENGTH),
eventType: UmamiApi.EventType.Pageview,
},
});
}

View File

@ -2,11 +2,12 @@ import { CLICKHOUSE, PRISMA, runQuery } from 'lib/db';
import kafka from 'lib/kafka';
import prisma from 'lib/prisma';
import cache from 'lib/cache';
import { Prisma } from '@prisma/client';
export async function createSession(...args) {
export async function createSession(args: Prisma.SessionCreateInput) {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
[PRISMA]: () => relationalQuery(args),
[CLICKHOUSE]: () => clickhouseQuery(args),
}).then(async data => {
if (cache.enabled) {
await cache.storeSession(data);
@ -16,11 +17,21 @@ export async function createSession(...args) {
});
}
async function relationalQuery(data) {
async function relationalQuery(data: Prisma.SessionCreateInput) {
return prisma.client.session.create({ data });
}
async function clickhouseQuery(data) {
async function clickhouseQuery(data: {
id: string;
websiteId: string;
hostname?: string;
browser?: string;
os?: string;
device?: string;
screen?: string;
language?: string;
country?: string;
}) {
const { id, websiteId, hostname, browser, os, device, screen, language, country } = data;
const { getDateFormat, sendMessage } = kafka;
const website = await cache.fetchWebsite(websiteId);

View File

@ -1,21 +1,22 @@
import clickhouse from 'lib/clickhouse';
import { CLICKHOUSE, PRISMA, runQuery } from 'lib/db';
import prisma from 'lib/prisma';
import { Prisma } from '@prisma/client';
export async function getSession(...args) {
export async function getSession(args: { id: string }) {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
[PRISMA]: () => relationalQuery(args),
[CLICKHOUSE]: () => clickhouseQuery(args),
});
}
async function relationalQuery(where) {
async function relationalQuery(where: Prisma.SessionWhereUniqueInput) {
return prisma.client.session.findUnique({
where,
});
}
async function clickhouseQuery({ id: sessionId }) {
async function clickhouseQuery({ id: sessionId }: { id: string }) {
const { rawQuery, findFirst } = clickhouse;
const params = [sessionId];

View File

@ -3,17 +3,26 @@ import clickhouse from 'lib/clickhouse';
import { runQuery, CLICKHOUSE, PRISMA } from 'lib/db';
import cache from 'lib/cache';
export async function getSessionMetrics(...args) {
export async function getSessionMetrics(
...args: [
websiteId: string,
data: { startDate: Date; endDate: Date; field: string; filters: object },
]
) {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
});
}
async function relationalQuery(websiteId, { startDate, endDate, field, filters = {} }) {
async function relationalQuery(
websiteId: string,
data: { startDate: Date; endDate: Date; field: string; filters: object },
) {
const { startDate, endDate, field, filters = {} } = data;
const { parseFilters, rawQuery } = prisma;
const params = [startDate, endDate];
const { pageviewQuery, sessionQuery, joinSession } = parseFilters(null, filters, params);
const { filterQuery, joinSession } = parseFilters(filters, params);
return rawQuery(
`select ${field} x, count(*) y
@ -26,8 +35,7 @@ async function relationalQuery(websiteId, { startDate, endDate, field, filters =
${joinSession}
where website.website_id='${websiteId}'
and pageview.created_at between $1 and $2
${pageviewQuery}
${sessionQuery}
${filterQuery}
)
group by 1
order by 2 desc`,
@ -35,11 +43,15 @@ async function relationalQuery(websiteId, { startDate, endDate, field, filters =
);
}
async function clickhouseQuery(websiteId, { startDate, endDate, field, filters = {} }) {
async function clickhouseQuery(
websiteId: string,
data: { startDate: Date; endDate: Date; field: string; filters: object },
) {
const { startDate, endDate, field, filters = {} } = data;
const { parseFilters, getBetweenDates, rawQuery } = clickhouse;
const website = await cache.fetchWebsite(websiteId);
const params = [websiteId, website?.revId || 0];
const { pageviewQuery, sessionQuery } = parseFilters(null, filters, params);
const { filterQuery } = parseFilters(filters, params);
return rawQuery(
`select ${field} x, count(*) y
@ -48,8 +60,7 @@ async function clickhouseQuery(websiteId, { startDate, endDate, field, filters =
and rev_id = $2
and event_name = ''
and ${getBetweenDates('created_at', startDate, endDate)}
${pageviewQuery}
${sessionQuery}
${filterQuery}
group by x
order by y desc`,
params,

View File

@ -1,52 +0,0 @@
import prisma from 'lib/prisma';
import clickhouse from 'lib/clickhouse';
import { runQuery, PRISMA, CLICKHOUSE } from 'lib/db';
export async function getSessions(...args) {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
});
}
async function relationalQuery(websites, start_at) {
return prisma.client.session.findMany({
where: {
...(websites && websites.length > 0
? {
websiteId: {
in: websites,
},
}
: {}),
createdAt: {
gte: start_at,
},
},
});
}
async function clickhouseQuery(websites, start_at) {
const { rawQuery, getDateFormat, getCommaSeparatedStringFormat } = clickhouse;
return rawQuery(
`select distinct
session_id,
website_id,
created_at,
hostname,
browser,
os,
device,
screen,
language,
country
from event
where ${
websites && websites.length > 0
? `website_id in (${getCommaSeparatedStringFormat(websites)})`
: '0 = 0'
}
and created_at >= ${getDateFormat(start_at)}`,
);
}

View File

@ -3,14 +3,14 @@ import prisma from 'lib/prisma';
import clickhouse from 'lib/clickhouse';
import { runQuery, CLICKHOUSE, PRISMA } from 'lib/db';
export async function getActiveVisitors(...args) {
export async function getActiveVisitors(...args: [websiteId: string]) {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
});
}
async function relationalQuery(websiteId) {
async function relationalQuery(websiteId: string) {
const date = subMinutes(new Date(), 5);
const params = [date];
@ -25,7 +25,7 @@ async function relationalQuery(websiteId) {
);
}
async function clickhouseQuery(websiteId) {
async function clickhouseQuery(websiteId: string) {
const { rawQuery, getDateFormat } = clickhouse;
const params = [websiteId];

View File

@ -1,30 +0,0 @@
import { getPageviews } from '../pageview/getPageviews';
import { getSessions } from '../session/getSessions';
import { getEvents } from '../event/getEvents';
export async function getRealtimeData(websites, time) {
const [pageviews, sessions, events] = await Promise.all([
getPageviews(websites, time),
getSessions(websites, time),
getEvents(websites, time),
]);
return {
pageviews: pageviews.map(({ id, ...props }) => ({
__id: `p${id}`,
pageviewId: id,
...props,
})),
sessions: sessions.map(({ id, ...props }) => ({
__id: `s${id}`,
sessionId: id,
...props,
})),
events: events.map(({ id, ...props }) => ({
__id: `e${id}`,
eventId: id,
...props,
})),
timestamp: Date.now(),
};
}

View File

@ -0,0 +1,3 @@
export async function getRealtimeData() {
throw new Error('Not Implemented');
}

View File

@ -3,22 +3,23 @@ import clickhouse from 'lib/clickhouse';
import { runQuery, CLICKHOUSE, PRISMA } from 'lib/db';
import cache from 'lib/cache';
export async function getWebsiteStats(...args) {
export async function getWebsiteStats(
...args: [websiteId: string, data: { startDate: Date; endDate: Date; filters: object }]
) {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
});
}
async function relationalQuery(websiteId, { start_at, end_at, filters = {} }) {
async function relationalQuery(
websiteId: string,
data: { startDate: Date; endDate: Date; filters: object },
) {
const { startDate, endDate, filters = {} } = data;
const { getDateQuery, getTimestampInterval, parseFilters, rawQuery } = prisma;
const params = [start_at, end_at];
const { pageviewQuery, sessionQuery, joinSession } = parseFilters(
'pageview',
null,
filters,
params,
);
const params = [startDate, endDate];
const { filterQuery, joinSession } = parseFilters(filters, params);
return rawQuery(
`select sum(t.c) as "pageviews",
@ -36,19 +37,22 @@ async function relationalQuery(websiteId, { start_at, end_at, filters = {} }) {
${joinSession}
where website.website_id='${websiteId}'
and pageview.created_at between $1 and $2
${pageviewQuery}
${sessionQuery}
${filterQuery}
group by 1, 2
) t`,
params,
);
}
async function clickhouseQuery(websiteId, { start_at, end_at, filters = {} }) {
async function clickhouseQuery(
websiteId: string,
data: { startDate: Date; endDate: Date; filters: object },
) {
const { startDate, endDate, filters = {} } = data;
const { rawQuery, getDateQuery, getBetweenDates, parseFilters } = clickhouse;
const website = await cache.fetchWebsite(websiteId);
const params = [websiteId, website?.revId || 0];
const { pageviewQuery, sessionQuery } = parseFilters(null, filters, params);
const { filterQuery } = parseFilters(filters, params);
return rawQuery(
`select
@ -66,9 +70,8 @@ async function clickhouseQuery(websiteId, { start_at, end_at, filters = {} }) {
where event_name = ''
and website_id = $1
and rev_id = $2
and ${getBetweenDates('created_at', start_at, end_at)}
${pageviewQuery}
${sessionQuery}
and ${getBetweenDates('created_at', startDate, endDate)}
${filterQuery}
group by session_id, time_series
) t;`,
params,

28
tsconfig.json Normal file
View File

@ -0,0 +1,28 @@
{
"compilerOptions": {
"target": "es5",
"outDir": "./build",
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"incremental": true,
"lib": ["dom", "dom.iterable", "esnext"],
"skipLibCheck": true,
"esModuleInterop": true,
"noImplicitAny": false,
"preserveConstEnums": true,
"removeComments": true,
"sourceMap": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"allowJs": true,
"strict": true,
"baseUrl": ".",
"strictNullChecks": false,
"noEmit": true,
"jsx": "preserve"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "queries/admin/website/getAllWebsites.ts"],
"exclude": ["node_modules"]
}