Преглед изворни кода

:recycle: adding more detailed responses for membership endpoints | adding some comments and renaming things too

tags/0.0.1
TOJ пре 4 година
родитељ
комит
7c8f8ca0e5

+ 1
- 1
backend/lib/routes/membership/active.js Прегледај датотеку

46
             const membershipType = request.query.type
46
             const membershipType = request.query.type
47
 
47
 
48
             const profileId = request.params.profile_id
48
             const profileId = request.params.profile_id
49
-            const groupings = await membershipService.findGroupingsById(
49
+            const groupings = await membershipService.findGroupingsByProfileId(
50
                 profileId,
50
                 profileId,
51
                 membershipType
51
                 membershipType
52
             )
52
             )

+ 61
- 35
backend/lib/routes/membership/join.js Прегледај датотеку

9
 }
9
 }
10
 
10
 
11
 const validators = {
11
 const validators = {
12
-    join: {
13
-        payload: Joi.object({
14
-            profile_id: Joi.number().required(),
15
-            target_id: Joi.number().allow(null),
16
-            grouping_id: Joi.number().allow(null),
17
-            grouping_name: Joi.string().allow(null),
18
-            grouping_type: Joi.string().allow(null),
19
-            role: Joi.string(),
20
-        }),
21
-    },
12
+    payload: Joi.object({
13
+        profile_id: Joi.number().required(),
14
+        target_id: Joi.number().allow(null),
15
+        grouping_id: Joi.number().allow(null),
16
+        grouping_name: Joi.string().allow(null),
17
+        grouping_type: Joi.string().allow(null),
18
+        role: Joi.string(),
19
+    }),
20
+}
21
+
22
+const responseSchemas = {
23
+    response: Joi.object({
24
+        memberships: Joi.array().items(),
25
+        hasMatch: Joi.boolean()
26
+    }),
27
+    error: Joi.object({
28
+        error: Joi.string(),
29
+    }),
22
 }
30
 }
23
 
31
 
24
 module.exports = {
32
 module.exports = {
35
          * @param {*} h
43
          * @param {*} h
36
          * @returns {object}
44
          * @returns {object}
37
          */
45
          */
38
-        handler: async function (request) {
46
+        handler: async function (request, h) {
39
             try {
47
             try {
40
-                const { membershipService } = request.services()
48
+                const { membershipService } = request.server.services()
41
 
49
 
42
                 /** Grab payload info */
50
                 /** Grab payload info */
43
                 const res = request.payload
51
                 const res = request.payload
50
                 /** Default to participant role */
58
                 /** Default to participant role */
51
                 const role = res.role ? res.role : 'participant'
59
                 const role = res.role ? res.role : 'participant'
52
 
60
 
61
+                console.log('---')
53
                 /** User membership service method to create membership */
62
                 /** User membership service method to create membership */
54
                 const memberships = await membershipService.joinGrouping(
63
                 const memberships = await membershipService.joinGrouping(
55
                     res.profile_id,
64
                     res.profile_id,
57
                     groupingToWrite,
66
                     groupingToWrite,
58
                     role,
67
                     role,
59
                 )
68
                 )
60
-
61
-                return {
62
-                    ok: true,
63
-                    handler: pluginConfig.handlerType,
64
-                    data: {
65
-                        memberships,
66
-                        hasMatch: memberships.every(
67
-                            membership => membership.is_active == true,
68
-                        ),
69
-                    },
70
-                }
69
+                console.log(memberships)
70
+                return h
71
+                    .response({
72
+                        ok: true,
73
+                        handler: pluginConfig.handlerType,
74
+                        data: {
75
+                            memberships,
76
+                            hasMatch: memberships.every(
77
+                                membership => membership.is_active == true,
78
+                            ),
79
+                        },
80
+                    })
81
+                    .code(200)
71
             } catch (err) {
82
             } catch (err) {
72
-                return {
73
-                    ok: false,
74
-                    handler: pluginConfig.handlerType,
75
-                    data: { error: `${err}` },
76
-                }
83
+                return h
84
+                    .response({
85
+                        ok: false,
86
+                        handler: pluginConfig.handlerType,
87
+                        data: { error: `${err}` },
88
+                    })
89
+                    .code(409)
77
             }
90
             }
78
         },
91
         },
79
-        validate: validators.join,
92
+
93
+        /** Validate based on validators object */
94
+        validate: {
95
+            ...validators,
96
+            failAction: 'log'
97
+        },
98
+
99
+        /** Validate the server response */
80
         response: {
100
         response: {
81
-            schema: Joi.object({
82
-                ok: Joi.bool(),
83
-                handler: Joi.string(),
84
-                data: Joi.object(),
85
-            }),
86
-            failAction: 'log',
101
+            status: {
102
+                200: Joi.object({
103
+                    ok: Joi.bool(),
104
+                    handler: Joi.string(),
105
+                    data: responseSchemas.response,
106
+                }),
107
+                409: Joi.object({
108
+                    ok: Joi.bool(),
109
+                    handler: Joi.string(),
110
+                    data: responseSchemas.error,
111
+                }),
112
+            },
87
         },
113
         },
88
     },
114
     },
89
 }
115
 }

+ 30
- 51
backend/lib/services/membership.js Прегледај датотеку

10
      * @param {number} profileId
10
      * @param {number} profileId
11
      * @returns {Array} List of all grouping_ids for user
11
      * @returns {Array} List of all grouping_ids for user
12
      */
12
      */
13
-    async _getGroupIdsForProfileId(profileId, type) {
13
+    async _getGroupingIdsForProfileId(profileId, type) {
14
         const { Membership } = this.server.models()
14
         const { Membership } = this.server.models()
15
 
15
 
16
         /** Grab every Membership associated with this id */
16
         /** Grab every Membership associated with this id */
17
         let allMemberships
17
         let allMemberships
18
-        console.log()
18
+
19
         if(type) {
19
         if(type) {
20
             allMemberships = await Membership.query()
20
             allMemberships = await Membership.query()
21
                 .where({ profile_id: profileId })
21
                 .where({ profile_id: profileId })
26
                 .where({ profile_id: profileId })
26
                 .where({ profile_id: profileId })
27
                 .where({ is_active: true })
27
                 .where({ is_active: true })
28
         }
28
         }
29
-        
29
+
30
         /** Copy a list of the just the Groupings */
30
         /** Copy a list of the just the Groupings */
31
         const groupingIdsToGrab = allMemberships.map(
31
         const groupingIdsToGrab = allMemberships.map(
32
             membership => membership.grouping_id,
32
             membership => membership.grouping_id,
38
 
38
 
39
     /**
39
     /**
40
      * Internal method to create a new grouping
40
      * Internal method to create a new grouping
41
-     * @param {*} groupingToTry
41
+     * @param {object} groupingToTry from payload data
42
      * @param {*} txn
42
      * @param {*} txn
43
-     * @returns
43
+     * @returns {Grouping} created db record
44
      */
44
      */
45
     async _createGrouping(groupingToTry, txn) {
45
     async _createGrouping(groupingToTry, txn) {
46
         const { Grouping } = this.server.models()
46
         const { Grouping } = this.server.models()
50
         }
50
         }
51
         return await Grouping.query(txn).insert(groupingInfo)
51
         return await Grouping.query(txn).insert(groupingInfo)
52
     }
52
     }
53
-
54
-    async findOrCreateGrouping(groupingToTry) {
53
+    /**
54
+     * Tries to grab a grouping_id from payload data
55
+     * or returns grouping_id from a newly created record
56
+     * @param {object} groupingToTry from payload data
57
+     * @returns {number} grouping_id from payload or created record
58
+     */
59
+    async findOrCreateGroupingFromPayload(groupingToTry) {
55
         let idToReturn = groupingToTry.grouping_id
60
         let idToReturn = groupingToTry.grouping_id
56
         if (!idToReturn) {
61
         if (!idToReturn) {
57
             /** ?: For some reason this returns the key id */
62
             /** ?: For some reason this returns the key id */
66
      * @param {number} profileId
71
      * @param {number} profileId
67
      * @returns {Array}
72
      * @returns {Array}
68
      */
73
      */
69
-    async findGroupingsById(profileId, type) {
74
+    async findGroupingsByProfileId(profileId, type) {
70
         const { Grouping } = this.server.models()
75
         const { Grouping } = this.server.models()
71
 
76
 
72
-        const dedupedGroupings = await this._getGroupIdsForProfileId(profileId, type)
77
+        const dedupedGroupings = await this._getGroupingIdsForProfileId(profileId, type)
73
 
78
 
74
         /** Grab just the Groupings this id has a Membership for */
79
         /** Grab just the Groupings this id has a Membership for */
75
         return await Grouping.query()
80
         return await Grouping.query()
76
-            .throwIfNotFound()
77
             .whereIn('grouping_id', dedupedGroupings)
81
             .whereIn('grouping_id', dedupedGroupings)
78
     }
82
     }
79
 
83
 
80
     async _groupingIdsInCommon(profileId, targetId) {
84
     async _groupingIdsInCommon(profileId, targetId) {
81
-        const dedupedUserGroupingIds = await this._getGroupIdsForProfileId(
85
+        const dedupedUserGroupingIds = await this._getGroupingIdsForProfileId(
82
             profileId,
86
             profileId,
83
         )
87
         )
84
-        const dedupedTargetGroupingIds = await this._getGroupIdsForProfileId(
88
+        const dedupedTargetGroupingIds = await this._getGroupingIdsForProfileId(
85
             targetId,
89
             targetId,
86
         )
90
         )
87
 
91
 
102
         }
106
         }
103
     }
107
     }
104
 
108
 
105
-    async attemptMatch(profileId, targetId) {
106
-        const { Membership } = this.server.models()
107
-
108
-        /** If both people have groups in common */
109
-        const matchingGroupingIds = await this._groupingIdsInCommon(
110
-            profileId,
111
-            targetId,
112
-        )
113
-
114
-        if (matchingGroupingIds.length) {
115
-            /** Grab all memberships associated with groupingIds */
116
-            const memberships = await Membership.query().whereIn(
117
-                'grouping_id',
118
-                matchingGroupingIds,
119
-            )
120
-
121
-            /** Set membership as active only if the user initiates it */
122
-            await this._patchMembership(memberships, profileId, {
123
-                is_active: true,
124
-            })
125
-
126
-            /** Make a new query to get updated information */
127
-            return await Membership.query().whereIn(
128
-                'grouping_id',
129
-                matchingGroupingIds,
130
-            )
131
-        }
132
-    }
133
 
109
 
134
     /**
110
     /**
135
      * Check for grouping membership then add membership record and set to active
111
      * Check for grouping membership then add membership record and set to active
168
             )
144
             )
169
         } else {
145
         } else {
170
             /**
146
             /**
171
-             * If both have NO grouping in common create a membership
172
-             * for both to new group but set membership as inactive for target
147
+             * If both have NO grouping in common, create a membership
148
+             * for both and add to a new grouping but
149
+             * set membership as inactive for target
173
              * */
150
              * */
174
-            /** Check if the grouping exists and if NOT creat it */
175
-            const groupingId = await this.findOrCreateGrouping(groupingToWrite)
176
 
151
 
177
-            const userMembership = await Membership.query(txn).insert({
178
-                profile_id: profileId,
152
+            /** Check if the grouping exists and if NOT create it */
153
+            const groupingId = await this.findOrCreateGroupingFromPayload(groupingToWrite)
154
+            const membershipDetailsInCommon = {
179
                 grouping_id: groupingId,
155
                 grouping_id: groupingId,
180
                 membership_type: role,
156
                 membership_type: role,
181
                 can_edit: false,
157
                 can_edit: false,
158
+            }
159
+
160
+            const userMembership = await Membership.query(txn).insert({
161
+                profile_id: profileId,
162
+                ...membershipDetailsInCommon,
182
                 is_active: true,
163
                 is_active: true,
183
             })
164
             })
184
 
165
 
185
             const targetMembership = await Membership.query(txn).insert({
166
             const targetMembership = await Membership.query(txn).insert({
186
-                profile_id: profileId,
187
-                grouping_id: groupingId,
188
-                membership_type: role,
189
-                can_edit: false,
167
+                profile_id: targetId,
168
+                ...membershipDetailsInCommon,
190
                 is_active: false,
169
                 is_active: false,
191
             })
170
             })
192
 
171
 
203
     async leaveGrouping(profileId, groupingId) {
182
     async leaveGrouping(profileId, groupingId) {
204
         const { Membership } = this.server.models()
183
         const { Membership } = this.server.models()
205
 
184
 
206
-        const dedupedGroupings = await this._getGroupIdsForProfileId(profileId)
185
+        const dedupedGroupings = await this._getGroupingIdsForProfileId(profileId)
207
 
186
 
208
         /** Do NOTHING if NOT in Grouping */
187
         /** Do NOTHING if NOT in Grouping */
209
         if (!dedupedGroupings.includes(groupingId)) return
188
         if (!dedupedGroupings.includes(groupingId)) return

Loading…
Откажи
Сачувај