@monorise/react 1.0.11 → 1.0.12

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.
package/lib/api.ts ADDED
@@ -0,0 +1,150 @@
1
+ import request, {
2
+ type AxiosError,
3
+ type AxiosRequestConfig,
4
+ type AxiosResponse,
5
+ } from 'axios';
6
+ import type { AppActions } from '../actions/app.action';
7
+ import type { AuthActions } from '../actions/auth.action';
8
+ import type { MonoriseStore } from '../store/monorise.store';
9
+ import type { ApplicationRequestError } from '../types/api.type';
10
+
11
+ const initAxiosInterceptor = (store: MonoriseStore, appActions: AppActions) => {
12
+ const { startLoading } = appActions;
13
+
14
+ const axiosInstance = request.create();
15
+
16
+ function makeRequest<T = any, R = AxiosResponse<T, any>, D = any>(
17
+ url: string,
18
+ config: AxiosRequestConfig<D>,
19
+ data?: D,
20
+ ): Promise<R> {
21
+ const { requestKey, isInterruptive = false, feedback } = config;
22
+ const { ongoingRequests } = store.getState().app;
23
+
24
+ if (ongoingRequests.has(requestKey)) {
25
+ return ongoingRequests.get(requestKey) as Promise<R>;
26
+ }
27
+
28
+ const promise = axiosInstance.request<T, R, D>({
29
+ ...config,
30
+ url,
31
+ data,
32
+ headers: {
33
+ 'Mr-Interruptive': String(isInterruptive),
34
+ },
35
+ });
36
+ startLoading({
37
+ requestKey,
38
+ isInterruptive,
39
+ message: feedback?.loading,
40
+ request: promise,
41
+ });
42
+
43
+ return promise;
44
+ }
45
+
46
+ const axios = {
47
+ ...axiosInstance,
48
+ post: <T = any, R = AxiosResponse<T, any>, D = any>(
49
+ url: string,
50
+ data: D,
51
+ config: AxiosRequestConfig<D>,
52
+ ): Promise<R> => makeRequest(url, { ...config, method: 'POST' }, data),
53
+ put: <T = any, R = AxiosResponse<T, any>, D = any>(
54
+ url: string,
55
+ data: D,
56
+ config: AxiosRequestConfig<D>,
57
+ ): Promise<R> => makeRequest(url, { ...config, method: 'PUT' }, data),
58
+ patch: <T = any, R = AxiosResponse<T, any>, D = any>(
59
+ url: string,
60
+ data: D,
61
+ config: AxiosRequestConfig<D>,
62
+ ): Promise<R> => makeRequest(url, { ...config, method: 'PATCH' }, data),
63
+ delete: <T = any, R = AxiosResponse<T, any>, D = any>(
64
+ url: string,
65
+ config: AxiosRequestConfig<D>,
66
+ ): Promise<R> => makeRequest(url, { ...config, method: 'DELETE' }),
67
+ get: <T = any, R = AxiosResponse<T, any>, D = any>(
68
+ url: string,
69
+ config: AxiosRequestConfig<D>,
70
+ ): Promise<R> => makeRequest(url, { ...config, method: 'GET' }),
71
+ };
72
+
73
+ return axios;
74
+ };
75
+
76
+ type ConfigOptions = {
77
+ onApiSuccess?: <T>(
78
+ response: AxiosResponse<T>,
79
+ feedbackSuccess:
80
+ | ((data: AxiosResponse<T>['data']) => React.ReactNode)
81
+ | string
82
+ | boolean,
83
+ ) => void;
84
+ };
85
+
86
+ const injectAxiosInterceptor = (
87
+ appActions: AppActions,
88
+ authActions: AuthActions,
89
+ axios: ReturnType<typeof initAxiosInterceptor>,
90
+ opts?: ConfigOptions,
91
+ ) => {
92
+ let options: ConfigOptions = opts || {};
93
+ const { endLoading, setError, clearError } = appActions;
94
+ const { setIsUnauthorized } = authActions;
95
+
96
+ const unknownError: ApplicationRequestError = {
97
+ code: 'UNKNOWN_EXCEPTION',
98
+ message: "Ops, something doesn't seems right",
99
+ };
100
+
101
+ axios.interceptors.response.use(
102
+ (response) => {
103
+ const { requestKey, isInterruptive, feedback } = response.config;
104
+ endLoading({ requestKey, isInterruptive });
105
+ clearError(requestKey);
106
+
107
+ if (feedback?.success) {
108
+ options.onApiSuccess?.(response, feedback.success);
109
+ }
110
+ // switch (typeof feedback.success) {
111
+ // case 'function':
112
+ // toast(feedback.success(response.data));
113
+ // break;
114
+ // case 'string':
115
+ // toast(
116
+ // <Fragment>
117
+ // <IconCircleCheckFilled color='rgb(34 197 94)' />
118
+ // {feedback.success}
119
+ // </Fragment>,
120
+ // );
121
+ // break;
122
+ // case 'boolean':
123
+ // toast('Request success');
124
+ // break;
125
+ // }
126
+
127
+ return Promise.resolve(response);
128
+ },
129
+ (error: AxiosError<ApplicationRequestError>) => {
130
+ const { requestKey, isInterruptive } = error.config as AxiosRequestConfig;
131
+ endLoading({ requestKey, isInterruptive });
132
+ setError({ requestKey, error: error.response?.data || unknownError });
133
+ if (error.response?.status === 401) {
134
+ setIsUnauthorized(true);
135
+ }
136
+ return Promise.reject(error);
137
+ },
138
+ );
139
+
140
+ const setOptions = (opts: ConfigOptions) => {
141
+ options = {
142
+ ...options,
143
+ ...opts,
144
+ };
145
+ };
146
+
147
+ return { setOptions };
148
+ };
149
+
150
+ export { initAxiosInterceptor, injectAxiosInterceptor };
@@ -0,0 +1 @@
1
+ export const HTML_TAG_REGEX = /<\/?("[^"]*"|'[^']*'|[^>])*(>|$)/g;
package/lib/entity.ts ADDED
@@ -0,0 +1,76 @@
1
+ import type { CreatedEntity, Entity, EntitySchemaMap } from '@monorise/base';
2
+ import type { Mutual, MutualData } from '../types/mutual.type';
3
+
4
+ export const constructLocal = (
5
+ entityType: Entity,
6
+ entityId: string,
7
+ data: any,
8
+ ): CreatedEntity<Entity> => {
9
+ return {
10
+ entityType: entityType as unknown as string,
11
+ entityId,
12
+ data,
13
+ createdAt: new Date().toISOString(),
14
+ updatedAt: new Date().toISOString(),
15
+ };
16
+ };
17
+
18
+ export const constructMutual = <B extends Entity, T extends Entity>(
19
+ byEntityType: B,
20
+ byEntityId: string,
21
+ entityType: T,
22
+ entityId: string,
23
+ mutualData: Partial<MutualData<B, T>>,
24
+ data: EntitySchemaMap[T],
25
+ ): Mutual => {
26
+ return {
27
+ mutualId: `${byEntityId}-${entityId}`,
28
+ byEntityType,
29
+ byEntityId,
30
+ entityType,
31
+ entityId,
32
+ mutualData,
33
+ data,
34
+ createdAt: new Date().toISOString(),
35
+ updatedAt: new Date().toISOString(),
36
+ mutualUpdatedAt: new Date().toISOString(),
37
+ };
38
+ };
39
+
40
+ export const flipMutual = (mutual: Mutual): Mutual => {
41
+ return {
42
+ ...mutual,
43
+ entityId: mutual.byEntityId,
44
+ entityType: mutual.byEntityType,
45
+ byEntityId: mutual.entityId,
46
+ byEntityType: mutual.entityType,
47
+ };
48
+ };
49
+
50
+ export const byMutualIndex = (a: Mutual<any, any>, b: Mutual<any, any>) => {
51
+ return a.mutualData.index - b.mutualData.index;
52
+ };
53
+
54
+ export const byEntityId = (a: CreatedEntity<any>, b: CreatedEntity<any>) => {
55
+ if (b.entityId < a.entityId) return -1;
56
+ return 1;
57
+ };
58
+
59
+ export const constructOrderByIndex = (mutuals: Mutual<any, any>[]) => {
60
+ return mutuals.sort(byMutualIndex).map((mutual) => mutual.entityId);
61
+ };
62
+
63
+ export const injectFields = <T extends Entity>(
64
+ entity: CreatedEntity<T> | undefined,
65
+ fields: Record<string, any>,
66
+ ): CreatedEntity<T> | undefined => {
67
+ return entity
68
+ ? {
69
+ ...entity,
70
+ data: {
71
+ ...entity.data,
72
+ ...fields,
73
+ },
74
+ }
75
+ : undefined;
76
+ };
package/lib/utils.ts ADDED
@@ -0,0 +1,12 @@
1
+ export const convertToMap = <T extends Record<string, any>>(
2
+ data: T[],
3
+ mapKey: string,
4
+ ) => {
5
+ const map = new Map();
6
+
7
+ for (const i in data) {
8
+ map.set(data[i][mapKey], data[i]);
9
+ }
10
+
11
+ return map;
12
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@monorise/react",
3
- "version": "1.0.11",
3
+ "version": "1.0.12",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -0,0 +1,65 @@
1
+ import type { Entity } from '@monorise/base';
2
+ import type { AxiosInterceptor } from '../types/api.type';
3
+
4
+ type LoginPayload = {
5
+ email: string;
6
+ };
7
+
8
+ type Options = {
9
+ apiBaseUrl?: string;
10
+ };
11
+
12
+ const initAuthService = (axios: AxiosInterceptor) => {
13
+ let options: Options = {};
14
+ const { apiBaseUrl = '/api/auth' } = options;
15
+
16
+ const requestLoginMagicLink = (entityType: Entity, payload: LoginPayload) => {
17
+ return axios.post(
18
+ `${apiBaseUrl}/${entityType}`,
19
+ {
20
+ body: { ...payload },
21
+ },
22
+ {
23
+ requestKey: `auth/${entityType}/request-login`,
24
+ isInterruptive: true,
25
+ feedback: {
26
+ loading: 'Requesting login link',
27
+ },
28
+ },
29
+ );
30
+ };
31
+
32
+ const getSessionProfile = <T extends Record<string, unknown>>() =>
33
+ axios.get<
34
+ T & {
35
+ displayName: string;
36
+ email: string;
37
+ accountId: string;
38
+ }
39
+ >('/session', {
40
+ requestKey: 'auth/session',
41
+ });
42
+
43
+ const logout = () =>
44
+ axios.get('/logout', {
45
+ requestKey: 'auth/logout',
46
+ });
47
+
48
+ const setOptions = (opts: Options) => {
49
+ options = {
50
+ ...options,
51
+ ...opts,
52
+ };
53
+ };
54
+
55
+ return {
56
+ requestLoginMagicLink,
57
+ getSessionProfile,
58
+ logout,
59
+ setOptions,
60
+ };
61
+ };
62
+
63
+ export default initAuthService;
64
+
65
+ export type AuthService = ReturnType<typeof initAuthService>;