Pārlūkot izejas kodu

:construction: Finished saving responses from survey to database

tags/0.0.3^2
tomit4 3 gadus atpakaļ
vecāks
revīzija
62d77d27dd

+ 9
- 11
backend/lib/routes/profile/insert.js Parādīt failu

9
 const pluginConfig = {
9
 const pluginConfig = {
10
     handlerType: 'profile',
10
     handlerType: 'profile',
11
     docs: {
11
     docs: {
12
-        description: 'Insert profile',
13
-        notes: 'Insert new profile responses',
12
+        description: 'Insert responses',
13
+        notes: 'Insert new responses',
14
     },
14
     },
15
 }
15
 }
16
 
16
 
17
 const responseSchemas = {
17
 const responseSchemas = {
18
-    response: surveyResponseSchema.list,
18
+    response: surveyResponseSchema.single,
19
     error: errorSchema.single,
19
     error: errorSchema.single,
20
 }
20
 }
21
 
21
 
34
 
34
 
35
 module.exports = {
35
 module.exports = {
36
     method: 'POST',
36
     method: 'POST',
37
-    path: '/{profile_id}/insert/{response_id?}',
37
+    path: '/{profile_id}/insert/{response_key_id?}',
38
     options: {
38
     options: {
39
         ...pluginConfig.docs,
39
         ...pluginConfig.docs,
40
         tags: ['api'],
40
         tags: ['api'],
41
         /** Protect this route with authentication? */
41
         /** Protect this route with authentication? */
42
         auth: false,
42
         auth: false,
43
+        cors: true,
43
 
44
 
44
         handler: async function (request, h) {
45
         handler: async function (request, h) {
45
             const { profileService } = request.services()
46
             const { profileService } = request.services()
46
-            const profileId = request.params.profile_id
47
-
48
             /** Grab payload info */
47
             /** Grab payload info */
49
             const res = request.payload
48
             const res = request.payload
50
-            console.log('res :=>', res)
51
 
49
 
52
             try {
50
             try {
53
-                const allResponses = profileService.saveResponseForProfile(profileId, res)
51
+                const insertedResponse = await profileService.insertSingleResponseForProfile(res)
54
 
52
 
55
-                if (!allResponses) {
56
-                    throw new RangeError('Response not inserted')
53
+                if (!insertedResponse) {
54
+                    throw new Error('Response not inserted')
57
                 }
55
                 }
58
 
56
 
59
                 return h
57
                 return h
60
                     .response({
58
                     .response({
61
                         ok: true,
59
                         ok: true,
62
                         handler: pluginConfig.handlerType,
60
                         handler: pluginConfig.handlerType,
63
-                        data: allResponses,
61
+                        data: insertedResponse,
64
                     })
62
                     })
65
                     .code(200)
63
                     .code(200)
66
             } catch (err) {
64
             } catch (err) {

+ 30
- 33
backend/lib/services/profile/index.js Parādīt failu

4
 const profiler = require('./profiler')
4
 const profiler = require('./profiler')
5
 const scoring = require('./scorer')
5
 const scoring = require('./scorer')
6
 const zipcoder = require('./zipcoder')
6
 const zipcoder = require('./zipcoder')
7
+const { response } = require('@hapi/hapi/lib/validation')
7
 
8
 
8
 module.exports = class ProfileService extends Schmervice.Service {
9
 module.exports = class ProfileService extends Schmervice.Service {
9
     constructor(...args) {
10
     constructor(...args) {
50
         return [...new Set(profileIdsToGrab)]
51
         return [...new Set(profileIdsToGrab)]
51
     }
52
     }
52
 
53
 
54
+    /**
55
+     * Convert indexes to actual score values
56
+     * Using using the input and converting to index
57
+     * of the generated possible prescore array in config
58
+     */
59
+    _convertResponse(responseToSave) {
60
+        if (scoring._isScorableResponse(responseToSave.response_key_id)) {
61
+            // Convert -3 to 0, 0 to 3, 3 to 6
62
+            const offset = (config.scoreVals.length - 1) / 2
63
+            const scoreFromInput = parseInt(responseToSave.val) + offset
64
+            const scoreFromConfig = config.scoreVals.indexOf(scoreFromInput)
65
+            if (scoreFromConfig < 0) {
66
+                console.error('score not found in possible config responses')
67
+            }
68
+            responseToSave.val = scoreFromConfig.toString()
69
+        }
70
+        return responseToSave
71
+    }
72
+
53
     async getProfile(profileId) {
73
     async getProfile(profileId) {
54
         const { Profile } = this.server.models()
74
         const { Profile } = this.server.models()
55
         await this._setTagLookup()
75
         await this._setTagLookup()
120
             user_id: userId,
140
             user_id: userId,
121
         })
141
         })
122
         for (const responseToSave of responses) {
142
         for (const responseToSave of responses) {
123
-            /**
124
-             * Convert indexes to actual score values
125
-             * Using using the input and converting to index
126
-             * of the generated possible prescore array in config
127
-             * DUPLICATE:See saveResponseForProfile() line 343
128
-             */
129
-            let convertedResponse = responseToSave
130
-            if (scoring._isScorableResponse(responseToSave.response_key_id)) {
131
-                // Convert -3 to 0, 0 to 3, 3 to 6
132
-                const offset = (config.scoreVals.length - 1) / 2
133
-                const indexFromInput = parseInt(responseToSave.val) + offset
134
-                convertedResponse.val =
135
-                    config.scoreVals[indexFromInput].toString()
136
-            }
137
-
143
+            const convertedResponse = this._convertResponse(responseToSave)
138
             const responseInfo = {
144
             const responseInfo = {
139
                 profile_id: profile.id,
145
                 profile_id: profile.id,
140
                 response_key_id: convertedResponse.response_key_id,
146
                 response_key_id: convertedResponse.response_key_id,
173
         })
179
         })
174
     }
180
     }
175
 
181
 
182
+    async insertSingleResponseForProfile(responseToSave) {
183
+        const { Response } = this.server.models()
184
+        const convertedResponse = this._convertResponse(responseToSave)
185
+        const savedResponse = await Response.query().insert(convertedResponse)
186
+        delete savedResponse.id
187
+        return savedResponse
188
+    }
189
+
176
     /** Add response
190
     /** Add response
177
      * @param {Object} response to save
191
      * @param {Object} response to save
178
      * @returns {null} updated responses
192
      * @returns {null} updated responses
199
                 .delete()
213
                 .delete()
200
                 .whereIn('response_key_id', alreadyAnswered)
214
                 .whereIn('response_key_id', alreadyAnswered)
201
         }
215
         }
202
-
203
-        /**
204
-         * Convert indexes to actual score values
205
-         * Using using the input and converting to index
206
-         * of the generated possible prescore array in config
207
-         */
208
-        let convertedResponse = responseToSave
209
-        if (scoring._isScorableResponse(responseToSave.response_key_id)) {
210
-            // Convert -3 to 0, 0 to 3, 3 to 6
211
-            const offset = (config.scoreVals.length - 1) / 2
212
-            const scoreFromInput = parseInt(responseToSave.val) + offset
213
-            const scoreFromConfig = config.scoreVals.indexOf(scoreFromInput)
214
-            if (scoreFromConfig < 0) {
215
-                console.error('score not found in possible config responses')
216
-            }
217
-            convertedResponse.val = scoreFromConfig.toString()
218
-        }
219
-
216
+        const convertedResponse = this._convertResponse(responseToSave)
220
         await Response.query().insert(convertedResponse)
217
         await Response.query().insert(convertedResponse)
221
         return allResponses
218
         return allResponses
222
     }
219
     }

+ 7
- 9
frontend/src/services/survey.service.js Parādīt failu

22
     return withResponses
22
     return withResponses
23
 }
23
 }
24
 
24
 
25
-const insertNewSurveyResponses = async (surveyResponses, profileId) => {
26
-    surveyResponses.forEach(responseKeyIdwithVal => {
27
-        const keyId = responseKeyIdwithVal.response_key_id
28
-        const val = responseKeyIdwithVal.val
25
+const insertNewSurveyResponse = async (surveyResponse, profileId) => {
26
+        const keyId = surveyResponse.response_key_id
27
+        const val = surveyResponse.val
29
         // POST
28
         // POST
30
         // TODO: create this route on the backend
29
         // TODO: create this route on the backend
31
-        db.post(`/profile/${profileId}/insert/${keyId}`, [
30
+        db.post(`/profile/${profileId}/insert/${keyId}`,
32
             {
31
             {
33
                 profile_id: profileId,
32
                 profile_id: profileId,
34
-                reponse_key_id: keyId,
33
+                response_key_id: keyId,
35
                 val: val,
34
                 val: val,
36
             }
35
             }
37
-        ])
38
-    })
36
+        )
39
 }
37
 }
40
 
38
 
41
 // similar to this
39
 // similar to this
69
 
67
 
70
 export {
68
 export {
71
     fetchQuestions,
69
     fetchQuestions,
72
-    insertNewSurveyResponses,
70
+    insertNewSurveyResponse,
73
     updateSurveyByProfileId,
71
     updateSurveyByProfileId,
74
     scoreSurveyByProfileId,
72
     scoreSurveyByProfileId,
75
     fetchResponsesByProfileId,
73
     fetchResponsesByProfileId,

+ 3
- 3
frontend/src/utils/survey.js Parādīt failu

1
 import { Survey } from '../entities/index.js'
1
 import { Survey } from '../entities/index.js'
2
-import { fetchQuestions, insertNewSurveyResponses } from '../services/index.js'
2
+import { fetchQuestions, insertNewSurveyResponse } from '../services/index.js'
3
 import { splash, possible, surveyStages, allSteps } from './lang.js'
3
 import { splash, possible, surveyStages, allSteps } from './lang.js'
4
 
4
 
5
 class SurveyFactory {
5
 class SurveyFactory {
83
             console.error(err)
83
             console.error(err)
84
         }
84
         }
85
     }
85
     }
86
-    async addNewSurveyAnswers(responses, profileId) {
86
+    async addNewSurveyAnswer(responses, profileId) {
87
         try {
87
         try {
88
-            this.responsesFromDb = await insertNewSurveyResponses(responses, profileId)
88
+            this.responsesFromDb = await insertNewSurveyResponse(responses, profileId)
89
             return this.responsesFromDb
89
             return this.responsesFromDb
90
         }
90
         }
91
         catch (err) {
91
         catch (err) {

+ 1
- 1
frontend/src/views/OnboardingView.vue Parādīt failu

96
                 // save endpoint here
96
                 // save endpoint here
97
                 // start with utils/surve.js
97
                 // start with utils/surve.js
98
                 if (this.currentProfileId) {
98
                 if (this.currentProfileId) {
99
-                    surveyFactory.addNewSurveyAnswers(this.responses, this.currentProfileId)
99
+                    surveyFactory.addNewSurveyAnswer(this.responses[this.responses.length - 1], this.currentProfileId)
100
                 }
100
                 }
101
 
101
 
102
                 // creates a user in db as long as name, email, and seeking are defined
102
                 // creates a user in db as long as name, email, and seeking are defined

Notiek ielāde…
Atcelt
Saglabāt