summaryrefslogtreecommitdiff
path: root/lib/storage.ts
blob: ead937aa3e14599ba3cf242111eac3f88f30f701 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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)
}