dce-reactkit 3.0.0-beta.24 → 3.0.0-beta.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/cjs/index.js +436 -5
  2. package/dist/cjs/index.js.map +1 -1
  3. package/dist/cjs/types/components/AppWrapper.d.ts +25 -0
  4. package/dist/cjs/types/helpers/genRouteHandler.d.ts +30 -0
  5. package/dist/cjs/types/helpers/handleError.d.ts +18 -0
  6. package/dist/cjs/types/helpers/handleSuccess.d.ts +8 -0
  7. package/dist/cjs/types/helpers/visitServerEndpoint.d.ts +23 -0
  8. package/dist/cjs/types/index.d.ts +6 -1
  9. package/dist/cjs/types/server/initServer.d.ts +21 -0
  10. package/dist/cjs/types/types/ParamType.d.ts +17 -0
  11. package/dist/cjs/types/types/ReactKitErrorCode.d.ts +3 -1
  12. package/dist/esm/index.js +431 -5
  13. package/dist/esm/index.js.map +1 -1
  14. package/dist/esm/types/components/AppWrapper.d.ts +25 -0
  15. package/dist/esm/types/helpers/genRouteHandler.d.ts +30 -0
  16. package/dist/esm/types/helpers/handleError.d.ts +18 -0
  17. package/dist/esm/types/helpers/handleSuccess.d.ts +8 -0
  18. package/dist/esm/types/helpers/visitServerEndpoint.d.ts +23 -0
  19. package/dist/esm/types/index.d.ts +6 -1
  20. package/dist/esm/types/server/initServer.d.ts +21 -0
  21. package/dist/esm/types/types/ParamType.d.ts +17 -0
  22. package/dist/esm/types/types/ReactKitErrorCode.d.ts +3 -1
  23. package/dist/index.d.ts +109 -2
  24. package/package.json +2 -1
  25. package/rollup.config.js +0 -1
  26. package/src/components/AppWrapper.tsx +52 -0
  27. package/src/helpers/genRouteHandler.ts +326 -0
  28. package/src/helpers/handleError.ts +65 -0
  29. package/src/helpers/handleSuccess.ts +18 -0
  30. package/src/helpers/visitServerEndpoint.tsx +110 -0
  31. package/src/index.ts +13 -0
  32. package/src/server/initServer.ts +53 -0
  33. package/src/types/ParamType.tsx +18 -0
  34. package/src/types/ReactKitErrorCode.tsx +3 -1
@@ -0,0 +1,326 @@
1
+ // Import caccl functions
2
+ import { cacclGetLaunchInfo } from '../server/initServer';
3
+
4
+ // Import shared types
5
+ import ReactKitErrorCode from '../types/ReactKitErrorCode';
6
+ import ParamType from '../types/ParamType';
7
+
8
+ // Import helpers
9
+ import handleError from './handleError';
10
+ import handleSuccess from './handleSuccess';
11
+
12
+ /**
13
+ * Generate an express API route handler
14
+ * @author Gabe Abrams
15
+ * @param opts object containing all arguments
16
+ * @param opts.paramTypes map containing the types for each parameter that is
17
+ * included in the request (map: param name => type)
18
+ * @param opts.handler function that processes the request
19
+ * @returns express route handler that takes the following arguments:
20
+ * params (map: param name => value), handleSuccess (function for handling
21
+ * successful requests), handleError (function for handling failed requests),
22
+ * req (express request object), res (express response object)
23
+ */
24
+ const genRouteHandler = (
25
+ opts: {
26
+ paramTypes: {
27
+ [k: string]: ParamType
28
+ },
29
+ handler: (
30
+ opts: {
31
+ params: {
32
+ [k: string]: any
33
+ },
34
+ handleSuccess: (body: any) => void,
35
+ handleError: (error: any) => void,
36
+ req: any,
37
+ res: any,
38
+ },
39
+ ) => void,
40
+ },
41
+ ) => {
42
+ // Return a route handler
43
+ return async (req: any, res: any) => {
44
+ // Output params
45
+ const output: { [k in string]: any } = {};
46
+
47
+ /*----------------------------------------*/
48
+ /* Parse Params */
49
+ /*----------------------------------------*/
50
+
51
+ // Process items one by one
52
+ const paramList = Object.entries(opts.paramTypes);
53
+ for (let i = 0; i < paramList.length; i++) {
54
+ const [name, type] = paramList[i];
55
+
56
+ // Find the value as a string
57
+ const value = (
58
+ req.params[name]
59
+ || req.query[name]
60
+ || req.body[name]
61
+ );
62
+
63
+ // Parse
64
+ if (type === ParamType.Boolean || type === ParamType.BooleanOptional) {
65
+ // Boolean
66
+
67
+ // Handle case where value doesn't exist
68
+ if (value === undefined) {
69
+ if (type === ParamType.BooleanOptional) {
70
+ output[name] = undefined;
71
+ } else {
72
+ return handleError(
73
+ res,
74
+ {
75
+ message: `Parameter ${name} is required, but it was not included.`,
76
+ code: ReactKitErrorCode.MissingParameter,
77
+ status: 422,
78
+ },
79
+ );
80
+ }
81
+ } else {
82
+ // Value exists
83
+
84
+ // Simplify value
85
+ const simpleVal = (
86
+ String(value)
87
+ .trim()
88
+ .toLowerCase()
89
+ );
90
+
91
+ // Parse
92
+ output[name] = (
93
+ [
94
+ 'true',
95
+ 'yes',
96
+ 'y',
97
+ '1',
98
+ 't',
99
+ ].indexOf(simpleVal) >= 0
100
+ );
101
+ }
102
+ } else if (type === ParamType.Float || type === ParamType.FloatOptional) {
103
+ // Float
104
+
105
+ // Handle case where value doesn't exist
106
+ if (value === undefined) {
107
+ if (type === ParamType.FloatOptional) {
108
+ output[name] = undefined;
109
+ } else {
110
+ return handleError(
111
+ res,
112
+ {
113
+ message: `Parameter ${name} is required, but it was not included.`,
114
+ code: ReactKitErrorCode.MissingParameter,
115
+ status: 422,
116
+ },
117
+ );
118
+ }
119
+ } else if (!Number.isNaN(Number.parseFloat(String(value)))) {
120
+ // Value is a number
121
+ output[name] = Number.parseFloat(String(value));
122
+ } else {
123
+ // Issue!
124
+ return handleError(
125
+ res,
126
+ {
127
+ message: `Request data was malformed: ${name} was not a valid float.`,
128
+ code: ReactKitErrorCode.InvalidParameter,
129
+ status: 422,
130
+ },
131
+ );
132
+ }
133
+ } else if (type === ParamType.Int || type === ParamType.IntOptional) {
134
+ // Int
135
+
136
+ // Handle case where value doesn't exist
137
+ if (value === undefined) {
138
+ if (type === ParamType.IntOptional) {
139
+ output[name] = undefined;
140
+ } else {
141
+ return handleError(
142
+ res,
143
+ {
144
+ message: `Parameter ${name} is required, but it was not included.`,
145
+ code: ReactKitErrorCode.MissingParameter,
146
+ status: 422,
147
+ },
148
+ );
149
+ }
150
+ } else if (!Number.isNaN(Number.parseInt(String(value), 10))) {
151
+ // Value is a number
152
+ output[name] = Number.parseInt(String(value), 10);
153
+ } else {
154
+ // Issue!
155
+ return handleError(
156
+ res,
157
+ {
158
+ message: `Request data was malformed: ${name} was not a valid int.`,
159
+ code: ReactKitErrorCode.InvalidParameter,
160
+ status: 422,
161
+ },
162
+ );
163
+ }
164
+ } else if (type === ParamType.JSON || type === ParamType.JSONOptional) {
165
+ // Stringified JSON
166
+
167
+ // Handle case where value doesn't exist
168
+ if (value === undefined) {
169
+ if (type === ParamType.JSONOptional) {
170
+ output[name] = undefined;
171
+ } else {
172
+ return handleError(
173
+ res,
174
+ {
175
+ message: `Parameter ${name} is required, but it was not included.`,
176
+ code: ReactKitErrorCode.MissingParameter,
177
+ status: 422,
178
+ },
179
+ );
180
+ }
181
+ } else {
182
+ // Value exists
183
+
184
+ // Parse
185
+ try {
186
+ output[name] = JSON.parse(String(value));
187
+ } catch (err) {
188
+ return handleError(
189
+ res,
190
+ {
191
+ message: `Request data was malformed: ${name} was not a valid JSON payload.`,
192
+ code: ReactKitErrorCode.InvalidParameter,
193
+ status: 422,
194
+ },
195
+ );
196
+ }
197
+ }
198
+ } else if (type === ParamType.String || type === ParamType.StringOptional) {
199
+ // String
200
+
201
+ // Handle case where value doesn't exist
202
+ if (value === undefined) {
203
+ if (type === ParamType.StringOptional) {
204
+ output[name] = undefined;
205
+ } else {
206
+ return handleError(
207
+ res,
208
+ {
209
+ message: `Parameter ${name} is required, but it was not included.`,
210
+ code: ReactKitErrorCode.MissingParameter,
211
+ status: 422,
212
+ },
213
+ );
214
+ }
215
+ } else {
216
+ // Value exists
217
+
218
+ // Leave as is
219
+ output[name] = value;
220
+ }
221
+ } else {
222
+ // No valid data type
223
+ return handleError(
224
+ res,
225
+ {
226
+ message: `An internal error occurred: we could not determine the type of ${name}.`,
227
+ code: ReactKitErrorCode.InvalidParameter,
228
+ status: 422,
229
+ },
230
+ );
231
+ }
232
+ }
233
+
234
+ /*----------------------------------------*/
235
+ /* Launch Info */
236
+ /*----------------------------------------*/
237
+
238
+ // Get launch info
239
+ const { launched, launchInfo } = cacclGetLaunchInfo(req);
240
+ if (!launched || !launchInfo) {
241
+ return handleError(
242
+ res,
243
+ {
244
+ message: 'Your session has expired. Please refresh the page and try again.',
245
+ code: ReactKitErrorCode.SessionExpired,
246
+ status: 440,
247
+ },
248
+ );
249
+ }
250
+
251
+ // Error if user info cannot be found
252
+ if (
253
+ !launchInfo.userId
254
+ || !launchInfo.userFirstName
255
+ || !launchInfo.userLastName
256
+ || (
257
+ launchInfo.notInCourse
258
+ && !launchInfo.isAdmin
259
+ )
260
+ || (
261
+ !launchInfo.isTTM
262
+ && !launchInfo.isLearner
263
+ && !launchInfo.isAdmin
264
+ )
265
+ ) {
266
+ return handleError(
267
+ res,
268
+ {
269
+ message: 'Your session was invalid. Please refresh the page and try again.',
270
+ code: ReactKitErrorCode.SessionExpired,
271
+ status: 440,
272
+ },
273
+ );
274
+ }
275
+
276
+ // Add launch info to output
277
+ output.userId = launchInfo.userId;
278
+ output.userFirstName = launchInfo.userFirstName;
279
+ output.userLastName = launchInfo.userLastName;
280
+ output.isLearner = !!launchInfo.isLearner;
281
+ output.isTTM = !!launchInfo.isTTM;
282
+ output.isAdmin = !!launchInfo.isAdmin;
283
+ output.isWatchingInPrivate = !!(req.session.isWatchingInPrivate);
284
+
285
+ /*----------------------------------------*/
286
+ /* Require Course Consistency */
287
+ /*----------------------------------------*/
288
+
289
+ // Make sure the user actually launched from the appropriate course
290
+ if (
291
+ output.courseId
292
+ && launchInfo.courseId
293
+ && output.courseId !== launchInfo.courseId
294
+ && !output.isTTM
295
+ && !output.isAdmin
296
+ ) {
297
+ // Course of interest is not the launch course
298
+ return handleError(
299
+ res,
300
+ {
301
+ message: 'You switched sessions by opening Immersive Classroom in another tab. Please refresh the page and try again.',
302
+ code: ReactKitErrorCode.WrongCourse,
303
+ status: 401,
304
+ },
305
+ );
306
+ }
307
+
308
+ /*------------------------------------------------------------------------*/
309
+ /* Call handler */
310
+ /*------------------------------------------------------------------------*/
311
+
312
+ opts.handler({
313
+ params: output,
314
+ handleSuccess: (body: any) => {
315
+ return handleSuccess(res, body);
316
+ },
317
+ handleError: (error: any) => {
318
+ return handleError(res, error);
319
+ },
320
+ req,
321
+ res,
322
+ });
323
+ };
324
+ };
325
+
326
+ export default genRouteHandler;
@@ -0,0 +1,65 @@
1
+ // Import shared types
2
+ import ReactKitErrorCode from '../types/ReactKitErrorCode';
3
+
4
+ /**
5
+ * Handle an error and respond to the client
6
+ * @author Gabe Abrams
7
+ * @param res express response
8
+ * @param error error info
9
+ * @param opts.err the error to send to the client
10
+ * or the error message
11
+ * @param [opts.code] an error code (only used if err.code is not
12
+ * included)
13
+ * @param [opts.status=500] the https status code to use
14
+ * defined)
15
+ */
16
+ const handleError = (
17
+ res: any,
18
+ error: (
19
+ | {
20
+ message: any,
21
+ code?: string,
22
+ status?: number,
23
+ }
24
+ | Error
25
+ | string
26
+ | any
27
+ ),
28
+ ): undefined => {
29
+ // Get the error message
30
+ let message;
31
+ if (error && (error as any).message) {
32
+ message = (error.message || 'An unknown error occurred.');
33
+ } else if (typeof error === 'string') {
34
+ message = (
35
+ error.trim().length > 0
36
+ ? error
37
+ : 'An unknown error occurred.'
38
+ );
39
+ } else {
40
+ message = 'An unknown error occurred.';
41
+ }
42
+
43
+ // Get the error code
44
+ const code = (error.code || ReactKitErrorCode.NoCode);
45
+
46
+ // Get the status code
47
+ const status = (error.status || 500);
48
+
49
+ // Respond to user
50
+ res
51
+ // Set the http status code
52
+ .status(status)
53
+ // Send a JSON response
54
+ .json({
55
+ // Error message
56
+ message,
57
+ // Error code
58
+ code,
59
+ // Success = false flag so client can detect server-side errors
60
+ success: false,
61
+ });
62
+ return undefined;
63
+ };
64
+
65
+ export default handleError;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Send successful API response
3
+ * @author Gabe Abrams
4
+ * @param res express response
5
+ * @param body the body of the response to send to the client
6
+ */
7
+ const handleSuccess = (res: any, body: any): undefined => {
8
+ // Send a http 200 json response
9
+ res.json({
10
+ // Include the body as a parameter
11
+ body,
12
+ // Success = true flag so client can detect successful responses
13
+ success: true,
14
+ });
15
+ return undefined;
16
+ };
17
+
18
+ export default handleSuccess;
@@ -0,0 +1,110 @@
1
+ // Import custom error
2
+ import ErrorWithCode from '../errors/ErrorWithCode';
3
+ import ReactKitErrorCode from '../types/ReactKitErrorCode';
4
+
5
+ // Import helpers from app wrapper
6
+ import { cacclSendRequest } from '../components/AppWrapper';
7
+
8
+ /*------------------------------------------------------------------------*/
9
+ /* Listener */
10
+ /*------------------------------------------------------------------------*/
11
+
12
+ // Handler for session expiry
13
+ let sessionExpiryHandler: () => void;
14
+
15
+ // Keep track of whether or not session expiry has already been handled
16
+ let sessionAlreadyExpired = false;
17
+
18
+ /**
19
+ * Set the session expiry handler
20
+ * @author Gabe Abrams
21
+ * @param handler new handler to use when session expires
22
+ */
23
+ export const setSessionExpiryHandler = (handler: () => void) => {
24
+ sessionExpiryHandler = handler;
25
+ };
26
+
27
+ /*------------------------------------------------------------------------*/
28
+ /* Main */
29
+ /*------------------------------------------------------------------------*/
30
+
31
+ /**
32
+ * Visit an endpoint on the server [for client only]
33
+ * @author Gabe Abrams
34
+ * @param opts object containing all arguments
35
+ * @param opts.path - the path of the server endpoint
36
+ * @param [opts.method=GET] - the method of the endpoint
37
+ * @param [opts.params] - query/body parameters to include
38
+ * @returns response from server
39
+ */
40
+ const visitServerEndpoint = async (
41
+ opts: {
42
+ path: string,
43
+ method?: ('GET' | 'POST' | 'DELETE' | 'PUT'),
44
+ params?: { [key in string]: any },
45
+ },
46
+ ): Promise<any> => {
47
+ // Send the request
48
+ const response = await cacclSendRequest({
49
+ path: opts.path,
50
+ method: opts.method ?? 'GET',
51
+ params: opts.params,
52
+ });
53
+
54
+ // Check for failure
55
+ if (!response || !response.body) {
56
+ throw new ErrorWithCode(
57
+ 'We didn\'t get a response from the server. Please check your internet connection.',
58
+ ReactKitErrorCode.NoResponse,
59
+ );
60
+ }
61
+ if (!response.body.success) {
62
+ // Session expired
63
+ if (response.body.code === ReactKitErrorCode.SessionExpired) {
64
+ // Skip notice if session was already expired
65
+ if (sessionAlreadyExpired) {
66
+ // Never return (browser is already reloading)
67
+ await new Promise<{ [key in string]: any }>(() => {
68
+ // Promise that never returns
69
+ });
70
+ }
71
+ sessionAlreadyExpired = true;
72
+
73
+ // Show session expiration message
74
+ if (sessionExpiryHandler) {
75
+ // Use handler
76
+ sessionExpiryHandler();
77
+ } else {
78
+ // Fallback to alert
79
+
80
+ // eslint-disable-next-line no-alert
81
+ alert('Your session has expired. Please start over.');
82
+ }
83
+
84
+ // Never return (don't continue execution)
85
+ await new Promise<{ [key in string]: any }>(() => {
86
+ // Promise that never returns
87
+ });
88
+ }
89
+
90
+ // Other errors
91
+ throw new ErrorWithCode(
92
+ (
93
+ response.body.message
94
+ || 'An unknown error occurred. Please contact an admin.'
95
+ ),
96
+ (
97
+ response.body.code
98
+ || ReactKitErrorCode.NoCode
99
+ ),
100
+ );
101
+ }
102
+
103
+ // Success! Extract the body
104
+ const { body } = response.body;
105
+
106
+ // Return
107
+ return body;
108
+ };
109
+
110
+ export default visitServerEndpoint;
package/src/index.ts CHANGED
@@ -19,6 +19,10 @@ import padZerosLeft from './helpers/padZerosLeft';
19
19
  import roundToNumDecimals from './helpers/roundToNumDecimals';
20
20
  import sum from './helpers/sum';
21
21
  import waitMs from './helpers/waitMs';
22
+ import visitServerEndpoint from './helpers/visitServerEndpoint';
23
+ import genRouteHandler from './helpers/genRouteHandler';
24
+ import handleError from './helpers/handleError';
25
+ import handleSuccess from './helpers/handleSuccess';
22
26
 
23
27
  // Import types
24
28
  import ModalButtonType from './types/ModalButtonType';
@@ -26,6 +30,7 @@ import ModalSize from './types/ModalSize';
26
30
  import ModalType from './types/ModalType';
27
31
  import ReactKitErrorCode from './types/ReactKitErrorCode';
28
32
  import Variant from './types/Variant';
33
+ import ParamType from './types/ParamType';
29
34
 
30
35
  // Export each item
31
36
  export {
@@ -52,10 +57,18 @@ export {
52
57
  roundToNumDecimals,
53
58
  sum,
54
59
  waitMs,
60
+ // Client helpers
61
+ visitServerEndpoint,
62
+ // Server helpers
63
+ genRouteHandler,
64
+ handleError,
65
+ handleSuccess,
55
66
  // Types
56
67
  ModalButtonType,
57
68
  ModalSize,
58
69
  ModalType,
59
70
  ReactKitErrorCode,
60
71
  Variant,
72
+ // Server types
73
+ ParamType,
61
74
  };
@@ -0,0 +1,53 @@
1
+ // Import custom error
2
+ import ErrorWithCode from '../errors/ErrorWithCode';
3
+ import ReactKitErrorCode from '../types/ReactKitErrorCode';
4
+
5
+ // Types
6
+ type GetLaunchInfoFunction = (req: any) => {
7
+ launched: boolean,
8
+ launchInfo?: any,
9
+ };
10
+
11
+ // Stored copy of caccl functions
12
+ let _cacclGetLaunchInfo: GetLaunchInfoFunction;
13
+
14
+ /*------------------------------------------------------------------------*/
15
+ /* Helpers */
16
+ /*------------------------------------------------------------------------*/
17
+
18
+ /**
19
+ * Get launch info via CACCL
20
+ * @author Gabe Abrams
21
+ * @param req express request object
22
+ * @returns object { launched, launchInfo }
23
+ */
24
+ export const cacclGetLaunchInfo: GetLaunchInfoFunction = (req: any) => {
25
+ if (!_cacclGetLaunchInfo) {
26
+ throw new ErrorWithCode(
27
+ 'Could not get launch info because server was not initialized with dce-reactkit\'s initServer function',
28
+ ReactKitErrorCode.NoCACCLGetLaunchInfoFunction,
29
+ );
30
+ }
31
+
32
+ return _cacclGetLaunchInfo(req);
33
+ };
34
+
35
+ /*------------------------------------------------------------------------*/
36
+ /* Main */
37
+ /*------------------------------------------------------------------------*/
38
+
39
+ /**
40
+ * Prepare dce-reactkit to run on the server
41
+ * @author Gabe Abrams
42
+ * @param opts object containing all arguments
43
+ * @param opts.getLaunchInfo CACCL LTI's get launch info function
44
+ */
45
+ const initServer = (
46
+ opts: {
47
+ getLaunchInfo: GetLaunchInfoFunction,
48
+ },
49
+ ) => {
50
+ _cacclGetLaunchInfo = opts.getLaunchInfo;
51
+ };
52
+
53
+ export default initServer;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Server-side API param types
3
+ * @author Gabe Abrams
4
+ */
5
+ enum ParamType {
6
+ Boolean = 'boolean', // Boolean
7
+ BooleanOptional = 'boolean-optional', // Optional boolean
8
+ Float = 'float', // Float Number
9
+ FloatOptional = 'float-optional', // Optional Float Number
10
+ Int = 'int', // Integer Number
11
+ IntOptional = 'int-optional', // Optional Integer Number
12
+ JSON = 'json', // JSONified object
13
+ JSONOptional = 'json-optional', // Optional JSONified object
14
+ String = 'string', // String
15
+ StringOptional = 'string-optional', // Optional string
16
+ }
17
+
18
+ export default ParamType;
@@ -1,4 +1,4 @@
1
- // Highest error code = DRK2
1
+ // Highest error code = DRK8
2
2
 
3
3
  /**
4
4
  * List of error codes built into the react kit
@@ -11,6 +11,8 @@ enum ReactKitErrorCode {
11
11
  MissingParameter = 'DRK4',
12
12
  InvalidParameter = 'DRK5',
13
13
  WrongCourse = 'DRK6',
14
+ NoCACCLSendRequestFunction = 'DRK7',
15
+ NoCACCLGetLaunchInfoFunction = 'DRK8',
14
16
  }
15
17
 
16
18
  export default ReactKitErrorCode;