@@ -5,6 +5,9 @@ import { stat, writeFile } from "fs/promises";
55import { connectToDatabase } from "../../../lib/mongodb" ;
66import { Recipe } from "../../../models" ;
77import mime from 'mime' ;
8+ import { existsSync } from "fs" ;
9+ import fs from "fs/promises" ;
10+ import path from "path" ;
811
912connectToDatabase ( ) ;
1013
@@ -25,33 +28,36 @@ export async function GET() {
2528export async function POST ( req : Request ) {
2629 const data = await req . formData ( ) ;
2730 const file : File | null = data . get ( 'photo' ) as unknown as File ;
28- const bytes = await file . arrayBuffer ( ) ;
29-
30- const buffer = Buffer . from ( await file . arrayBuffer ( ) ) ;
31- const relativeUploadDir = `/uploads/recipes` ;
32- const uploadDir = join ( process . cwd ( ) , "public" , relativeUploadDir ) ;
33- await stat ( uploadDir ) ;
34-
31+
32+ const fileArrayBuffer = await file . arrayBuffer ( ) ;
33+ const destinationDirPath = path . join ( process . cwd ( ) , process . env . STORE_PATH ! ) ;
34+
35+ if ( ! existsSync ( destinationDirPath ) ) {
36+ await fs . mkdir ( destinationDirPath , { recursive : true } ) ;
37+ }
38+
39+ let name = data . get ( 'name' )
40+ var fileExtension = file . name . split ( '.' ) . pop ( ) ;
41+ let filename = `${ name } .${ fileExtension } `
42+ while ( existsSync ( path . join ( destinationDirPath , filename ) ) ) {
43+ filename = `(1)` + filename ;
44+ }
45+ await fs . writeFile (
46+ path . join ( destinationDirPath , filename ) ,
47+ Buffer . from ( fileArrayBuffer )
48+ ) ;
3549 try {
36- const uniqueSuffix = `${ Date . now ( ) } -${ Math . round ( Math . random ( ) * 1e9 ) } ` ;
37- const filename = `${ file . name . replace (
38- / \. [ ^ / . ] + $ / ,
39- ""
40- ) } -${ uniqueSuffix } .${ mime . getExtension ( file . type ) } `;
41- await writeFile ( `${ uploadDir } /${ filename } ` , buffer ) ;
42-
4350 const newRecipe = {
4451 name : data . get ( 'name' ) ,
4552 description : data . get ( 'description' ) ,
4653 ingredients : JSON . parse ( data . get ( 'ingredients' ) as string ) ,
4754 steps : data . get ( 'steps' ) ,
48- photo : `${ relativeUploadDir } /${ filename } `
55+ photo : `/api/file /${ filename } `
4956 }
5057
51- console . log ( "recipe" , newRecipe )
5258 const recipe = new Recipe ( newRecipe ) ;
5359 const save = await recipe . save ( ) ;
54- return NextResponse . json ( { status : 200 , data : save } ) ;
60+ return NextResponse . json ( { status : 200 , data : save } ) ;
5561 } catch ( error ) {
5662 console . log ( error ) ;
5763 return NextResponse . json ( 'error' , {
0 commit comments