-
Notifications
You must be signed in to change notification settings - Fork 344
Expand file tree
/
Copy pathuseInvites.js
More file actions
91 lines (81 loc) · 2.76 KB
/
useInvites.js
File metadata and controls
91 lines (81 loc) · 2.76 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
// @flow
import React, { useState } from 'react';
import noop from 'lodash/noop';
import API from '../../../api';
import type { SendInvitesFnType, UseInvitesOptions } from '../types';
import type { InviteCollaboratorsRequest } from '../../../features/unified-share-modal/flowTypes';
import type { ItemType } from '../../../common/types/core';
/**
* Generate the sendInvites() function, which is used for inviting collaborators in the USM.
*
* @param {API} api
* @param {string} itemID
* @param {ItemType} itemType
* @param {UseInvitesOptions} options
*/
function useInvites(api: API, itemID: string, itemType: ItemType, options: UseInvitesOptions) {
const [sendInvites, setSendInvites] = useState<null | SendInvitesFnType>(null);
const {
collaborators,
handleSuccess = noop,
handleError = noop,
isContentSharingV2Enabled,
setIsLoading = noop,
transformRequest,
transformResponse = arg => arg,
} = options;
React.useEffect(() => {
if (sendInvites || (isContentSharingV2Enabled && !collaborators)) return;
const itemData = {
id: itemID,
type: itemType,
};
const sendCollabRequest = collab => {
return new Promise((resolve, reject) => {
api.getCollaborationsAPI(false).addCollaboration(
itemData,
collab,
response => {
handleSuccess(response);
resolve(transformResponse(response));
},
error => {
handleError(error);
reject(error);
},
);
});
};
const createPostCollaborationFn: SendInvitesFnType =
() => async (collabRequest: InviteCollaboratorsRequest) => {
if (!transformRequest) return Promise.resolve(null);
const { users, groups } = transformRequest(collabRequest);
setIsLoading(true);
try {
return await Promise.all([
...users.map(user => sendCollabRequest(user)),
...groups.map(group => sendCollabRequest(group)),
]);
} finally {
setIsLoading(false);
}
};
if (!sendInvites) {
setSendInvites(createPostCollaborationFn);
}
}, [
api,
collaborators,
handleError,
handleSuccess,
isContentSharingV2Enabled,
itemID,
itemType,
sendInvites,
setIsLoading,
transformRequest,
transformResponse,
]);
return sendInvites;
}
export default useInvites;