@selfcommunity/react-core
Version:
React Core Components useful for integrating UI Community components (react-ui).
240 lines (239 loc) • 10.7 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.contributorsObjectActionTypes = void 0;
const tslib_1 = require("tslib");
const react_1 = require("react");
const Errors_1 = require("../constants/Errors");
const api_services_1 = require("@selfcommunity/api-services");
const utils_1 = require("@selfcommunity/utils");
const useSCFetchFeedObject_1 = tslib_1.__importDefault(require("./useSCFetchFeedObject"));
const Cache_1 = require("../constants/Cache");
const hooks_1 = require("../utils/hooks");
/**
* @hidden
* We have complex state logic that involves multiple sub-values,
* so useReducer is preferable to useState.
* Define all possible auth action types label
* Use this to export actions and dispatch an action
*/
exports.contributorsObjectActionTypes = {
LOADING_NEXT: '_loading_next',
LOADING_PREVIOUS: '_loading_previous',
DATA_NEXT_LOADED: '_data_next_loaded',
DATA_PREVIOUS_LOADED: '_data_previous_loaded',
DATA_RELOAD: '_data_reload',
DATA_RELOADED: '_data_reloaded',
};
/**
* contributorsReducer:
* - manage the state of contributors object
* - update the state base on action type
* @param state
* @param action
*/
function contributorsReducer(state, action) {
switch (action.type) {
case exports.contributorsObjectActionTypes.LOADING_NEXT:
return Object.assign(Object.assign({}, state), { isLoadingNext: true, isLoadingPrevious: false });
case exports.contributorsObjectActionTypes.LOADING_PREVIOUS:
return Object.assign(Object.assign({}, state), { isLoadingNext: false, isLoadingPrevious: true });
case exports.contributorsObjectActionTypes.DATA_NEXT_LOADED:
return Object.assign(Object.assign(Object.assign(Object.assign({}, state), { page: action.payload.currentPage, contributors: action.payload.contributors, isLoadingNext: false, componentLoaded: true, next: action.payload.next }), (action.payload.previous ? { previous: action.payload.previous } : {})), (action.payload.total ? { total: action.payload.total } : {}));
case exports.contributorsObjectActionTypes.DATA_PREVIOUS_LOADED:
return Object.assign(Object.assign({}, state), { page: action.payload.currentPage, contributors: action.payload.contributors, isLoadingPrevious: false, previous: action.payload.previous });
case exports.contributorsObjectActionTypes.DATA_RELOAD:
return Object.assign(Object.assign({}, state), { next: action.payload.next, contributors: [], total: 0, previous: null, reload: true });
case exports.contributorsObjectActionTypes.DATA_RELOADED:
return Object.assign(Object.assign({}, state), { componentLoaded: false, reload: false });
default:
throw new Error(`Unhandled type: ${action.type}`);
}
}
/**
* Define initial state
* @param data
*/
function stateInitializer(data) {
const __contributorsObjectCacheKey = data.obj ? (0, Cache_1.getContributorsCacheKey)(data.obj.id, data.obj.type, data.next) : null;
let _initState = {
componentLoaded: false,
contributors: [],
total: 0,
next: data.next,
previous: null,
isLoadingNext: false,
isLoadingPrevious: false,
page: data.offset / data.pageSize + 1,
reload: false,
};
if (__contributorsObjectCacheKey && utils_1.LRUCache.hasKey(__contributorsObjectCacheKey) && data.cacheStrategy !== utils_1.CacheStrategies.NETWORK_ONLY) {
const _cachedData = utils_1.LRUCache.get(__contributorsObjectCacheKey);
return Object.assign(Object.assign({}, _initState), { total: _cachedData.count, next: _cachedData.next, previous: _cachedData.previous, contributors: _cachedData.results });
}
return _initState;
}
/**
:::info
This custom hooks is used to fetch paginated contributors.
:::
* @param props
*/
function useSCFetchContributors(props) {
// PROPS
const { id, feedObject, feedObjectType, offset = 0, pageSize = 5, onChangePage, cacheStrategy = utils_1.CacheStrategies.CACHE_FIRST } = props;
// REFS
const isMountedRef = (0, hooks_1.useIsComponentMountedRef)();
// FeedObject
const { obj, setObj } = (0, useSCFetchFeedObject_1.default)({ id, feedObject, feedObjectType });
const objId = obj ? obj.id : null;
/**
* Get next url
*/
const getNextUrl = () => {
const _offset = offset ? `&offset=${offset}` : '';
const _objectId = obj ? obj.id : id;
const _typeObject = obj ? obj.type : feedObjectType;
return `${api_services_1.Endpoints.FeedObjectContributorsList.url({ type: _typeObject, id: _objectId })}?limit=${pageSize}${_offset}`;
};
// STATE
const [state, dispatch] = (0, react_1.useReducer)(contributorsReducer, {}, () => stateInitializer({ obj, offset, pageSize, next: getNextUrl(), cacheStrategy }));
/**
* Calculate current page
*/
const getCurrentPage = (url) => {
const urlSearchParams = new URLSearchParams(url);
const params = Object.fromEntries(urlSearchParams.entries());
const currentOffset = params.offset ? parseInt(params.offset) : 0;
return currentOffset / pageSize + 1;
};
/**
* Get Comments (with cache)
*/
const revalidate = (url, forward) => {
return performFetchComments(url, false).then((res) => {
let _contributors;
let currentPage = getCurrentPage(state.next);
if (forward) {
let start = state.contributors.slice(0, state.contributors.length - res.results.length);
_contributors = start.concat(res.results);
}
else {
let start = state.contributors.slice(res.results.length, state.contributors.length);
_contributors = res.results.concat(start);
}
if (isMountedRef.current) {
dispatch({
type: forward ? exports.contributorsObjectActionTypes.DATA_NEXT_LOADED : exports.contributorsObjectActionTypes.DATA_PREVIOUS_LOADED,
payload: Object.assign(Object.assign({ page: currentPage, contributors: _contributors }, (forward ? { next: res.next } : { previous: res.previous })), { total: res.count }),
});
}
});
};
/**
* Get Comments
*/
const performFetchComments = (url, seekCache = true) => {
const _contributorsCacheKey = (0, Cache_1.getContributorsCacheKey)(obj.id, obj.type, url);
if (seekCache && utils_1.LRUCache.hasKey(_contributorsCacheKey) && cacheStrategy !== utils_1.CacheStrategies.NETWORK_ONLY) {
return Promise.resolve(utils_1.LRUCache.get(_contributorsCacheKey));
}
return api_services_1.http
.request({
url,
method: api_services_1.Endpoints.Comments.method,
})
.then((res) => {
if (res.status >= 300) {
return Promise.reject(res);
}
utils_1.LRUCache.set(_contributorsCacheKey, res.data);
return Promise.resolve(res.data);
});
};
/**
* Fetch previous contributors
*/
function getPreviousPage() {
if (obj && state.previous && !state.isLoadingPrevious) {
dispatch({ type: exports.contributorsObjectActionTypes.LOADING_PREVIOUS });
performFetchComments(state.previous)
.then((res) => {
if (isMountedRef.current) {
let currentPage = getCurrentPage(state.previous);
dispatch({
type: exports.contributorsObjectActionTypes.DATA_PREVIOUS_LOADED,
payload: {
page: currentPage,
contributors: [...res.results, ...state.contributors],
previous: res.previous,
},
});
onChangePage && onChangePage(currentPage);
}
})
.catch((error) => {
utils_1.Logger.error(Errors_1.SCOPE_SC_CORE, error);
})
.then(() => {
if (cacheStrategy === utils_1.CacheStrategies.STALE_WHILE_REVALIDATE) {
revalidate(state.next, false);
}
});
}
}
/**
* Fetch next contributors
*/
function getNextPage() {
if (obj && state.next && !state.isLoadingNext) {
dispatch({ type: exports.contributorsObjectActionTypes.LOADING_NEXT });
performFetchComments(state.next)
.then((res) => {
if (isMountedRef.current) {
let currentPage = getCurrentPage(state.next);
dispatch({
type: exports.contributorsObjectActionTypes.DATA_NEXT_LOADED,
payload: Object.assign({ page: currentPage, contributors: [...state.contributors, ...res.results], next: res.next, total: res.count, componentLoaded: true }, (offset && state.contributors.length === 0 ? { previous: res.previous } : {})),
});
onChangePage && onChangePage(currentPage);
}
})
.catch((error) => {
utils_1.Logger.error(Errors_1.SCOPE_SC_CORE, error);
})
.then(() => {
if (isMountedRef.current && cacheStrategy === utils_1.CacheStrategies.STALE_WHILE_REVALIDATE) {
revalidate(state.next, true);
}
});
}
}
/**
* Reset contributors status on change pageSize, offset
*/
(0, react_1.useEffect)(() => {
if (isMountedRef.current && state.componentLoaded && Boolean(obj) && !state.reload) {
dispatch({
type: exports.contributorsObjectActionTypes.DATA_RELOAD,
payload: {
next: getNextUrl(),
},
});
}
}, [objId, pageSize, offset, isMountedRef]);
/**
* Reload fetch contributors
*/
(0, react_1.useEffect)(() => {
if (isMountedRef.current && state.componentLoaded && state.reload && !state.isLoadingNext && !state.isLoadingPrevious) {
dispatch({
type: exports.contributorsObjectActionTypes.DATA_RELOADED,
});
getNextPage();
}
}, [state.reload, isMountedRef]);
return Object.assign(Object.assign({ feedObject: obj, setFeedObject: setObj }, state), { pageSize,
getNextPage,
getPreviousPage });
}
exports.default = useSCFetchContributors;