Ver código fonte

:construction: Finished saving responses from survey to database

tags/0.0.3^2
tomit4 3 anos atrás
pai
commit
62d77d27dd

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

@@ -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 arquivo

@@ -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()
@@ -120,21 +140,7 @@ module.exports = class ProfileService extends Schmervice.Service {
120 140
             user_id: userId,
121 141
         })
122 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 144
             const responseInfo = {
139 145
                 profile_id: profile.id,
140 146
                 response_key_id: convertedResponse.response_key_id,
@@ -173,6 +179,14 @@ module.exports = class ProfileService extends Schmervice.Service {
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 190
     /** Add response
177 191
      * @param {Object} response to save
178 192
      * @returns {null} updated responses
@@ -199,24 +213,7 @@ module.exports = class ProfileService extends Schmervice.Service {
199 213
                 .delete()
200 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 217
         await Response.query().insert(convertedResponse)
221 218
         return allResponses
222 219
     }

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

@@ -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 arquivo

@@ -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 arquivo

@@ -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

Carregando…
Cancelar
Salvar