Skip to content

Commit

Permalink
Updated search queries.
Browse files Browse the repository at this point in the history
  • Loading branch information
mikecao committed Feb 4, 2024
1 parent 80a58cb commit e971f25
Show file tree
Hide file tree
Showing 12 changed files with 90 additions and 147 deletions.
8 changes: 4 additions & 4 deletions src/app/(main)/dashboard/Dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@ import useDashboard from 'store/dashboard';

export function Dashboard() {
const { formatMessage, labels, messages } = useMessages();
const { teamId } = useTeamContext();
const { teamId, renderTeamUrl } = useTeamContext();
const { showCharts, editing } = useDashboard();
const { dir } = useLocale();
const pageSize = 10;

const { result, query, params, setParams } = useWebsites({}, { pageSize });
const { result, query, params, setParams } = useWebsites({ teamId }, { pageSize });
const { page } = params;
const hasData = !!result?.data;
const hasData = !!result?.data?.length;

const handlePageChange = (page: number) => {
setParams({ ...params, page });
Expand All @@ -36,7 +36,7 @@ export function Dashboard() {
</PageHeader>
{!hasData && (
<EmptyPlaceholder message={formatMessage(messages.noWebsitesConfigured)}>
<Link href="/settings/websites">
<Link href={renderTeamUrl('/settings/websites')}>
<Button>
<Icon rotate={dir === 'rtl' ? 180 : 0}>
<Icons.ArrowRight />
Expand Down
2 changes: 1 addition & 1 deletion src/app/(main)/settings/websites/Websites.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export default function Websites({ teamId }: { teamId: string }) {

return (
<>
<WebsitesHeader showActions={user.role !== 'view-only'} />
<WebsitesHeader teamId={teamId} showActions={user.role !== 'view-only'} />
<WebsitesDataTable teamId={teamId} userId={user.id} allowEdit={true} />
</>
);
Expand Down
2 changes: 1 addition & 1 deletion src/app/(main)/websites/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Metadata } from 'next';
export default function WebsitesPage({ params: { teamId, userId } }) {
return (
<>
<WebsitesHeader showActions={false} />
<WebsitesHeader teamId={teamId} showActions={false} />
<WebsitesBrowse teamId={teamId} userId={userId} />
</>
);
Expand Down
2 changes: 1 addition & 1 deletion src/components/input/ProfileButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { useMessages } from 'components/hooks';
import { useLogin } from 'components/hooks';
import { useLocale } from 'components/hooks';
import { CURRENT_VERSION } from 'lib/constants';
import styles from './ProfileButton.module.css';
import Avatar from 'components/common/Avatar';
import styles from './ProfileButton.module.css';

export function ProfileButton() {
const { formatMessage, labels } = useMessages();
Expand Down
4 changes: 4 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export * from 'components/hooks/useMessages';
export * from 'components/hooks/useNavigation';
export * from 'components/hooks/useSticky';
export * from 'components/hooks/useTheme';
export * from 'components/hooks/useTeamContext';
export * from 'components/hooks/useTimezone';

export * from './app/(main)/settings/teams/[teamId]/TeamEditForm';
Expand Down Expand Up @@ -60,3 +61,6 @@ export * from 'components/common/HoverTooltip';
export * from 'components/common/LinkButton';
export * from 'components/common/MobileMenu';
export * from 'components/common/Pager';

export * from 'components/input/TeamsButton';
export * from 'components/input/ThemeButton';
18 changes: 7 additions & 11 deletions src/lib/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,27 +17,23 @@ export function getDatabaseType(url = process.env.DATABASE_URL) {
return POSTGRESQL;
}

if (process.env.CLICKHOUSE_URL) {
return CLICKHOUSE;
}

return type;
}

export async function runQuery(queries: any) {
const db = getDatabaseType(process.env.CLICKHOUSE_URL || process.env.DATABASE_URL);

if (db === POSTGRESQL || db === MYSQL) {
return queries[PRISMA]();
}

if (db === CLICKHOUSE) {
if (process.env.CLICKHOUSE_URL) {
if (queries[KAFKA]) {
return queries[KAFKA]();
}

return queries[CLICKHOUSE]();
}

const db = getDatabaseType();

if (db === POSTGRESQL || db === MYSQL) {
return queries[PRISMA]();
}
}

export function notImplemented() {
Expand Down
44 changes: 36 additions & 8 deletions src/lib/prisma.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const POSTGRESQL_DATE_FORMATS = {
};

function getAddIntervalQuery(field: string, interval: string): string {
const db = getDatabaseType(process.env.DATABASE_URL);
const db = getDatabaseType();

if (db === POSTGRESQL) {
return `${field} + interval '${interval}'`;
Expand All @@ -36,7 +36,7 @@ function getAddIntervalQuery(field: string, interval: string): string {
}

function getDayDiffQuery(field1: string, field2: string): string {
const db = getDatabaseType(process.env.DATABASE_URL);
const db = getDatabaseType();

if (db === POSTGRESQL) {
return `${field1}::date - ${field2}::date`;
Expand All @@ -48,7 +48,7 @@ function getDayDiffQuery(field1: string, field2: string): string {
}

function getCastColumnQuery(field: string, type: string): string {
const db = getDatabaseType(process.env.DATABASE_URL);
const db = getDatabaseType();

if (db === POSTGRESQL) {
return `${field}::${type}`;
Expand Down Expand Up @@ -92,7 +92,7 @@ function getTimestampDiffQuery(field1: string, field2: string): string {
}
}

function mapFilter(column, operator, name, type = 'varchar') {
function mapFilter(column: string, operator: string, name: string, type = 'varchar') {
switch (operator) {
case OPERATORS.equals:
return `${column} = {{${name}::${type}}}`;
Expand Down Expand Up @@ -208,16 +208,44 @@ function getQueryMode(): Prisma.QueryMode {
return 'default';
}

function getSearchParameters(query: string, filters: { [key: string]: any }[]) {
if (!query) return;

const mode = getQueryMode();
const parseFilter = (filter: { [key: string]: any }) => {
const [[key, value]] = Object.entries(filter);

return {
[key]:
typeof value === 'string'
? {
[value]: query,
mode,
}
: parseFilter(value),
};
};

const params = filters.map(filter => parseFilter(filter));

return {
AND: {
OR: params,
},
};
}

export default {
...prisma,
getAddIntervalQuery,
getDayDiffQuery,
getCastColumnQuery,
getDayDiffQuery,
getDateQuery,
getTimestampDiffQuery,
getFilterQuery,
parseFilters,
getSearchParameters,
getTimestampDiffQuery,
getQueryMode,
rawQuery,
pagedQuery,
parseFilters,
rawQuery,
};
16 changes: 12 additions & 4 deletions src/pages/api/reports/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ import { useAuth, useCors, useValidate } from 'lib/middleware';
import { NextApiRequestQueryBody } from 'lib/types';
import { pageInfo } from 'lib/schema';
import { NextApiResponse } from 'next';
import { methodNotAllowed, ok } from 'next-basics';
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { createReport, getReports } from 'queries';
import * as yup from 'yup';
import { canViewTeam, canViewWebsite } from 'lib/auth';

export interface ReportRequestBody {
websiteId: string;
Expand Down Expand Up @@ -51,16 +52,23 @@ export default async (
const { page, query, pageSize, websiteId, teamId } = req.query;
const filters = {
page,
pageSize: +pageSize || undefined,
pageSize,
query,
};

if (
(websiteId && !(await canViewWebsite(req.auth, websiteId))) ||
(teamId && !(await canViewTeam(req.auth, teamId)))
) {
return unauthorized(res);
}

const data = await getReports(
{
where: {
userId: !teamId && !websiteId ? userId : undefined,
websiteId,
website: {
id: websiteId,
userId: !websiteId && !teamId ? userId : undefined,
teamId,
},
},
Expand Down
72 changes: 17 additions & 55 deletions src/queries/admin/report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,68 +20,30 @@ export async function getReports(
criteria: ReportFindManyArgs,
filters: ReportSearchFilter = {},
): Promise<FilterResult<Report[]>> {
const mode = prisma.getQueryMode();
const { query, userId, websiteId } = filters;
const { query } = filters;

const where: Prisma.ReportWhereInput = {
userId,
websiteId,
...criteria.where,
AND: [
...prisma.getSearchParameters(query, [
{ name: 'contains' },
{ description: 'contains' },
{ type: 'contains' },
{
OR: [
{
userId,
},
],
user: {
username: 'contains',
},
},
{
OR: [
{
name: {
contains: query,
mode,
},
},
{
description: {
contains: query,
mode,
},
},
{
type: {
contains: query,
mode,
},
},
{
user: {
username: {
contains: query,
mode,
},
},
},
{
website: {
name: {
contains: query,
mode,
},
},
},
{
website: {
domain: {
contains: query,
mode,
},
},
},
],
website: {
name: 'contains',
},
},
{
website: {
domain: 'contains',
},
},
],
]),
};

return prisma.pagedQuery('report', { ...criteria, where }, filters);
Expand Down
35 changes: 3 additions & 32 deletions src/queries/admin/team.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,41 +24,12 @@ export async function getTeams(
criteria: TeamFindManyArgs,
filters: TeamSearchFilter = {},
): Promise<FilterResult<Team[]>> {
const mode = prisma.getQueryMode();
const { userId, query } = filters;
const { getSearchParameters } = prisma;
const { query } = filters;

const where: Prisma.TeamWhereInput = {
...criteria.where,
...(userId && {
teamUser: {
some: { userId },
},
}),
...(query && {
AND: {
OR: [
{
name: {
startsWith: query,
mode,
},
},
{
teamUser: {
some: {
role: ROLES.teamOwner,
user: {
username: {
startsWith: query,
mode,
},
},
},
},
},
],
},
}),
...getSearchParameters(query, [{ name: 'contains' }]),
};

return prisma.pagedQuery<TeamFindManyArgs>(
Expand Down
10 changes: 1 addition & 9 deletions src/queries/admin/teamUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,10 @@ export async function getTeamUsers(
filters?: TeamUserSearchFilter,
): Promise<FilterResult<TeamUser[]>> {
const { query } = filters;
const mode = prisma.getQueryMode();

const where: Prisma.TeamUserWhereInput = {
...criteria.where,
user: {
username: query
? {
contains: query,
mode,
}
: undefined,
},
...prisma.getSearchParameters(query, [{ user: { username: 'contains' } }]),
};

return prisma.pagedQuery(
Expand Down
Loading

0 comments on commit e971f25

Please sign in to comment.