@selfcommunity/react-core
Version:
React Core Components useful for integrating UI Community components (react-ui).
246 lines (244 loc) • 10.5 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const react_1 = require("react");
const api_services_1 = require("@selfcommunity/api-services");
const types_1 = require("@selfcommunity/types");
const useSCCachingManager_1 = tslib_1.__importDefault(require("./useSCCachingManager"));
const Errors_1 = require("../constants/Errors");
const utils_1 = require("@selfcommunity/utils");
const SCPreferencesProvider_1 = require("../components/provider/SCPreferencesProvider");
const Notification_1 = require("../constants/Notification");
const Preferences_1 = require("../constants/Preferences");
const use_deep_compare_effect_1 = require("use-deep-compare-effect");
const pubsub_js_1 = tslib_1.__importDefault(require("pubsub-js"));
/**
:::info
This custom hook is used to manage the courses followed.
:::
:::tip How to use it:
Follow these steps:
```jsx
1. const scUserContext: SCUserContextType = useSCUser();
2. const scJoinedCoursesManager: SCJoinedCoursesManagerType = scUserContext.manager.courses;
3. scJoinedCoursesManager.isJoined(course)
```
:::
*/
function useSCJoinedCoursesManager(user) {
const { cache, updateCache, emptyCache, data, setData, loading, setLoading, setUnLoading, isLoading } = (0, useSCCachingManager_1.default)();
const { preferences, features } = (0, SCPreferencesProvider_1.useSCPreferences)();
const authUserId = user ? user.id : null;
const coursesEnabled = (0, react_1.useMemo)(() => preferences &&
features &&
features.includes(types_1.SCFeatureName.COURSE) &&
Preferences_1.CONFIGURATIONS_COURSES_ENABLED in preferences &&
preferences[Preferences_1.CONFIGURATIONS_COURSES_ENABLED].value, [preferences, features]);
const notificationInvitedToJoinCourse = (0, react_1.useRef)(null);
const notificationAddedToCourse = (0, react_1.useRef)(null);
/**
* Subscribe to notification types user_follow, user_unfollow
*/
(0, use_deep_compare_effect_1.useDeepCompareEffectNoCheck)(() => {
notificationInvitedToJoinCourse.current = pubsub_js_1.default.subscribe(`${types_1.SCNotificationTopicType.INTERACTION}.${types_1.SCNotificationTypologyType.USER_INVITED_TO_JOIN_COURSE}`, notificationSubscriber);
notificationAddedToCourse.current = pubsub_js_1.default.subscribe(`${types_1.SCNotificationTopicType.INTERACTION}.${types_1.SCNotificationTypologyType.USER_ADDED_TO_COURSE}`, notificationSubscriber);
return () => {
pubsub_js_1.default.unsubscribe(notificationInvitedToJoinCourse.current);
pubsub_js_1.default.unsubscribe(notificationAddedToCourse.current);
};
}, [data]);
/**
* Notification subscriber handler
* @param msg
* @param dataMsg
*/
const notificationSubscriber = (msg, dataMsg) => {
var _a;
if (dataMsg.data.course !== undefined) {
let _status;
switch (Notification_1.SCNotificationMapping[dataMsg.data.activity_type]) {
case types_1.SCNotificationTypologyType.USER_INVITED_TO_JOIN_COURSE:
_status = types_1.SCCourseJoinStatusType.INVITED;
break;
case types_1.SCNotificationTypologyType.USER_ADDED_TO_COURSE:
if (dataMsg.data.notification_obj.course && ((_a = dataMsg.data.notification_obj.course.paywalls) === null || _a === void 0 ? void 0 : _a.length)) {
_status = types_1.SCCourseJoinStatusType.PAYMENT_WAITING;
}
else {
_status = types_1.SCCourseJoinStatusType.JOINED;
}
break;
}
updateCache([dataMsg.data.course]);
setData((prev) => getDataUpdated(prev, dataMsg.data.course, _status));
}
};
/**
* Memoized refresh all courses
* It makes a single request to the server and retrieves
* all the courses followed by the user in a single solution
* It might be useful for multi-tab sync
*/
const refresh = (0, react_1.useMemo)(() => () => {
emptyCache();
if (user) {
// Only if user is authenticated
api_services_1.http
.request({
url: api_services_1.Endpoints.GetUserJoinedCourses.url({ id: user.id }),
method: api_services_1.Endpoints.GetUserJoinedCourses.method,
})
.then((res) => {
if (res.status >= 300) {
return Promise.reject(res);
}
const coursesIds = res.data.results.map((c) => c.id);
updateCache(coursesIds);
setData(res.data.results.map((c) => ({ [c.id]: c.join_status })));
return Promise.resolve(res.data);
})
.catch((e) => {
utils_1.Logger.error(Errors_1.SCOPE_SC_CORE, 'Unable to refresh the authenticated user courses.');
utils_1.Logger.error(Errors_1.SCOPE_SC_CORE, e);
});
}
}, [data, user, cache]);
/**
* Memoized join Course
* Toggle action
*/
const join = (0, react_1.useMemo)(() => (course) => tslib_1.__awaiter(this, void 0, void 0, function* () {
setLoading(course.id);
const res = yield api_services_1.http.request({
url: api_services_1.Endpoints.JoinOrAcceptInviteToCourse.url({ id: course.id }),
method: api_services_1.Endpoints.JoinOrAcceptInviteToCourse.method,
});
if (res.status >= 300) {
return Promise.reject(res);
}
updateCache([course.id]);
setData((prev) => getDataUpdated(prev, course.id, course.privacy === types_1.SCCoursePrivacyType.PRIVATE && course.join_status !== types_1.SCCourseJoinStatusType.INVITED
? types_1.SCCourseJoinStatusType.REQUESTED
: types_1.SCCourseJoinStatusType.JOINED));
setUnLoading(course.id);
return yield Promise.resolve(res.data);
}), [data, loading, cache]);
/**
* Memoized leave Course
* Toggle action
*/
const leave = (0, react_1.useMemo)(() => (course) => tslib_1.__awaiter(this, void 0, void 0, function* () {
if (data[course.id] !== types_1.SCCourseJoinStatusType.REQUESTED) {
setLoading(course.id);
const res = yield api_services_1.http.request({
url: api_services_1.Endpoints.LeaveOrRemoveCourseRequest.url({ id: course.id }),
method: api_services_1.Endpoints.LeaveOrRemoveCourseRequest.method,
});
if (res.status >= 300) {
return Promise.reject(res);
}
updateCache([course.id]);
setData((prev) => getDataUpdated(prev, course.id, null));
setUnLoading(course.id);
return yield Promise.resolve(res.data);
}
}), [data, loading, cache]);
/**
* Check the authenticated user subscription status to the course
* Update the courses cached
* Update courses subscription statuses
* @param course
*/
const checkCourseJoinedStatus = (course) => {
setLoading(course.id);
return api_services_1.http
.request({
url: api_services_1.Endpoints.GetCourseStatus.url({ id: course.id }),
method: api_services_1.Endpoints.GetCourseStatus.method,
})
.then((res) => {
if (res.status >= 300) {
return Promise.reject(res);
}
setData((prev) => getDataUpdated(prev, course.id, res.data.status));
updateCache([course.id]);
setUnLoading(course.id);
return Promise.resolve(res.data);
})
.catch((e) => {
setUnLoading(course.id);
return Promise.reject(e);
});
};
/**
* Get updated data
* @param data
* @param courseId
* @param joinStatus
*/
const getDataUpdated = (data, courseId, joinStatus) => {
const _index = data.findIndex((k) => parseInt(Object.keys(k)[0]) === courseId);
let _data;
if (_index < 0) {
_data = [...data, ...[{ [courseId]: joinStatus }]];
}
else {
_data = data.map((k, i) => {
if (parseInt(Object.keys(k)[0]) === courseId) {
return { [Object.keys(k)[0]]: joinStatus };
}
return { [Object.keys(k)[0]]: data[i][Object.keys(k)[0]] };
});
}
return _data;
};
/**
* Return current course subscription status if exists,
* otherwise return null
*/
const getCurrentCourseCacheStatus = (0, react_1.useMemo)(() => (course) => {
const d = data.filter((k) => parseInt(Object.keys(k)[0]) === course.id);
return d.length ? d[0][course.id] : !data.length ? course.join_status : null;
}, [data]);
/**
* Bypass remote check if the course is subscribed
*/
const getJoinStatus = (0, react_1.useMemo)(() => (course) => {
updateCache([course.id]);
setData((prev) => getDataUpdated(prev, course.id, course.join_status));
return course.join_status;
}, [data, cache]);
/**
* Memoized joinStatus
* If the course is already in cache -> check if the course is in courses,
* otherwise, check if user joined the course
*/
const joinStatus = (0, react_1.useMemo)(() => (course) => {
// Cache is valid also for anonymous user
if (cache.includes(course.id)) {
return getCurrentCourseCacheStatus(course);
}
if (authUserId && course) {
if ('join_status' in course) {
return getJoinStatus(course);
}
if (!isLoading(course)) {
checkCourseJoinedStatus(course);
}
}
return null;
}, [loading, cache, authUserId, getJoinStatus, getCurrentCourseCacheStatus]);
/**
* Empty cache on logout
*/
(0, react_1.useEffect)(() => {
if (!authUserId) {
emptyCache();
}
}, [authUserId]);
if (!coursesEnabled || !user) {
return { courses: data, loading, isLoading };
}
return { courses: data, loading, isLoading, join, leave, joinStatus, refresh, emptyCache };
}
exports.default = useSCJoinedCoursesManager;
;