소스 검색

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

master
j 5 년 전
부모
커밋
ea94436c7b

+ 2
- 1
backend/lib/models/profile.js 파일 보기

7
     }
7
     }
8
     static get joiSchema() {
8
     static get joiSchema() {
9
         return Joi.object({
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 파일 보기

7
     }
7
     }
8
     static get joiSchema() {
8
     static get joiSchema() {
9
         return Joi.object({
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 파일 보기

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

+ 88
- 0
backend/lib/routes/profile/create.js 파일 보기

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 파일 보기

57
      * @param {Array} responses
57
      * @param {Array} responses
58
      * @returns
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
      * Delete a profile
78
      * Delete a profile

+ 35
- 36
backend/server/manifest.js 파일 보기

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
 /** Pull .env into process.env */
8
 /** Pull .env into process.env */
9
-Dotenv.config({ path: `${__dirname}/.env` });
9
+Dotenv.config({ path: `${__dirname}/.env` })
10
 
10
 
11
 /** Glue manifest as a confidence store */
11
 /** Glue manifest as a confidence store */
12
 module.exports = new Confidence.Store({
12
 module.exports = new Confidence.Store({
17
             $default: {
17
             $default: {
18
                 $param: 'API_PORT',
18
                 $param: 'API_PORT',
19
                 $coerce: 'number',
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
         debug: {
24
         debug: {
25
             $filter: 'NODE_ENV',
25
             $filter: 'NODE_ENV',
26
             $default: {
26
             $default: {
27
                 log: ['error', 'start'],
27
                 log: ['error', 'start'],
28
-                request: ['error']
28
+                request: ['error'],
29
             },
29
             },
30
             production: {
30
             production: {
31
-                request: ['implementation']
32
-            }
33
-        }
31
+                request: ['implementation'],
32
+            },
33
+        },
34
     },
34
     },
35
     register: {
35
     register: {
36
         plugins: [
36
         plugins: [
37
-
38
             /** Main app */
37
             /** Main app */
39
             {
38
             {
40
                 plugin: '../lib',
39
                 plugin: '../lib',
41
                 routes: {
40
                 routes: {
42
-                    prefix: '/api'
41
+                    prefix: '/api',
43
                 },
42
                 },
44
                 options: {
43
                 options: {
45
                     jwtKey: {
44
                     jwtKey: {
46
                         $filter: 'NODE_ENV',
45
                         $filter: 'NODE_ENV',
47
                         $default: {
46
                         $default: {
48
                             $param: 'APP_SECRET',
47
                             $param: 'APP_SECRET',
49
-                            $default: 'app-secret'
48
+                            $default: 'app-secret',
50
                         },
49
                         },
51
                         // Use .env file in production
50
                         // Use .env file in production
52
                         production: {
51
                         production: {
53
-                            $param: 'APP_SECRET'
54
-                        }
55
-                    }
56
-                }
52
+                            $param: 'APP_SECRET',
53
+                        },
54
+                    },
55
+                },
57
             },
56
             },
58
 
57
 
59
             /** Documentaion plugins */
58
             /** Documentaion plugins */
60
-            Inert, Vision,
59
+            Inert,
60
+            Vision,
61
             {
61
             {
62
                 plugin: HapiSwagger,
62
                 plugin: HapiSwagger,
63
                 options: {
63
                 options: {
64
-                    info: { title: 'Test API Documentation' }
65
-                }
64
+                    info: { title: 'Test API Documentation' },
65
+                },
66
             },
66
             },
67
             /** Model and knex integration */
67
             /** Model and knex integration */
68
             {
68
             {
76
                             client: process.env.DB_TYPE,
76
                             client: process.env.DB_TYPE,
77
                             useNullAsDefault: true,
77
                             useNullAsDefault: true,
78
                             connection: {
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
                     production: {
86
                     production: {
87
-                        migrateOnStart: false
88
-                    }
89
-                }
90
-            }
91
-        ]
92
-    }
87
+                        migrateOnStart: false,
88
+                    },
89
+                },
90
+            },
91
+        ],
92
+    },
93
 })
93
 })
94
-

Loading…
취소
저장