11"use server" ;
2-
32import { writeClient } from "@/lib/sanity/writeClient" ;
43
54export async function submitApplication ( formData ) {
65 try {
76 const name = formData . get ( "name" ) ;
87 const email = formData . get ( "email" ) ;
98 const positionId = formData . get ( "positionId" ) ;
9+ const questionKeysRaw = formData . get ( "questionKeys" ) ;
10+
11+ if ( ! questionKeysRaw ) {
12+ throw new Error ( "Missing form structure data." ) ;
13+ }
1014
11- const questionKeys = JSON . parse ( formData . get ( "questionKeys" ) ) ;
15+ const questionKeys = JSON . parse ( questionKeysRaw ) ;
16+ const answers = [ ] ;
1217
13- const answers = await Promise . all (
14- questionKeys . map ( async ( q ) => {
15- const fieldData = {
16- _key : Math . random ( ) . toString ( 36 ) . substring ( 2 ) ,
17- question : q . text ,
18- } ;
18+ for ( const q of questionKeys ) {
19+ const fieldData = {
20+ _key : Math . random ( ) . toString ( 36 ) . substring ( 2 , 11 ) ,
21+ question : q . text ,
22+ } ;
1923
20- const value = formData . get ( q . text ) ;
24+ const value = formData . get ( q . text ) ;
2125
22- if ( q . type === "image upload" ) {
23- if ( value && value instanceof File && value . size > 0 ) {
26+ if ( q . type === "image upload" ) {
27+ if ( value && value instanceof File && value . size > 0 ) {
28+ try {
2429 const asset = await writeClient . assets . upload ( "image" , value , {
2530 filename : value . name ,
31+ contentType : value . type ,
2632 } ) ;
33+
2734 fieldData . imageAnswer = {
2835 _type : "image" ,
2936 asset : {
3037 _type : "reference" ,
3138 _ref : asset . _id ,
3239 } ,
3340 } ;
41+ } catch ( uploadError ) {
42+ console . error (
43+ `Image upload failed for question: ${ q . text } ` ,
44+ uploadError ,
45+ ) ;
46+ throw new Error (
47+ `Failed to upload image for "${ q . text } ". Please try a smaller file.` ,
48+ ) ;
3449 }
35- } else {
36- fieldData . textAnswer = value ;
3750 }
51+ } else {
52+ fieldData . textAnswer = value ?. toString ( ) || "" ;
53+ }
3854
39- return fieldData ;
40- } ) ,
41- ) ;
55+ answers . push ( fieldData ) ;
56+ }
4257
4358 await writeClient . create ( {
4459 _type : "application" ,
@@ -54,11 +69,13 @@ export async function submitApplication(formData) {
5469
5570 return { success : true } ;
5671 } catch ( error ) {
57- console . error ( "Submission Error:" , error ) ;
72+ console . error ( "CRITICAL SUBMISSION ERROR:" , error ) ;
73+
5874 return {
5975 success : false ,
6076 error :
61- error . message || "An error occurred while submitting your application." ,
77+ error . message ||
78+ "A server error occurred. Please check your connection and try again." ,
6279 } ;
6380 }
6481}
0 commit comments