Skip to content

Commit

Permalink
add api routes for dash
Browse files Browse the repository at this point in the history
  • Loading branch information
fahimmehraj committed Feb 12, 2024
1 parent e3f8d29 commit 6ca6439
Show file tree
Hide file tree
Showing 14 changed files with 401 additions and 10 deletions.
22 changes: 21 additions & 1 deletion .env.local
Original file line number Diff line number Diff line change
@@ -1 +1,21 @@
DATABASE_URL='mysql://be64bxj9rei05uiom8hw:pscale_pw_AkKRh9rEw2Jn9aBITBd7LBgiB0MLS8WoRwZsqUDthS8@aws.connect.psdb.cloud/atomhacks?sslaccept=strict'
# Created by Vercel CLI
BLOB_READ_WRITE_TOKEN="vercel_blob_rw_qvp4owlAyWnIY4PO_eWaDQ6ZN2tFbfsw2p6Fby355l6mAxd"
DATABASE_URL="mysql://be64bxj9rei05uiom8hw:pscale_pw_AkKRh9rEw2Jn9aBITBd7LBgiB0MLS8WoRwZsqUDthS8@aws.connect.psdb.cloud/atomhacks?sslaccept=strict"
NEXTAUTH_SECRET="b9dd8b68d7a71cb5a16bdbcea00abee7"
NX_DAEMON=""
TURBO_REMOTE_ONLY=""
TURBO_RUN_SUMMARY=""
VERCEL="1"
VERCEL_ENV="development"
VERCEL_GIT_COMMIT_AUTHOR_LOGIN=""
VERCEL_GIT_COMMIT_AUTHOR_NAME=""
VERCEL_GIT_COMMIT_MESSAGE=""
VERCEL_GIT_COMMIT_REF=""
VERCEL_GIT_COMMIT_SHA=""
VERCEL_GIT_PREVIOUS_SHA=""
VERCEL_GIT_PROVIDER=""
VERCEL_GIT_PULL_REQUEST_ID=""
VERCEL_GIT_REPO_ID=""
VERCEL_GIT_REPO_OWNER=""
VERCEL_GIT_REPO_SLUG=""
VERCEL_URL=""
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,4 @@ yarn-error.log*
next-env.d.ts

.direnv
.env*.local
59 changes: 59 additions & 0 deletions app/api/submission/create/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import prisma from "@/lib/prisma";
import { duplicateEntry, filterBodyAndValidate, getUser, getUserFromRequest, missingFields, redirect, unauthorized, wrongMethod } from "@/lib/server";
import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library";
import { NextResponse } from "next/server";

const fields = ["name", "description", "tracks"] as const;
const req_fields = ["name", "description", "tracks"] as const;

export default async function POST(req: Request) {
if (req.method != "POST") {
return wrongMethod();
}

// https://stackoverflow.com/questions/61190495/how-to-create-object-from-another-without-undefined-properties
const body = filterBodyAndValidate(await req.json(), fields, req_fields);
if (!body) {
return missingFields();
}

const user = await getUserFromRequest();
if (!user) {
return redirect("/api/auth/signin");
}

if (!user.teamId) {
return redirect("/dashboard/team/create")
}

try {
const submission = await prisma.submission.create({
data: {
...body,
team: {
connect:
{
id: user.teamId
},
},
},
include: {
team: {
include: {
users: true,
submission: true,
}
}
},
});
return NextResponse.json(submission, { status: 201 });
} catch (error) {
console.log(error);
if (error instanceof PrismaClientKnownRequestError) {
if (error.code == "P2002") {
return duplicateEntry();
}
}
return NextResponse.json({ message: "unknown error" }, { status: 400 });
}
}
75 changes: 75 additions & 0 deletions app/api/submission/edit/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { handleUpload, type HandleUploadBody } from '@vercel/blob/client';
import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library";
import prisma from "@/lib/prisma";
import {
duplicateEntry,
filterBodyAndValidate,
getUserFromRequest,
missingFields,
redirect,
wrongMethod,
} from "@/lib/server";
import { NextResponse } from 'next/server';

const fields = ["name", "description", "tracks", "srcLink", "videoLink", "public", "icon"] as const;
const req_fields = ["name", "description", "tracks"] as const;

export default async function PUT(req: Request) {
if (req.method != "PUT") {
return wrongMethod();
}

const user = await getUserFromRequest();
if (!user) {
return redirect("/api/auth/signin");
}

// https://stackoverflow.com/questions/61190495/how-to-create-object-from-another-without-undefined-properties
const body = filterBodyAndValidate(await req.json(), fields, req_fields);
if (!body) {
return missingFields();
}

if (!user.team || !user.teamId) {
return redirect("/dashboard/team/create");
}

if (!user.team.submission) {
return redirect("/dashboard/submission/create");
}

// TODO: currently it reassigns image so it replaces images after editiing
// instead of appending
try {
const submission = await prisma.submission.update({
where: {
id: user.team.submission.id,
},
data: {
...body,
team: {
connect: {
id: user.teamId,
},
},
},
include: {
team: {
include: {
users: true,
submission: true,
},
},
},
});
return NextResponse.json(submission, { status: 201 });
} catch (error) {
console.log(error);
if (error instanceof PrismaClientKnownRequestError) {
if (error.code == "P2002") {
return duplicateEntry();
}
}
return NextResponse.json({ message: "Unknown Error" }, { status: 400 });
}
}
78 changes: 78 additions & 0 deletions app/api/submission/image/upload/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { handleUpload, type HandleUploadBody } from '@vercel/blob/client';
import { NextResponse } from 'next/server';
import prisma from "@/lib/prisma";
import { getSubmission, getUserFromRequest, redirect } from '@/lib/server';

export async function POST(request: Request) {
const body = (await request.json()) as HandleUploadBody;


try {
const jsonResponse = await handleUpload({
body,
request,
onBeforeGenerateToken: async (
pathname: string,
/* clientPayload?: string, */
) => {
const user = await getUserFromRequest();
if (!user) {
throw new Error("Not Authenticated");
}

if (!user.team || !user.teamId) {
throw new Error("No team");
}

if (!user.team.submission) {
throw new Error("No Submission");
}

return {
allowedContentTypes: ['image/jpeg', 'image/png', 'image/gif'],
tokenPayload: JSON.stringify({
submissionId: user.team.id,
}),
};
},
onUploadCompleted: async ({ blob, tokenPayload }) => {
console.log('blob upload completed', blob, tokenPayload);
if (!tokenPayload) {
throw new Error("Impossible");
}

try {
const { submissionId } = JSON.parse(tokenPayload);
const existingSubmission = await getSubmission(submissionId);
if (!existingSubmission) {
throw new Error("No submission with id", submissionId);
}
const submission = await prisma.submission.update({
where: {
id: submissionId
},
data: {
media: {
create: [
{
url: blob.url
}
]
}
}
});
console.log("success", submission);
} catch (error) {
throw new Error(`Could not update user: ${error}`);
}
},
});

return NextResponse.json(jsonResponse);
} catch (error) {
return NextResponse.json(
{ error: (error as Error).message },
{ status: 400 }, // The webhook will retry 5 times waiting for a 200
);
}
}
51 changes: 51 additions & 0 deletions app/api/team/create/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import prisma from "@/lib/prisma";
import { duplicateEntry, filterBodyAndValidate, missingFields, unauthorized, wrongMethod } from "@/lib/server";
import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library";
import { getUserFromRequest } from "@/lib/server";
import { NextResponse } from "next/server";

const requiredFields = ["name", "users"] as const;
const fields = [...requiredFields] as const;

export default async function POST(req: Request) {
if (req.method != "POST") {
return wrongMethod();
}
const user = await getUserFromRequest();
if (!user) {
return unauthorized();
}

let body = filterBodyAndValidate(await req.json(), fields, requiredFields);
if (!body) {
return missingFields();
}

const { users: ids, ...restOfBody } = body;

try {
const team = await prisma.team.create({
data: {
...restOfBody,
users: {
connect: ids
.map((id: string) => ({
id,
}))
.concat([{ id: user.id }]),
},
},
include: {
users: true,
},
});
return NextResponse.json(team, { status: 201 });
} catch (error) {
console.log(error);
if (error instanceof PrismaClientKnownRequestError) {
if (error.code == "P2002") {
return duplicateEntry();
}
}
}
}
63 changes: 63 additions & 0 deletions app/api/team/edit/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library";
import { duplicateEntry, filterBody, getUserFromRequest, missingFields, unauthorized, wrongMethod } from "@/lib/server";
import prisma from "@/lib/prisma";
import { NextResponse } from "next/server";

const fields = ["name", "users"] as const;

export default async function POST(req: Request) {
if (req.method != "POST") {
return wrongMethod();
}

const user = await getUserFromRequest();
if (!user) {
return unauthorized();
}
if (!user.team || !user.teamId) {
return unauthorized();
}

let body = filterBody(await req.json(), fields);
if (!body) {
return missingFields();
}
console.log(body);

let { users: ids, ...restOfBody } = body;
// if the users in body are also currently in team, that is deletion
// if not add it
// Hackathon level code
ids = user.team.users
.map((user) => user.id)
.filter((id) => !ids.some((new_id: string) => id == new_id))
.concat(ids.filter((id: string) => !user.team!.users.some((user) => user.id == id)));
console.log(ids);

try {
const team = await prisma.team.update({
where: {
id: user.teamId,
},
data: {
...restOfBody,
users: {
set: ids.map((id: string) => ({
id,
})),
},
},
include: {
users: true,
},
});
return NextResponse.json(team, { status: 201 });
} catch (error) {
console.log(error);
if (error instanceof PrismaClientKnownRequestError) {
if (error.code == "P2002") {
return duplicateEntry();
}
}
}
}
2 changes: 1 addition & 1 deletion app/dashboard/components/DashNav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export default function Navbar() {
Back to Home
</NavButton>
{routes.map((route, index) => (
<NavButton href={route.path} lineColor={route.color}>
<NavButton key={index} href={route.path} lineColor={route.color}>
{route.name}
</NavButton>
))}
Expand Down
3 changes: 3 additions & 0 deletions app/dashboard/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ export default async function Dashboard() {
console.log("yeas");
redirect("/dashboard/form");
}

console.log(session.user)
console.log(user);
return (
<>
<div className="mb-8 flex items-center justify-center">
Expand Down
3 changes: 2 additions & 1 deletion flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
nodePackages.prisma
nodePackages.pnpm
nodePackages.typescript-language-server
nodePackages.vercel
nodejs_20
];
shellHook = with pkgs; ''
Expand All @@ -24,4 +25,4 @@
'';
};
});
}
}
Loading

0 comments on commit 6ca6439

Please sign in to comment.