Skip to content

Commit

Permalink
refactor: move more queries to queries.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
simonknittel committed Jan 7, 2025
1 parent ecc3bd6 commit 13c4adf
Show file tree
Hide file tree
Showing 56 changed files with 256 additions and 341 deletions.
10 changes: 2 additions & 8 deletions app/src/app/api/confirm-email/route.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { getEmailConfirmationToken } from "@/auth/queries";
import apiErrorHandler from "@/common/utils/apiErrorHandler";
import { prisma } from "@/db";
import { NextResponse, type NextRequest } from "next/server";
Expand All @@ -18,14 +19,7 @@ export async function GET(request: NextRequest) {
token: request.nextUrl.searchParams.get("token"),
});

const result = await prisma.emailConfirmationToken.findUnique({
where: {
token: paramsData.token,
expires: {
gt: new Date(),
},
},
});
const result = await getEmailConfirmationToken(paramsData.token);
if (!result)
return NextResponse.redirect(
new URL("/email-confirmation", request.url),
Expand Down
20 changes: 5 additions & 15 deletions app/src/app/api/operation/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ type Params = Promise<{
id: string;
}>;

const paramsSchema = z.string().cuid();
const paramsSchema = z.object({ id: z.string().cuid() });

const patchBodySchema = z.object({
title: z.string().trim(),
Expand All @@ -24,30 +24,20 @@ export async function PATCH(request: Request, props: { params: Params }) {
/**
* Validate the request params
*/
const paramsData = paramsSchema.parse((await props.params).id);
const params = paramsSchema.parse(await props.params);

/**
* Validate the request body
*/
const body: unknown = await request.json();
const data = patchBodySchema.parse(body);

/**
* Make sure the item exists.
*/
const item = await prisma.operation.findUnique({
where: {
id: paramsData,
},
});
if (!item) throw new Error("Not found");

/**
* Update
*/
const updatedItem = await prisma.operation.updateMany({
where: {
id: (await props.params).id,
id: params.id,
},
data: {
title: data.title,
Expand Down Expand Up @@ -76,14 +66,14 @@ export async function DELETE(request: Request, props: { params: Params }) {
/**
* Validate the request params
*/
const paramsData = paramsSchema.parse((await props.params).id);
const params = paramsSchema.parse(await props.params);

/**
* Delete
*/
await prisma.operation.delete({
where: {
id: paramsData,
id: params.id,
},
});

Expand Down
9 changes: 4 additions & 5 deletions app/src/app/api/spynet/organization/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import apiErrorHandler from "@/common/utils/apiErrorHandler";
import { scrapeOrganizationLogo } from "@/common/utils/scrapeOrganizationLogo";
import { prisma } from "@/db";
import { log } from "@/logging";
import { getOrganizationBySpectrumId } from "@/organizations/queries";
import { ConfirmationStatus } from "@prisma/client";
import { NextResponse } from "next/server";
import { serializeError } from "serialize-error";
Expand Down Expand Up @@ -34,11 +35,9 @@ export async function POST(request: Request) {
/**
* Do the thing
*/
const existingOrganization = await prisma.organization.findFirst({
where: {
spectrumId: data.spectrumId,
},
});
const existingOrganization = await getOrganizationBySpectrumId(
data.spectrumId,
);
if (existingOrganization) throw new Error("Duplicate");

let logo: string | undefined;
Expand Down
26 changes: 9 additions & 17 deletions app/src/app/api/upload/assign/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,48 +37,40 @@ export async function PATCH(request: Request) {
const data = bodySchema.parse(body);

/**
* Make sure the item exists.
* Assign the image to the resource
*/
if (data.resourceType === "manufacturer") {
/**
* Authenticate and authorize the request
*/
await authentication.authorizeApi(
"manufacturersSeriesAndVariants",
"manage",
);

const existingItem = await prisma.manufacturer.findUnique({
where: {
id: data.resourceId,
},
});
if (!existingItem) throw new Error("Not found");

/**
* Update
*/
await prisma.manufacturer.update({
where: {
id: existingItem.id,
id: data.resourceId,
},
data: {
[data.resourceAttribute]: data.imageId,
},
});
} else if (data.resourceType === "role") {
/**
* Authenticate and authorize the request
*/
await authentication.authorizeApi("role", "manage");

const existingItem = await prisma.role.findUnique({
where: {
id: data.resourceId,
},
});
if (!existingItem) throw new Error("Not found");

/**
* Update
*/
await prisma.role.update({
where: {
id: existingItem.id,
id: data.resourceId,
},
data: {
[data.resourceAttribute]: data.imageId,
Expand Down
4 changes: 2 additions & 2 deletions app/src/app/app/career/economic/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { getMyReadableFlows } from "@/career/queries";
import { Hero } from "@/common/components/Hero";
import Note from "@/common/components/Note";
import { SkeletonTile } from "@/common/components/SkeletonTile";
import { prisma } from "@/db";
import { getRoles } from "@/roles/queries";
import { type Metadata } from "next";
import { notFound } from "next/navigation";
import { Suspense } from "react";
Expand All @@ -27,7 +27,7 @@ export default async function Page() {
const flow = flows.find((flow) => flow.id === "economic");
if (!flow) notFound();

const roles = await prisma.role.findMany();
const roles = await getRoles();

return (
<main className="p-4 pb-20 lg:p-8">
Expand Down
4 changes: 2 additions & 2 deletions app/src/app/app/career/security/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { getMyReadableFlows } from "@/career/queries";
import { Hero } from "@/common/components/Hero";
import Note from "@/common/components/Note";
import { SkeletonTile } from "@/common/components/SkeletonTile";
import { prisma } from "@/db";
import { getRoles } from "@/roles/queries";
import { type Metadata } from "next";
import { notFound } from "next/navigation";
import { Suspense } from "react";
Expand All @@ -27,7 +27,7 @@ export default async function Page() {
const flow = flows.find((flow) => flow.id === "security");
if (!flow) notFound();

const roles = await prisma.role.findMany();
const roles = await getRoles();

return (
<main className="p-4 pb-20 lg:p-8">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getManufacturerById } from "@/fleet/utils/getManufacturerById";
import { getManufacturerById } from "@/fleet/queries";
import { notFound } from "next/navigation";

type Params = Promise<
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Link } from "@/common/components/Link";
import { dedupedGetSeriesAndManufacturerById } from "@/fleet/utils/getSeriesAndManufacturer";
import { dedupedGetSeriesAndManufacturerById } from "@/fleet/queries";
import { notFound } from "next/navigation";

type Params = Promise<
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { ImageUpload } from "@/common/components/ImageUpload";
import { SkeletonTile } from "@/common/components/SkeletonTile";
import { EditableManufacturerName } from "@/fleet/components/EditableManufacturerName";
import { SeriesTile } from "@/fleet/components/SeriesTile";
import { getManufacturerById } from "@/fleet/utils/getManufacturerById";
import { getManufacturerById } from "@/fleet/queries";
import { log } from "@/logging";
import clsx from "clsx";
import { type Metadata } from "next";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { SkeletonTile } from "@/common/components/SkeletonTile";
import { EditableSeriesName } from "@/fleet/components/EditableSeriesName";
import { VariantsTile } from "@/fleet/components/VariantsTile";
import { dedupedGetSeriesAndManufacturerById } from "@/fleet/utils/getSeriesAndManufacturer";
import { dedupedGetSeriesAndManufacturerById } from "@/fleet/queries";
import { log } from "@/logging";
import { type Metadata } from "next";
import { notFound } from "next/navigation";
Expand Down
8 changes: 2 additions & 6 deletions app/src/app/app/operations/page.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { authenticatePage } from "@/auth/server";
import Note from "@/common/components/Note";
import { dedupedGetUnleashFlag } from "@/common/utils/getUnleashFlag";
import { prisma } from "@/db";
import { CreateOperation } from "@/operations/components/CreateOperation";
import OperationTile from "@/operations/components/OperationTile";
import { getOperations } from "@/operations/queries";
import { type Metadata } from "next";
import { notFound } from "next/navigation";

Expand All @@ -17,11 +17,7 @@ export default async function Page() {
const authentication = await authenticatePage("/app/operations");
await authentication.authorizePage("operation", "manage");

const operations = await prisma.operation.findMany({
include: {
members: true,
},
});
const operations = await getOperations();

return (
<main className="p-4 pb-20 lg:p-8">
Expand Down
22 changes: 7 additions & 15 deletions app/src/app/app/roles/[id]/permissions/page.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { authenticatePage } from "@/auth/server";
import { Link } from "@/common/components/Link";
import { dedupedGetUnleashFlag } from "@/common/utils/getUnleashFlag";
import { prisma } from "@/db";
import { log } from "@/logging";
import { PermissionsTab } from "@/roles/components/PermissionsTab";
import { getRoleById } from "@/roles/queries";
import { getRoleById, getRoles } from "@/roles/queries";
import { getAllClassificationLevels, getAllNoteTypes } from "@/spynet/queries";
import { type Metadata } from "next";
import { notFound } from "next/navigation";
import { FaHome, FaLock, FaUsers } from "react-icons/fa";
Expand Down Expand Up @@ -48,19 +48,11 @@ export default async function Page({ params }: Props) {
const role = await getRoleById((await params).id);
if (!role) notFound();

const [allRoles, noteTypes, classificationLevels] = await prisma.$transaction(
[
prisma.role.findMany({
include: {
permissionStrings: true,
},
}),

prisma.noteType.findMany(),

prisma.classificationLevel.findMany(),
],
);
const [allRoles, noteTypes, classificationLevels] = await Promise.all([
getRoles(true),
getAllNoteTypes(),
getAllClassificationLevels(),
]);

const enableOperations = Boolean(
await dedupedGetUnleashFlag("EnableOperations"),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Actions } from "@/common/components/Actions";
import { prisma } from "@/db";
import { getAllClassificationLevels } from "@/spynet/queries";
import clsx from "clsx";
import Create from "./Create";
import Delete from "./Delete";
Expand All @@ -10,7 +10,7 @@ interface Props {
}

const ClassificationLevelsTile = async ({ className }: Readonly<Props>) => {
const classificationLevels = await prisma.classificationLevel.findMany();
const classificationLevels = await getAllClassificationLevels();

const sortedClassificationLevels = classificationLevels.toSorted((a, b) =>
a.name.localeCompare(b.name),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Actions } from "@/common/components/Actions";
import { prisma } from "@/db";
import { getAllNoteTypes } from "@/spynet/queries";
import clsx from "clsx";
import Create from "./Create";
import Delete from "./Delete";
Expand All @@ -10,7 +10,7 @@ interface Props {
}

const NoteTypesTile = async ({ className }: Readonly<Props>) => {
const noteTypes = await prisma.noteType.findMany();
const noteTypes = await getAllNoteTypes();

const sortedNoteTypes = noteTypes.toSorted((a, b) =>
a.name.localeCompare(b.name),
Expand Down
4 changes: 2 additions & 2 deletions app/src/app/app/spynet/citizen/_components/Tile.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { requireAuthentication } from "@/auth/server";
import { getCitizen } from "@/citizen/queries";
import { getAssignableRoles } from "@/common/utils/getAssignableRoles";
import { getAssignedAndVisibleRoles } from "@/common/utils/getAssignedAndVisibleRoles";
import { getLastSeenAt } from "@/common/utils/getLastSeenAt";
Expand All @@ -11,7 +12,6 @@ import {
sortAscWithAndNullLast,
sortDescAndNullLast,
} from "@/common/utils/sorting";
import { prisma } from "@/db";
import Pagination from "@/spynet/components/Pagination";
import clsx from "clsx";
import { Filters } from "./Filters";
Expand All @@ -27,7 +27,7 @@ export const Tile = async ({ className, searchParams }: Props) => {

const currentPage = getCurrentPageFromSearchParams(searchParams);

const entities = await prisma.entity.findMany();
const entities = await getCitizen();

const filters = searchParams.get("filters")?.split(",");

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { getAllClassificationLevelsDeduped } from "@/common/utils/cached/getAllClassificationLevels";
import getLatestNoteAttributes from "@/common/utils/getLatestNoteAttributes";
import { getAllClassificationLevels } from "@/spynet/queries";
import { type EntityLog, type EntityLogAttribute } from "@prisma/client";
import clsx from "clsx";

Expand All @@ -11,7 +11,7 @@ type Props = Readonly<{
}>;

export const ClassificationLevel = async ({ className, note }: Props) => {
const allClassificationLevels = await getAllClassificationLevelsDeduped();
const allClassificationLevels = await getAllClassificationLevels();
const { classificationLevelId } = getLatestNoteAttributes(note);

return (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { requireAuthentication } from "@/auth/server";
import TabPanel from "@/common/components/tabs/TabPanel";
import { getCreatableClassificationLevelsDeduped } from "@/common/utils/cached/getAllClassificationLevels";
import { getCreatableClassificationLevelsDeduped } from "@/spynet/utils/getAllClassificationLevels";
import {
type Entity,
type EntityLog,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { getCreatableClassificationLevelsDeduped } from "@/common/utils/cached/getAllClassificationLevels";
import getAllNoteTypes from "@/common/utils/cached/getAllNoteTypes";
import getLatestNoteAttributes from "@/common/utils/getLatestNoteAttributes";
import { getAllNoteTypes } from "@/spynet/queries";
import { getCreatableClassificationLevelsDeduped } from "@/spynet/utils/getAllClassificationLevels";
import { type EntityLog, type EntityLogAttribute } from "@prisma/client";
import { UpdateNoteModal } from "./UpdateNoteModal";

Expand Down
Loading

0 comments on commit 13c4adf

Please sign in to comment.