@@ -2,15 +2,14 @@ import { NextRequest, NextResponse } from 'next/server';
2
2
import fs from 'fs/promises' ;
3
3
import path from 'path' ;
4
4
import { CryptoService } from '@/server/CryptoService' ;
5
+ import pool from '@/server/db' ;
5
6
6
7
export async function POST ( req : NextRequest ) {
7
8
try {
8
- // Ensure the request has a body
9
9
if ( ! req . body ) {
10
10
return NextResponse . json ( { error : 'Missing body' } , { status : 400 } ) ;
11
11
}
12
12
13
- // Parse the incoming request body
14
13
const { photoUrl, encryptedUserId } = await req . json ( ) ;
15
14
16
15
if ( ! photoUrl || ! encryptedUserId ) {
@@ -20,7 +19,6 @@ export async function POST(req: NextRequest) {
20
19
) ;
21
20
}
22
21
23
- // Decrypt user ID from encryptedUserId (reuse your existing CryptoService)
24
22
const cryptedUserId = encryptedUserId . split ( '.' ) ;
25
23
const cryptedKeyUserId = { encryptedText : cryptedUserId [ 0 ] , iv : cryptedUserId [ 1 ] } ;
26
24
@@ -31,11 +29,9 @@ export async function POST(req: NextRequest) {
31
29
return NextResponse . json ( { error : 'Invalid User ID' } , { status : 400 } ) ;
32
30
}
33
31
34
- // Create user-specific directory for downloaded images
35
32
const downloadPath = path . join ( process . cwd ( ) , 'public' , 'profileImages' , String ( userId ) ) ;
36
33
await fs . mkdir ( downloadPath , { recursive : true } ) ;
37
34
38
- // Fetch the photo data from the given URL
39
35
const response = await fetch ( photoUrl ) ;
40
36
if ( ! response . ok ) {
41
37
return NextResponse . json (
@@ -44,18 +40,20 @@ export async function POST(req: NextRequest) {
44
40
) ;
45
41
}
46
42
47
- // Extract file type and name from headers or URL
48
43
const contentType = response . headers . get ( 'Content-Type' ) || 'image/jpeg' ;
49
44
const fileExtension = contentType . split ( '/' ) [ 1 ] || 'jpg' ;
50
45
const now = Date . now ( ) ;
51
46
const fileName = `${ now } _google_photo.${ fileExtension } ` ;
52
47
const filePath = path . join ( downloadPath , fileName ) ;
53
48
54
- // Write the photo data to the file system
55
49
const buffer = await response . arrayBuffer ( ) ;
56
50
await fs . writeFile ( filePath , Buffer . from ( buffer ) ) ;
57
51
58
- // Return success response with the saved file path
52
+ await pool . query (
53
+ 'UPDATE users SET nb_photos = nb_photos + 1 WHERE id = $1' ,
54
+ [ userId ]
55
+ ) ;
56
+
59
57
return NextResponse . json ( {
60
58
message : 'Photo downloaded and saved successfully!' ,
61
59
path : `/profileImages/${ userId } /${ fileName } ` ,
0 commit comments