summaryrefslogtreecommitdiff
path: root/lib/storage.ts
diff options
context:
space:
mode:
authordujinkim <dujin.kim@dtsolution.co.kr>2025-03-26 00:37:41 +0000
committerdujinkim <dujin.kim@dtsolution.co.kr>2025-03-26 00:37:41 +0000
commite0dfb55c5457aec489fc084c4567e791b4c65eb1 (patch)
tree68543a65d88f5afb3a0202925804103daa91bc6f /lib/storage.ts
3/25 까지의 대표님 작업사항
Diffstat (limited to 'lib/storage.ts')
-rw-r--r--lib/storage.ts44
1 files changed, 44 insertions, 0 deletions
diff --git a/lib/storage.ts b/lib/storage.ts
new file mode 100644
index 00000000..ead937aa
--- /dev/null
+++ b/lib/storage.ts
@@ -0,0 +1,44 @@
+import fs from "fs/promises"
+import path from "path"
+import crypto from "crypto"
+
+/**
+ * 주어진 File을 해시된 파일명으로 로컬에 저장하고,
+ * 저장된 파일의 메타데이터를 반환하는 공용 함수
+ */
+export async function saveDocument(
+ file: File,
+ directory: string = "./public"
+) {
+ // 확장자 추출
+ const originalName = file.name
+ const ext = path.extname(originalName) || ""
+
+ // 해시 파일명 생성
+ const randomHash = crypto.randomBytes(20).toString("hex")
+ const hashedFileName = randomHash + ext
+
+ // 파일 저장
+ await storeFile(file, hashedFileName, directory)
+
+ // 필요한 메타데이터 반환 (원본 이름, 해시 파일명 등)
+ return {
+ originalName,
+ hashedFileName,
+ ext,
+ // 필요하면 file.size, file.type 등도 포함 가능
+ }
+}
+
+/**
+ * 실제 파일 쓰기 (로컬이든, S3든 자유롭게 교체 가능)
+ */
+async function storeFile(file: File, hashedFileName: string, directory: string) {
+ const arrayBuffer = await file.arrayBuffer()
+ const buffer = Buffer.from(arrayBuffer)
+
+ const filePath = path.join(directory, hashedFileName)
+
+ // 만약 기존 파일에 추가가 아니라 새 파일 생성이라면 writeFile 사용
+ await fs.writeFile(filePath, buffer)
+} \ No newline at end of file