Просмотр исходного кода

save survey answers first pass

tags/0.0.1
diaseu 4 лет назад
Родитель
Сommit
719328a5c1

+ 21
- 3
frontend/src/components/form.vue Просмотреть файл

@@ -57,6 +57,7 @@
57 57
 import Joi from 'joi'
58 58
 import { validatorMapping, makeKebob } from '@/utils'
59 59
 import { defineProps, reactive, ref } from 'vue'
60
+import { saveSurveyByProfileID } from '../services/survey.service'
60 61
 
61 62
 const slidevalue = ref('0')
62 63
 
@@ -109,15 +110,32 @@ const isValid = step => {
109 110
 const next = e => {
110 111
     const validity = isValid(state.step - 1)
111 112
     if (validity.error) return console.error(validity.error)
112
-    // TODO: make steps work, 
113
-    // console.log('next', )
113
+    // TODO: make steps work,
114 114
     // Save or next
115 115
     if (state.step === props.form.length) {
116 116
         // TODO: call survey service
117 117
         // TODO: in the survey service, create a save function
118 118
         // call service from here, pass it profile id as argument
119 119
         // profileId = answers['what-is-your-user-id']
120
-        alert('saved...')
120
+        const questiontoResponseKeyId = {}
121
+        props.form.forEach(step => {
122
+            step.forEach(prompt => {
123
+                questiontoResponseKeyId[makeKebob(prompt.question)] = prompt.id
124
+            })
125
+        })
126
+        const idWithResponseVal = []
127
+        Object.keys(answers).forEach(answerKey => {
128
+            idWithResponseVal.push({
129
+                response_key_id: questiontoResponseKeyId[answerKey],
130
+                val: answers[answerKey],
131
+            })
132
+        })
133
+        // Remove 1st answer from idWithResponseVal and use it for profileId
134
+        // Bc we don't want to pass the 1st question to backend & we want profileId
135
+        // Necessary atm bc we manually added question in Survey class (entity)
136
+        const profileId = idWithResponseVal.shift().val
137
+
138
+        saveSurveyByProfileID(idWithResponseVal, profileId)
121 139
         resetAnswers()
122 140
         state.step = 1
123 141
     } else if (state.step < props.form.length) {

+ 1
- 1
frontend/src/entities/survey/survey.js Просмотреть файл

@@ -14,7 +14,7 @@ class Survey extends _baseRecord {
14 14
                 {
15 15
                     id: 0,
16 16
                     type: 'input-string',
17
-                    question: 'what is your user id',
17
+                    question: 'what is your profile id',
18 18
                     responses: null,
19 19
                     description: null,
20 20
                     category: null,

+ 81
- 64
frontend/src/services/survey.service.js Просмотреть файл

@@ -9,62 +9,64 @@ import { Survey } from '../entities/survey'
9 9
  * @returns {array} instantiated Profile objects (see: /entites/profile)
10 10
  */
11 11
 const fetchSurveyByProfileId = async profileId => {
12
-    const myquestions = await db.get(`/survey/questions`)
13
-    // const myquestions = [
14
-    //     [
15
-    //         {
16
-    //             id: 1,
17
-    //             type: 'input-string',
18
-    //             question: 'whats your favorite color',
19
-    //             responses: null,
20
-    //         },
21
-    //     ],
22
-    // [
23
-    //     {
24
-    //     "response_key_id": 1,
25
-    //     "response_key_category": "grit",
26
-    //     "response_key_prompt": "what is your name",
27
-    //     "response_key_description": null
28
-    //     },
29
-    // ],
30
-    //     [
31
-    //         {
32
-    //             id: 2,
33
-    //             type: 'tag-cloud',
34
-    //             question: 'whats your favorite number',
35
-    //             responses: ['1', '2', '3'],
36
-    //         },
37
-    //     ],
38
-    //     [
39
-    //         {
40
-    //             id: 3,
41
-    //             type: 'checklist',
42
-    //             question: 'what is your current status',
43
-    //             responses: ['employed', 'unemployed', 'degenerate', 'alien'],
44
-    //         },
45
-    //     ],
46
-    //     [
47
-    //         {
48
-    //             id: 4,
49
-    //             type: 'slide',
50
-    //             question: 'choose a num',
51
-    //             responses: null,
52
-    //         },
53
-    //     ],
54
-    //     [
55
-    //         {
56
-    //             id: 5,
57
-    //             type: 'checklist',
58
-    //             question: 'pick a status',
59
-    //             responses: ['cry', 'sad', 'mad', 'numb'],
60
-    //         },
61
-    //     ],
62
-    // ]
63
-    const allsteps = { 'step-1': [], 'step-2': [], 'step-3': [], 'step-4': [] }
64
-    let counter = 0
12
+    // const myquestions = await db.get(`/survey/questions`)
13
+    const myquestions = [
14
+        {
15
+            response_key_id: 1,
16
+            response_key_prompt: 'whats your favorite color',
17
+            response_key_description: 'color description',
18
+            response_key_category: 'category',
19
+        },
20
+        {
21
+            response_key_id: 2,
22
+            response_key_prompt: 'whats your favorite food',
23
+            response_key_description: 'food description',
24
+            response_key_category: 'category',
25
+        },
26
+        {
27
+            response_key_id: 3,
28
+            response_key_prompt: 'whats your favorite animal',
29
+            response_key_description: 'animal description',
30
+            response_key_category: 'category',
31
+        },
32
+        {
33
+            response_key_id: 4,
34
+            response_key_prompt: 'whats your favorite tree',
35
+            response_key_description: 'tree description',
36
+            response_key_category: 'category',
37
+        },
38
+        {
39
+            response_key_id: 5,
40
+            response_key_prompt: 'whats your favorite plant',
41
+            response_key_description: 'plant description',
42
+            response_key_category: 'category',
43
+        },
44
+        {
45
+            response_key_id: 6,
46
+            response_key_prompt: 'whats your favorite frog',
47
+            response_key_description: 'frog description',
48
+            response_key_category: 'category',
49
+        },
50
+        {
51
+            response_key_id: 7,
52
+            response_key_prompt: 'what is your zipcode',
53
+            response_key_description: 'zipcode description',
54
+            response_key_category: 'category',
55
+        },
56
+    ]
57
+    const allsteps = { }
58
+    const questionsPerStep = 3
59
+    const stepsNeeded = Math.ceil(myquestions.length / questionsPerStep)
65 60
 
61
+    // Create the steps needed inside allsteps
62
+    for (let i = 1; i <= stepsNeeded; i++) {
63
+        allsteps[`step-${i}`] = []
64
+    }
65
+
66
+    // Add the questions into each step, dividing into questionsPerStep
66 67
     for (let i = 0; i < myquestions.length; i++) {
67 68
         const question = myquestions[i]
69
+        // Reformats myquestions into the format we want
68 70
         const reformatted = {
69 71
             id: question.response_key_id,
70 72
             type: 'input-string',
@@ -73,22 +75,37 @@ const fetchSurveyByProfileId = async profileId => {
73 75
             description: question.response_key_description,
74 76
             category: question.response_key_category,
75 77
         }
76
-        counter = counter + 1
77
-        // TODO: check for step array before pushing
78
-        if (i < 4 * counter && i >= 4 * (counter - 1)) {
79
-            allsteps[`step-${counter}`].push(reformatted)
78
+        for (let n = 1; n <= stepsNeeded; n++) {
79
+            if (i >=questionsPerStep*(n-1) && i < questionsPerStep*n) {
80
+                allsteps[`step-${n}`].push(reformatted)
81
+            }
80 82
         }
81 83
     }
82 84
     const mysurvey = new Survey(allsteps)
83
-
84 85
     return mysurvey
85 86
 }
86 87
 
87
-// TODO: saveSurveyByProfileID - needs await, db.post
88
-const saveSurveyByProfileID = async profileID => {
89
-    const myresponses = await db.post(`/${profileId}/respond`)
90
-    
91
-    
88
+// TODO: separate to newSurvey vs updateSurvey
89
+const saveSurveyByProfileID = async (surveyResponses, profileId) => {
90
+    surveyResponses.forEach((responseKeyIdwithVal) => {
91
+        const keyId = responseKeyIdwithVal.response_key_id
92
+        const val = responseKeyIdwithVal.val
93
+        console.log('posting this', `/${profileId}/respond?response_key_id=${keyId}&val=${val}`)
94
+        // POST 
95
+        // const myresponses = db.post(`/${profileId}/respond?response_key_id=${keyId}&val=${val}`)
96
+        // PATCH
97
+        // const myresponses = db.patch(`/profile/${profileId}/update/${keyId}`, 
98
+        // [
99
+        //     {
100
+        //         response_id: 2,
101
+        //         profile_id: profileId,
102
+        //         response_key_id: keyId,
103
+        //         val: val,
104
+        //     },
105
+        // ]
106
+        // )
107
+        // return myresponses
108
+    })
92 109
 }
93 110
 
94
-export { fetchSurveyByProfileId }
111
+export { fetchSurveyByProfileId, saveSurveyByProfileID }

+ 13
- 10
frontend/src/utils/db.js Просмотреть файл

@@ -52,19 +52,22 @@ class Connector {
52 52
             console.error(error)
53 53
         }
54 54
     }
55
-    async put(endpoint, entry) {
56
-        /** from ajv schema validation */
57
-        if (entry.isValid()) {
58
-            try {
59
-            } catch (err) {
60
-                /** valid data but can't save */
61
-                console.error("can't put", entry)
55
+    async patch(endpoint, payload = {}) {
56
+        const header = { ...headerTemplate }
57
+        header.method = 'PATCH'
58
+        header.body = JSON.stringify(payload)
59
+        try {
60
+            let res = await fetch(`${remote}${endpoint}`, header)
61
+            if (!res.ok) {
62
+                throw Error(res.statusText)
62 63
             }
63
-        } else {
64
-            /** not valid data */
65
-            console.error('NOT VALID!', entry.isValid())
64
+            const jsonRes = await res.json()
65
+            return jsonRes.data
66
+        } catch (error) {
67
+            console.error(error)
66 68
         }
67 69
     }
70
+    
68 71
     /** !: DEV ONLY */
69 72
     // async removeAll() { }
70 73
 }

Загрузка…
Отмена
Сохранить