Pārlūkot izejas kodu

:sparkles: added ability to send responses and creat new profile

master
j 5 gadus atpakaļ
vecāks
revīzija
ea94436c7b

+ 2
- 1
backend/lib/models/profile.js Parādīt failu

@@ -7,7 +7,8 @@ module.exports = class Profile extends Schwifty.Model {
7 7
     }
8 8
     static get joiSchema() {
9 9
         return Joi.object({
10
-            profile_id: Joi.number().required(),
10
+            profile_id: Joi.number(),
11
+            user_id: Joi.number(),
11 12
         })
12 13
     }
13 14
 }

+ 4
- 1
backend/lib/models/response.js Parādīt failu

@@ -7,7 +7,10 @@ module.exports = class Response extends Schwifty.Model {
7 7
     }
8 8
     static get joiSchema() {
9 9
         return Joi.object({
10
-            response_id: Joi.number().required(),
10
+            response_id: Joi.number(),
11
+            profile_id: Joi.number(),
12
+            response_key_id: Joi.number(),
13
+            val: Joi.string(),
11 14
         })
12 15
     }
13 16
 }

+ 2
- 0
backend/lib/plugins/profile.js Parādīt failu

@@ -7,6 +7,7 @@ const ResponseModel = require('../models/response')
7 7
 const ProfileService = require('../services/profile')
8 8
 
9 9
 const ProfileProfilesRoute = require('../routes/profile/profiles')
10
+const ProfileCreateRoute = require('../routes/profile/create')
10 11
 
11 12
 module.exports = {
12 13
     name: 'profile-plugin',
@@ -25,5 +26,6 @@ module.exports = {
25 26
         server.registerService(ProfileService)
26 27
 
27 28
         await server.route(ProfileProfilesRoute)
29
+        await server.route(ProfileCreateRoute)
28 30
     },
29 31
 }

+ 88
- 0
backend/lib/routes/profile/create.js Parādīt failu

@@ -0,0 +1,88 @@
1
+'use strict'
2
+
3
+const Joi = require('joi')
4
+
5
+const pluginConfig = {
6
+    handlerType: 'profile',
7
+    docs: {
8
+        description: 'Create profile',
9
+        notes: 'Create a profile associated with this user',
10
+    },
11
+}
12
+
13
+const validators = {
14
+    /** Validate the header (cookie check) */
15
+    // headers: true,
16
+
17
+    /** Validate the route params (/active/{thing}) */
18
+    params: Joi.object({ user_id: Joi.number() }),
19
+
20
+    /** Validate the route query (/active/{thing}?limit=10&offset=10) */
21
+    // query: true,
22
+    /** Validate the incoming payload (POST method) */
23
+    payload: Joi.array().items(
24
+        Joi.object({
25
+            response_key_id: Joi.number().required(),
26
+            val: Joi.string().required(),
27
+        }),
28
+    ),
29
+}
30
+
31
+const responseSchemas = {
32
+    response: Joi.object({
33
+        profile_id: Joi.number(),
34
+        user_id: Joi.number(),
35
+    }),
36
+}
37
+
38
+module.exports = {
39
+    method: 'POST',
40
+    path: '/{user_id}/create',
41
+    options: {
42
+        ...pluginConfig.docs,
43
+        tags: ['api'],
44
+        /** Protect this route with authentication? */
45
+        auth: false,
46
+
47
+        handler: async function (request) {
48
+            const { profileService } = request.services()
49
+            const userId = request.params.user_id
50
+
51
+            /** Grab payload info */
52
+            const res = request.payload
53
+
54
+            const profile = await profileService.saveResponsesCreateProfileFor(
55
+                userId,
56
+                res,
57
+            )
58
+            try {
59
+                return {
60
+                    ok: true,
61
+                    handler: pluginConfig.handlerType,
62
+                    data: profile,
63
+                }
64
+            } catch (err) {
65
+                return {
66
+                    ok: false,
67
+                    handler: pluginConfig.handlerType,
68
+                    data: { error: `${err}` },
69
+                }
70
+            }
71
+        },
72
+
73
+        /** Validate based on validators object */
74
+        validate: {
75
+            ...validators,
76
+            failAction: 'log',
77
+        },
78
+
79
+        /** Validate the server response */
80
+        response: {
81
+            schema: Joi.object({
82
+                ok: Joi.bool(),
83
+                handler: Joi.string(),
84
+                data: responseSchemas.response,
85
+            }),
86
+        },
87
+    },
88
+}

+ 16
- 2
backend/lib/services/profile.js Parādīt failu

@@ -57,8 +57,22 @@ module.exports = class ProfileService extends Schmervice.Service {
57 57
      * @param {Array} responses
58 58
      * @returns
59 59
      */
60
-    async saveProfile(userId, responses, txn) {
61
-        console.warn(userId, responses, txn)
60
+    async saveResponsesCreateProfileFor(userId, responses, txn) {
61
+        const { Profile, Response } = this.server.models()
62
+
63
+        const profile = await Profile.query(txn).insert({
64
+            user_id: userId,
65
+        })
66
+        for (const responseToSave of responses) {
67
+            const responseInfo = {
68
+                profile_id: profile.id,
69
+                response_key_id: responseToSave.response_key_id,
70
+                val: responseToSave.val,
71
+            }
72
+            await Response.query(txn).insert(responseInfo)
73
+        }
74
+        //** Work around for HAPI returning profile_id as id */
75
+        return { user_id: profile.user_id, profile_id: profile.id }
62 76
     }
63 77
     /**
64 78
      * Delete a profile

+ 35
- 36
backend/server/manifest.js Parādīt failu

@@ -1,12 +1,12 @@
1
-const Dotenv = require('dotenv');
2
-const Confidence = require('@hapipal/confidence');
3
-const Inert = require('@hapi/inert');
4
-const Vision = require('@hapi/vision');
5
-const Schwifty = require('@hapipal/schwifty');
6
-const HapiSwagger = require('hapi-swagger');
1
+const Dotenv = require('dotenv')
2
+const Confidence = require('@hapipal/confidence')
3
+const Inert = require('@hapi/inert')
4
+const Vision = require('@hapi/vision')
5
+const Schwifty = require('@hapipal/schwifty')
6
+const HapiSwagger = require('hapi-swagger')
7 7
 
8 8
 /** Pull .env into process.env */
9
-Dotenv.config({ path: `${__dirname}/.env` });
9
+Dotenv.config({ path: `${__dirname}/.env` })
10 10
 
11 11
 /** Glue manifest as a confidence store */
12 12
 module.exports = new Confidence.Store({
@@ -17,52 +17,52 @@ module.exports = new Confidence.Store({
17 17
             $default: {
18 18
                 $param: 'API_PORT',
19 19
                 $coerce: 'number',
20
-                $default: process.env.API_PORT
20
+                $default: process.env.API_PORT,
21 21
             },
22
-            test: { $value: undefined }         // Let the server find an open port
22
+            test: { $value: undefined }, // Let the server find an open port
23 23
         },
24 24
         debug: {
25 25
             $filter: 'NODE_ENV',
26 26
             $default: {
27 27
                 log: ['error', 'start'],
28
-                request: ['error']
28
+                request: ['error'],
29 29
             },
30 30
             production: {
31
-                request: ['implementation']
32
-            }
33
-        }
31
+                request: ['implementation'],
32
+            },
33
+        },
34 34
     },
35 35
     register: {
36 36
         plugins: [
37
-
38 37
             /** Main app */
39 38
             {
40 39
                 plugin: '../lib',
41 40
                 routes: {
42
-                    prefix: '/api'
41
+                    prefix: '/api',
43 42
                 },
44 43
                 options: {
45 44
                     jwtKey: {
46 45
                         $filter: 'NODE_ENV',
47 46
                         $default: {
48 47
                             $param: 'APP_SECRET',
49
-                            $default: 'app-secret'
48
+                            $default: 'app-secret',
50 49
                         },
51 50
                         // Use .env file in production
52 51
                         production: {
53
-                            $param: 'APP_SECRET'
54
-                        }
55
-                    }
56
-                }
52
+                            $param: 'APP_SECRET',
53
+                        },
54
+                    },
55
+                },
57 56
             },
58 57
 
59 58
             /** Documentaion plugins */
60
-            Inert, Vision,
59
+            Inert,
60
+            Vision,
61 61
             {
62 62
                 plugin: HapiSwagger,
63 63
                 options: {
64
-                    info: { title: 'Test API Documentation' }
65
-                }
64
+                    info: { title: 'Test API Documentation' },
65
+                },
66 66
             },
67 67
             /** Model and knex integration */
68 68
             {
@@ -76,19 +76,18 @@ module.exports = new Confidence.Store({
76 76
                             client: process.env.DB_TYPE,
77 77
                             useNullAsDefault: true,
78 78
                             connection: {
79
-                                host : process.env.DB_HOST,
80
-                                user : process.env.DB_USER,
81
-                                password : process.env.DB_ROOT_PASSWORD,
82
-                                database : process.env.DB_NAME
83
-                            }
84
-                        }
79
+                                host: process.env.DB_HOST,
80
+                                user: process.env.DB_USER,
81
+                                password: process.env.DB_ROOT_PASSWORD,
82
+                                database: process.env.DB_NAME,
83
+                            },
84
+                        },
85 85
                     },
86 86
                     production: {
87
-                        migrateOnStart: false
88
-                    }
89
-                }
90
-            }
91
-        ]
92
-    }
87
+                        migrateOnStart: false,
88
+                    },
89
+                },
90
+            },
91
+        ],
92
+    },
93 93
 })
94
-

Notiek ielāde…
Atcelt
Saglabāt