Skip to content

Commit

Permalink
generate custom file key
Browse files Browse the repository at this point in the history
  • Loading branch information
rajdeep-ghosh committed Jul 25, 2024
1 parent d54753b commit de35d2c
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/app/api/drop/route.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import crypto from 'node:crypto';
import { NextResponse } from 'next/server';
import { eq } from 'drizzle-orm';
import { generateErrorMessage } from 'zod-error';

import { createFileReqSchema, getFileReqSchema } from '@/lib/api/schema/drop';
import { generateFileKey } from '@/lib/utils';
import db from '@/lib/db';
import { filesTable } from '@/lib/db/schema';
import { getObject, putObject } from '@/lib/storage';
Expand All @@ -29,7 +29,7 @@ async function POST(req: NextRequest) {
}

try {
const key = `${crypto.randomBytes(8).toString('hex')}-${body.data.name.replace(/\s+/g, '_')}`;
const key = generateFileKey(body.data.name);

const [newFile] = await db
.insert(filesTable)
Expand Down
12 changes: 11 additions & 1 deletion src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,14 @@ function getTimeDifference(futureTimeStr: Date) {
}
}

export { cn, formatBytes, getTimeDifference };
function generateFileKey(filename: string, length = 8) {
const array = new Uint8Array(length);
crypto.getRandomValues(array);
const randomStr = Array.from(array, (byte) =>
byte.toString(16).padStart(2, '0')
).join('');

return `${randomStr}-${filename.replace(/\s+/g, '_')}`;
}

export { cn, formatBytes, getTimeDifference, generateFileKey };

0 comments on commit de35d2c

Please sign in to comment.