-
Notifications
You must be signed in to change notification settings - Fork 426
Expand file tree
/
Copy pathindex.ts
More file actions
350 lines (311 loc) · 8.94 KB
/
index.ts
File metadata and controls
350 lines (311 loc) · 8.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
import { reportError } from '../ga';
import { toast } from 'react-toastify';
import messages from '../messages';
import shuffle from 'lodash/shuffle';
import partition from 'lodash/partition';
import { Application, Mentor, User, MentorshipRequest } from '../types/models';
import Auth from '../utils/auth';
import { setPersistData } from '../persistData';
type RequestMethod = 'POST' | 'GET' | 'PUT' | 'DELETE';
type ErrorResponse = {
success: false;
message: string;
};
type OkResponse<T> = {
success: true;
data: T;
};
const API_ERROR_TOAST_ID = 'api-error-toast-id';
const USER_LOCAL_KEY = 'user';
const USER_MENTORSHIP_REQUEST = 'mentorship-request';
export const paths = {
MENTORS: '/mentors',
USERS: '/users',
MENTORSHIP: '/mentorships',
ADMIN: '/admin',
FAVORITES: '/favorites',
};
let currentUser: User | undefined;
export default class ApiService {
mentorsPromise: Promise<Mentor[]> | null = null
auth: Auth;
constructor(auth: Auth) {
this.auth = auth
}
getAuthorizationHeader(): HeadersInit {
const token = this.auth?.getIdToken();
return token ? { Authorization: `Bearer ${token}` } : {};
}
getContentTypeHeader(jsonous: boolean): HeadersInit {
return jsonous ? { 'Content-Type': 'application/json' } : {};
}
makeApiCall = async <T>(
path: string,
body?: Record<string, any> | string | null,
method: RequestMethod = 'GET',
jsonous = true
): Promise<OkResponse<T> | ErrorResponse | null> => {
// public url for ssr
const url = `${process.env.NEXT_PUBLIC_PUBLIC_URL}/.netlify/functions${path}${
method === 'GET' && body ? `?${new URLSearchParams(body)}` : ''
}`;
const optionBody = jsonous
? body && JSON.stringify(body)
: (body as FormData);
const optionHeader: HeadersInit = {
...this.getAuthorizationHeader(),
...this.getContentTypeHeader(jsonous),
};
const options: RequestInit = {
mode: 'cors',
method,
body: method === 'GET' ? null : optionBody,
headers: optionHeader,
};
try {
const data = await fetch(url, options).catch((error) => {
return new Error(error);
});
if (data instanceof Error) {
throw data;
}
const res = await data.json();
if (res.statusCode >= 400) {
throw res.message;
}
return res;
} catch (error) {
// eslint-disable-next-line no-console
console.error(error);
const errorMessage = this.getErrorMessage(error);
reportError('Api', `${errorMessage || 'unknown error'} at ${path}`);
!toast.isActive(API_ERROR_TOAST_ID) &&
toast.error(errorMessage, {
toastId: API_ERROR_TOAST_ID,
});
return {
success: false,
message: error,
};
}
}
getCurrentUser = async (): Promise<typeof currentUser> => {
if (!this.auth.isAuthenticated()) {
this.clearCurrentUser();
return null;
}
const currentUserResponse = await this.makeApiCall<User>(`${paths.USERS}/current`)
if (currentUserResponse?.success) {
return currentUserResponse.data;
}
}
clearCurrentUser = () => {
currentUser = undefined;
ApiService.clearCurrentUserFromStorage();
}
// because we need to call it from authContext which doesn't have access to ApiService
static clearCurrentUserFromStorage = () => {
// TODO: use persistData
// eslint-disable-next-line no-restricted-syntax
localStorage.removeItem(USER_LOCAL_KEY);
}
getMentors = async () => {
if (!this.mentorsPromise) {
this.mentorsPromise = this.makeApiCall<Mentor[]>(`${paths.MENTORS}?limit=100&available=true`).then(
(response) => {
if (response?.success) {
const [available, unavailable] = partition(
response.data || [],
(mentor) => mentor.available
);
return [...shuffle(available), ...unavailable];
} else {
return [];
}
}
);
}
return this.mentorsPromise;
}
getUser = async (userId: string) => {
if (this.mentorsPromise != null) {
const mentors = await this.mentorsPromise;
const mentor = mentors.find((mentor) => mentor._id === userId);
if (mentor) {
return mentor;
}
}
const response = await this.makeApiCall<User>(`${paths.USERS}/${userId}`);
if (response?.success) {
return response.data;
}
return null;
}
getFavorites = async () => {
const response = await this.makeApiCall<{ mentorIds: string[] }>(
`${paths.FAVORITES}`
);
if (response?.success) {
return response.data.mentorIds;
}
return [];
}
addMentorToFavorites = async (mentorId: string) => {
const response = await this.makeApiCall(
`${paths.FAVORITES}/${mentorId}`,
{},
'POST'
);
return !!response?.success;
}
upsertApplication = async () => {
const response = await this.makeApiCall(
`${paths.MENTORS}/applications`,
{ description: 'why not?', status: 'Pending' },
'POST'
);
const success = response?.success === true;
return {
success,
message: success
? messages.EDIT_DETAILS_APPLICATION_SUBMITTED
: response?.message,
};
}
updateMentor = async (mentor: Mentor) => {
const response = await this.makeApiCall(
`${paths.USERS}`,
mentor,
'PUT'
);
return !!response?.success;
}
toggleAvatar = async (useGravatar: boolean) => {
const response = await this.makeApiCall<User>(
`${paths.USERS}/current/avatar`,
{ useGravatar },
'POST'
);
if (response?.success) {
return response.data;
}
return null;
}
// no need. we're using gravatar now
// updateMentorAvatar = async (mentor: Mentor, value: FormData) => {
// const response = await this.makeApiCall(
// `${paths.USERS}/${mentor._id}/avatar`,
// value,
// 'POST',
// false
// );
// if (response?.success) {
// await this.fetchCurrentItem();
// }
// return currentUser!;
// }
// TODO: do we need this? I think we have a general user update
// updateMentorAvailability = async (isAvailable: boolean) => {
// let currentUser = (await this.getCurrentUser())!;
// const userID = currentUser._id;
// const response = await this.makeApiCall(
// `${paths.USERS}/${userID}`,
// { available: isAvailable },
// 'PUT'
// );
// if (response?.success) {
// this.storeUserInLocalStorage({ ...currentUser, available: isAvailable });
// }
// return !!response?.success;
// }
deleteMentor = async (mentorId: string) => {
const response = await this.makeApiCall(
`${paths.USERS}/`,
null,
'DELETE'
);
return !!response?.success;
}
getPendingApplications = async () => {
const applicationStatus: Application['status'] = 'Pending';
const response = await this.makeApiCall<Application[]>(
`${paths.MENTORS}/applications?status=${applicationStatus}`,
null,
'GET'
);
return response?.success ? response.data : [];
}
respondApplication = async ({_id, ...applicationData}: Application) => {
const response = await this.makeApiCall(
`${paths.MENTORS}/applications/${_id}`,
applicationData,
'PUT'
);
return !!response?.success;
}
applyForMentorship = async (
mentor: Mentor,
{
background,
expectation,
message,
}: { background: string; expectation: string; message: string }
) => {
const payload = {
background,
expectation,
message,
};
const response = await this.makeApiCall(
`${paths.MENTORSHIP}/${mentor._id}/apply`,
payload,
'POST'
);
setPersistData('mentorship-request', payload);
return response;
}
getMyMentorshipApplication = () => {
// TODO: use persistData
// eslint-disable-next-line no-restricted-syntax
return JSON.parse(localStorage.getItem(USER_MENTORSHIP_REQUEST) || '{}');
}
getMentorshipRequests = async (userId: string) => {
const response = await this.makeApiCall<MentorshipRequest[]>(
`${paths.MENTORSHIP}/${userId}/requests`,
null,
'GET'
);
const apiOrder = response?.success ? response.data : [];
return apiOrder.reverse();
}
updateMentorshipReqStatus = async (
requestId: string,
userId: string,
payload: {
status: string;
reason: string;
}
) => {
const res = await this.makeApiCall(
`${paths.MENTORSHIP}/${userId}/requests/${requestId}`,
payload,
'PUT'
);
return res;
}
// Private methods
getErrorMessage = (error: { constraints: Record<string, string> }[]) => {
if (Array.isArray(error)) {
return Object.values(error[0].constraints)[0];
}
if (error) {
return error;
}
return messages.GENERIC_ERROR;
}
fetchCurrentItem = async () => {
}
resendVerificationEmail = async () => {
return this.makeApiCall(`${paths.USERS}/verify`, null, 'POST');
}
}