Skip to content

Commit

Permalink
feat(large-file-upload): auth and file record
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaosen7 committed Aug 12, 2024
1 parent d3102d4 commit 4fa51c0
Show file tree
Hide file tree
Showing 26 changed files with 699 additions and 675 deletions.
4 changes: 2 additions & 2 deletions apps/large-file-upload/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
"version": "0.6.2",
"private": true,
"scripts": {
"dev": "next dev",
"dev": "npcs dev",
"build": "next build",
"lint": "eslint .",
"typecheck": "tsc --noEmit",
"prisma-generate": "prisma generate",
"clean": "npcs clean"
},
"dependencies": {
"@clerk/nextjs": "^5.2.6",
"@clerk/nextjs": "^5.3.0",
"@esbuild-plugins/tsconfig-paths": "^0.1.2",
"@npcs/env": "workspace:^",
"@npcs/log": "workspace:^",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
-- AlterTable
ALTER TABLE "File" ALTER COLUMN "state" SET DEFAULT '',
ALTER COLUMN "state" SET DATA TYPE TEXT;
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/*
Warnings:
- You are about to drop the column `chunkSize` on the `File` table. All the data in the column will be lost.
- You are about to drop the column `concurrency` on the `File` table. All the data in the column will be lost.
- You are about to drop the column `poolElapse` on the `File` table. All the data in the column will be lost.
- You are about to drop the column `state` on the `File` table. All the data in the column will be lost.
*/
-- AlterTable
ALTER TABLE "File" DROP COLUMN "chunkSize",
DROP COLUMN "concurrency",
DROP COLUMN "poolElapse",
DROP COLUMN "state";
14 changes: 5 additions & 9 deletions apps/large-file-upload/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,9 @@ model User {
}

model File {
id String @id @default(uuid())
hash String
name String
users User[] @relation("UserFiles")
size Int @default(0)
concurrency Int @default(0)
chunkSize Int @default(0)
poolElapse Int @default(0)
state Int @default(0)
id String @id @default(uuid())
hash String
name String
users User[] @relation("UserFiles")
size Int @default(0)
}
52 changes: 8 additions & 44 deletions apps/large-file-upload/src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
"use server";
import { getCurrentUser, getCurrentUserOrThrow } from "@/actions/user";
import { addFile, getFiles, removeFile } from "@/actions/file";
import { getCurrentUser } from "@/actions/user";
import { log } from "@/log";
import { prisma } from "@/prisma/client";
import { auth } from "@clerk/nextjs/server";
import {
configuration,
FileSystemStorage,
IUploadProps,
startWebsocketServer,
Upload,
} from "@npcs/upload";
Expand All @@ -29,52 +28,16 @@ const requireAuth = async () => {
redirectToSignIn();
};

const onComplete: IUploadProps["onComplete"] = async (fileJSON) => {
"use server";
log.log(fileJSON);

const existingFile = await prisma.file.findFirst({
where: {
name: fileJSON.name,
hash: fileJSON.hash,
},
});

const user = await getCurrentUserOrThrow();
if (existingFile) {
await prisma.user.update({
where: user,
data: {
files: {
update: {
where: {
id: existingFile.id,
},
data: fileJSON,
},
},
},
});
} else {
await prisma.file.create({
data: {
...fileJSON,
users: {
connect: {
id: user.id,
},
},
},
});
}
};

export default async function Home() {
const user = await getCurrentUser();
const files = await getFiles();

log.debug(files);

return (
<div className="w-2/3 min-w-96">
<Upload
initialFiles={files}
input={
user
? undefined
Expand All @@ -83,7 +46,8 @@ export default async function Home() {
}
}
maxSize={1024 * 1024 * 1024}
onComplete={onComplete}
onComplete={addFile}
onRemove={removeFile}
/>
</div>
);
Expand Down
85 changes: 85 additions & 0 deletions apps/large-file-upload/src/libs/actions/file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
"use server";

import { log } from "@/log";
import { prisma } from "@/prisma/client";
import { IUploadClientJSON } from "@npcs/upload";
import { getCurrentUser, getCurrentUserOrThrow } from "./user";

export async function addFile(info: IUploadClientJSON) {
log.log(info);

const user = await getCurrentUserOrThrow();
const existingFile = await prisma.file.findFirst({
where: {
name: info.name,
hash: info.hash,
},
});

if (existingFile) {
await prisma.user.update({
where: user,
data: {
files: {
update: {
where: {
id: existingFile.id,
},
data: info,
},
},
},
});
} else {
await prisma.file.create({
data: {
...info,
users: {
connect: {
id: user.id,
},
},
},
});
}
}

export async function getFiles() {
const user = await getCurrentUser();
if (!user) {
return [];
}

const userWithFiles = await prisma.user.findFirst({
where: {
id: user.id,
},
include: {
files: true,
},
});

return userWithFiles?.files ?? [];
}

export async function removeFile(info: IUploadClientJSON) {
const user = await getCurrentUserOrThrow();

const existingFile = await prisma.file.findFirstOrThrow({
where: {
name: info.name,
hash: info.hash,
},
});

await prisma.user.update({
where: {
id: user.id,
},
data: {
files: {
disconnect: existingFile,
},
},
});
}
34 changes: 29 additions & 5 deletions apps/large-file-upload/src/libs/actions/user.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,26 @@
"use server";

import { log } from "@/log";
import { prisma } from "@/prisma/client";
import { currentUser } from "@clerk/nextjs/server";
import { auth, currentUser } from "@clerk/nextjs/server";
import { env } from "@npcs/env/shared";

async function getClerkId() {
async function getClerkUser() {
try {
const clerkUser = await currentUser();
return clerkUser?.id;
return await currentUser();
} catch (error) {
log.error(error);
return null;
}
}

export async function getClerkUserId() {
return auth().userId;
}

export async function getCurrentUser() {
const clerkId = await getClerkId();
const clerkId = await getClerkUserId();
log.debug({ clerkId });
if (!clerkId) {
return null;
}
Expand All @@ -22,6 +30,22 @@ export async function getCurrentUser() {
clerkId,
},
});

log.debug({ user });

// Enable test users in development
if (env.NODE_ENV === "development" && !user) {
const clerkUser = await getClerkUser();
if (clerkUser?.emailAddresses[0]?.emailAddress.includes("+clerk_test")) {
const user = await prisma.user.create({
data: {
clerkId,
},
});
return user;
}
}

return user;
}

Expand Down
4 changes: 3 additions & 1 deletion apps/large-file-upload/src/libs/log/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { createLog } from "@npcs/log";
import { env } from "@npcs/env/shared";
import { createLog, LogLevels } from "@npcs/log";

export const log = createLog("large-file-upload");
log.level = env.NODE_ENV === "development" ? LogLevels.debug : LogLevels.info;
2 changes: 1 addition & 1 deletion apps/notes/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"prisma-generate": "prisma generate"
},
"dependencies": {
"@clerk/nextjs": "^5.2.6",
"@clerk/nextjs": "^5.3.0",
"@clerk/themes": "^2.1.12",
"@faker-js/faker": "^8.4.1",
"@npcs/log": "workspace:^",
Expand Down
2 changes: 1 addition & 1 deletion apps/stackoverflow/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"seed": "tsx -r tsconfig-paths/register prisma/seed.ts"
},
"dependencies": {
"@clerk/nextjs": "^5.2.6",
"@clerk/nextjs": "^5.3.0",
"@faker-js/faker": "^8.4.1",
"@hookform/resolvers": "^3.9.0",
"@npcs/log": "workspace:^",
Expand Down
2 changes: 1 addition & 1 deletion apps/template/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"prisma-generate": "prisma generate"
},
"dependencies": {
"@clerk/nextjs": "^5.2.6",
"@clerk/nextjs": "^5.3.0",
"@npcs/log": "workspace:^",
"@npcs/next-config": "workspace:^",
"@npcs/playwright-config": "workspace:^",
Expand Down
41 changes: 20 additions & 21 deletions configs/next/prepare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,10 @@ function prepare() {
processPrismaDevFlow();
}

loadAndCheckEnv(IS_DEV);
loadAndCheckEnv();
}

function loadAndCheckEnv(isDev: boolean) {
const __filename = fileURLToPath(import.meta.url);
const jiti = createJiti(__filename);

function loadAndCheckEnv() {
/**
* local env file should only exists in development environment.
* In some other environment, such as github actions or docker, local env should extends from externals
Expand All @@ -37,31 +34,30 @@ function loadAndCheckEnv(isDev: boolean) {
? join(__dirname, ".env.local")
: "";
const envPath = join(__dirname, ".env");
const devEnvPath = isDev ? join(__dirname, ".env.development") : "";
const devEnvPath = IS_DEV ? join(__dirname, ".env.development") : "";

// load from file
dotenv.config({
path: [localEnvPath, envPath, devEnvPath].filter(Boolean),
});

// check
const { env: server } = jiti(
"@npcs/env/server",
) as typeof import("@npcs/env/server");
const { env: client } = jiti(
"@npcs/env/client",
) as typeof import("@npcs/env/client");
const __filename = fileURLToPath(import.meta.url);
const jiti = createJiti(__filename);
const loader = (side: string) => jiti(`@npcs/env/${side}`).env;

printEnv(server, "server");
printEnv(client, "client");
}
checkEnv("shared", loader);
checkEnv("server", loader);
checkEnv("client", loader);

function printEnv(env: Record<string, string | undefined>, side: string) {
if (IS_DEV) {
log.info(
`The environment variables in ${side} side are as follows (only logs in development):`,
);
log.table(Object.entries(env).map(([name, value]) => ({ name, value })));
function checkEnv(side: string, loader: (id: string) => object) {
const env = loader(side);
if (IS_DEV) {
log.info(
`The environment variables in \`${side}\` are as follows (only logs in development):`,
);
log.table(Object.entries(env).map(([name, value]) => ({ name, value })));
}
}
}

Expand All @@ -75,5 +71,8 @@ function processPrismaDevFlow() {
const hasSeed = !!APP_PACKAGE_JSON?.prisma?.seed;
exec(
`pnpm prisma migrate dev ${hasSeed ? `&& pnpm prisma db seed` : ""} && pnpm prisma studio -b false`,
{
stdio: "inherit",
},
);
}
1 change: 1 addition & 0 deletions configs/rollup/rollup.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export default {
rootDir: "./src",
incremental: false,
jsx: "react-jsx",
sourceMap: true,
},
exclude: ["**/*.stories.*", "**/*.test.*"],
}),
Expand Down
Loading

0 comments on commit 4fa51c0

Please sign in to comment.