@@ -96,6 +96,62 @@ export const postAnswer = async (
9696 ...shownAnswer } ;
9797} ;
9898
99+ export const postFileAnswer = async (
100+ { accessToken, group, bookId, questionId, addFiles, removeFiles} : {
101+ accessToken : string ;
102+ group : string | null ;
103+ bookId : number ;
104+ questionId : string ;
105+ addFiles : string [ ] ;
106+ removeFiles : string [ ] | boolean ;
107+ } ) : Promise < string | null > => {
108+ const userId = await getUserId ( accessToken ) ;
109+ const groupId = group ? ( await db . get (
110+ `SELECT id FROM groups WHERE name = ?` ,
111+ [ group ]
112+ ) ) ?. id : null ;
113+
114+ const question = await db . get ( `
115+ SELECT id, type FROM questions q
116+ JOIN books_chapters bc ON q.chapterId = bc.chapterId
117+ WHERE questionId = ? AND bc.bookId = ?
118+ ` , [ questionId , bookId ]
119+ ) ;
120+ if ( ! question ) {
121+ return "Question id and book id don't match" ;
122+ }
123+ if ( ! question . type . startsWith ( "upload" ) ) {
124+ return "Question is not of upload type" ;
125+ }
126+ const qId = question . id ;
127+ try {
128+ await db . run ( "BEGIN IMMEDIATE" ) ;
129+ const prevFiles = removeFiles === true ? [ ] :
130+ ( ( await db . get ( `
131+ SELECT answer FROM answers
132+ WHERE userId = ? AND bookId = ? AND groupId IS ? AND questionId = ?
133+ ORDER BY createdAt DESC
134+ LIMIT 1
135+ ` , [ userId , bookId , groupId , qId ]
136+ ) ) as { answer : string } | undefined ) ?. answer
137+ . split ( ":" )
138+ . filter ( ( f ) => f && ! addFiles . includes ( f ) && ( ! removeFiles || ! removeFiles . includes ( f ) ) )
139+ || [ ] ;
140+ const newFiles = [ ...prevFiles , ...addFiles ] . join ( ":" ) ;
141+ await db . run (
142+ `INSERT INTO answers (userId, bookId, groupId, questionId, answer)
143+ VALUES (?, ?, ?, ?, ?)` ,
144+ [ userId , bookId , groupId , qId , newFiles ]
145+ ) ;
146+ await db . run ( "COMMIT" ) ;
147+ }
148+ catch ( e ) {
149+ await db . run ( "ROLLBACK" ) ;
150+ return "Database error" ;
151+ }
152+ return null ;
153+ } ;
154+
99155export type CorrectAnswers = { questionId : string , answer : string } [ ] ;
100156
101157export const getAnswers = async ( { accessToken, bookId, group } : {
0 commit comments