Explorar el Código

:construction: Finished saving responses from survey to database

juan_spike
tomit4 hace 3 años
padre
commit
287896b9be

+ 9
- 11
backend/lib/routes/profile/insert.js Ver fichero

@@ -9,13 +9,13 @@ const params = require('../../schemas/params')
9 9
 const pluginConfig = {
10 10
     handlerType: 'profile',
11 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 17
 const responseSchemas = {
18
-    response: surveyResponseSchema.list,
18
+    response: surveyResponseSchema.single,
19 19
     error: errorSchema.single,
20 20
 }
21 21
 
@@ -34,33 +34,31 @@ const validators = {
34 34
 
35 35
 module.exports = {
36 36
     method: 'POST',
37
-    path: '/{profile_id}/insert/{response_id?}',
37
+    path: '/{profile_id}/insert/{response_key_id?}',
38 38
     options: {
39 39
         ...pluginConfig.docs,
40 40
         tags: ['api'],
41 41
         /** Protect this route with authentication? */
42 42
         auth: false,
43
+        cors: true,
43 44
 
44 45
         handler: async function (request, h) {
45 46
             const { profileService } = request.services()
46
-            const profileId = request.params.profile_id
47
-
48 47
             /** Grab payload info */
49 48
             const res = request.payload
50
-            console.log('res :=>', res)
51 49
 
52 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 57
                 return h
60 58
                     .response({
61 59
                         ok: true,
62 60
                         handler: pluginConfig.handlerType,
63
-                        data: allResponses,
61
+                        data: insertedResponse,
64 62
                     })
65 63
                     .code(200)
66 64
             } catch (err) {

+ 30
- 33
backend/lib/services/profile/index.js Ver fichero

@@ -4,6 +4,7 @@ const config = require('../../../db/data-generator/config.json')
4 4
 const profiler = require('./profiler')
5 5
 const scoring = require('./scorer')
6 6
 const zipcoder = require('./zipcoder')
7
+const { response } = require('@hapi/hapi/lib/validation')
7 8
 
8 9
 module.exports = class ProfileService extends Schmervice.Service {
9 10
     constructor(...args) {
@@ -50,6 +51,25 @@ module.exports = class ProfileService extends Schmervice.Service {
50 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 73
     async getProfile(profileId) {
54 74
         const { Profile } = this.server.models()
55 75
         await this._setTagLookup()
@@ -124,21 +144,7 @@ module.exports = class ProfileService extends Schmervice.Service {
124 144
             user_id: userId,
125 145
         })
126 146
         for (const responseToSave of responses) {
127
-            /**
128
-             * Convert indexes to actual score values
129
-             * Using using the input and converting to index
130
-             * of the generated possible prescore array in config
131
-             * DUPLICATE:See saveResponseForProfile() line 343
132
-             */
133
-            let convertedResponse = responseToSave
134
-            if (scoring._isScorableResponse(responseToSave.response_key_id)) {
135
-                // Convert -3 to 0, 0 to 3, 3 to 6
136
-                const offset = (config.scoreVals.length - 1) / 2
137
-                const indexFromInput = parseInt(responseToSave.val) + offset
138
-                convertedResponse.val =
139
-                    config.scoreVals[indexFromInput].toString()
140
-            }
141
-
147
+            const convertedResponse = this._convertResponse(responseToSave)
142 148
             const responseInfo = {
143 149
                 profile_id: profile.id,
144 150
                 response_key_id: convertedResponse.response_key_id,
@@ -177,6 +183,14 @@ module.exports = class ProfileService extends Schmervice.Service {
177 183
         })
178 184
     }
179 185
 
186
+    async insertSingleResponseForProfile(responseToSave) {
187
+        const { Response } = this.server.models()
188
+        const convertedResponse = this._convertResponse(responseToSave)
189
+        const savedResponse = await Response.query().insert(convertedResponse)
190
+        delete savedResponse.id
191
+        return savedResponse
192
+    }
193
+
180 194
     /** Add response
181 195
      * @param {Object} response to save
182 196
      * @returns {null} updated responses
@@ -203,24 +217,7 @@ module.exports = class ProfileService extends Schmervice.Service {
203 217
                 .delete()
204 218
                 .whereIn('response_key_id', alreadyAnswered)
205 219
         }
206
-
207
-        /**
208
-         * Convert indexes to actual score values
209
-         * Using using the input and converting to index
210
-         * of the generated possible prescore array in config
211
-         */
212
-        let convertedResponse = responseToSave
213
-        if (scoring._isScorableResponse(responseToSave.response_key_id)) {
214
-            // Convert -3 to 0, 0 to 3, 3 to 6
215
-            const offset = (config.scoreVals.length - 1) / 2
216
-            const scoreFromInput = parseInt(responseToSave.val) + offset
217
-            const scoreFromConfig = config.scoreVals.indexOf(scoreFromInput)
218
-            if (scoreFromConfig < 0) {
219
-                console.error('score not found in possible config responses')
220
-            }
221
-            convertedResponse.val = scoreFromConfig.toString()
222
-        }
223
-
220
+        const convertedResponse = this._convertResponse(responseToSave)
224 221
         await Response.query().insert(convertedResponse)
225 222
         return allResponses
226 223
     }

+ 7
- 9
frontend/src/services/survey.service.js Ver fichero

@@ -22,20 +22,18 @@ const fetchQuestions = async () => {
22 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 28
         // POST
30 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 32
                 profile_id: profileId,
34
-                reponse_key_id: keyId,
33
+                response_key_id: keyId,
35 34
                 val: val,
36 35
             }
37
-        ])
38
-    })
36
+        )
39 37
 }
40 38
 
41 39
 // similar to this
@@ -69,7 +67,7 @@ const fetchResponsesByProfileId = async profileId => {
69 67
 
70 68
 export {
71 69
     fetchQuestions,
72
-    insertNewSurveyResponses,
70
+    insertNewSurveyResponse,
73 71
     updateSurveyByProfileId,
74 72
     scoreSurveyByProfileId,
75 73
     fetchResponsesByProfileId,

+ 3
- 3
frontend/src/utils/survey.js Ver fichero

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

+ 1
- 1
frontend/src/views/OnboardingView.vue Ver fichero

@@ -96,7 +96,7 @@ export default {
96 96
                 // save endpoint here
97 97
                 // start with utils/surve.js
98 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 102
                 // creates a user in db as long as name, email, and seeking are defined

Loading…
Cancelar
Guardar