@twreporter/redux
Version:
redux actions and reducers for twreporter website
154 lines (149 loc) • 5.75 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.fetchAuthorCollection = fetchAuthorCollection;
exports.fetchAuthorCollectionIfNeeded = fetchAuthorCollectionIfNeeded;
exports.requestAuthorCollection = requestAuthorCollection;
var _articleSchema = require("../schemas/article-schema");
var _humps = require("humps");
var _authorPage = require("../constants/author-page");
var _url = require("../utils/url");
var _normalizr = require("normalizr");
var _actionTypes = _interopRequireDefault(require("../constants/action-types"));
var _axios = _interopRequireDefault(require("axios"));
var _errorActionCreators = _interopRequireDefault(require("./error-action-creators"));
var _reduxStateFieldNames = _interopRequireDefault(require("../constants/redux-state-field-names"));
var _get = _interopRequireDefault(require("lodash/get"));
var _omit = _interopRequireDefault(require("lodash/omit"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
// lodash
var _ = {
get: _get["default"],
omit: _omit["default"]
};
function requestAuthorCollection(authorId) {
return {
type: _actionTypes["default"].FETCH_AUTHOR_COLLECTION_REQUEST,
payload: {
authorId: authorId
}
};
}
/**
* NormalizedData
* @typedef {Object} NormalizedData
* @property {Object} entities - flatten entity objects
* @property {string[]} result - an array of top entity ids
*/
/**
* ReceiveAuthorCollectionAction
*
* @typedef {Object} ReceiveAuthorCollectionAction
* @property {string} type - CONSTANTS.FETCH_AUTHOR_COLLECTION_SUCCESS
* @property {string} authorId
* @property {NormalizedData} normalizedData
* @property {number} currentPage
* @property {number} totalPages
* @property {number} totalResults
* @property {number} receivedAt
*/
function fetchAuthorCollection(_ref) {
var targetPage = _ref.targetPage,
authorId = _ref.authorId,
returnDelay = _ref.returnDelay;
/**
* @param {Function} dispatch - Redux store dispatch function
* @param {Function} getState - Redux store getState function
* @return {Promise} resolve with success action or reject with fail action
*/
return function (dispatch, getState) {
// eslint-disable-line no-unused-vars
var searchParas = {
limit: _authorPage.MAX_ARTICLES_PER_FETCH,
offset: targetPage * _authorPage.MAX_ARTICLES_PER_FETCH
};
var state = getState();
var apiOrigin = _.get(state, [_reduxStateFieldNames["default"].origins, 'api']);
var url = (0, _url.formURL)(apiOrigin, "/v2/authors/".concat(authorId, "/posts"), searchParas, false);
dispatch(requestAuthorCollection(authorId));
// Call our API server to fetch the data
return _axios["default"].get(url).then(function (_ref2) {
var data = _ref2.data;
var articles = _.get(data, 'data.records', {});
var offset = _.get(data, 'data.meta.offset', 0);
var limit = _.get(data, 'data.meta.limit', 10);
var total = _.get(data, 'data.meta.total', 0);
var receiveAuthorCollectionAction = {
type: _actionTypes["default"].FETCH_AUTHOR_COLLECTION_SUCCESS,
payload: {
authorId: authorId,
normalizedData: (0, _normalizr.normalize)((0, _humps.camelizeKeys)(articles), new _normalizr.schema.Array(_articleSchema.article)),
currentPage: Math.floor(offset / limit),
totalPages: Math.ceil(total / limit),
totalResults: total,
receivedAt: Date.now()
}
};
// delay for displaying loading spinner
if (returnDelay > 0) {
return new Promise(function (resolve) {
setTimeout(function () {
dispatch(receiveAuthorCollectionAction);
resolve(receiveAuthorCollectionAction);
}, returnDelay);
});
}
dispatch(receiveAuthorCollectionAction);
return receiveAuthorCollectionAction;
})["catch"](function (error) {
var failAction = _errorActionCreators["default"].axios(error, _actionTypes["default"].FETCH_AUTHOR_COLLECTION_FAILURE);
failAction.payload.authorId = authorId;
failAction.payload.failedAt = Date.now();
dispatch(failAction);
return Promise.reject(failAction);
});
};
}
function fetchAuthorCollectionIfNeeded(authorId) {
/**
* @param {Function} dispatch - Redux store dispatch function
* @param {Function} getState - Redux store getState function
* @return {Promise} resolve with success action or reject with fail action
*/
return function (dispatch, getState) {
var currentState = getState();
var articlesDataOfAnAuthor = _.get(currentState, ['articlesByAuthor', authorId], null);
// If state.articlesByAuthor[authorId] does not exist:
if (articlesDataOfAnAuthor === null) {
return dispatch(fetchAuthorCollection({
authorId: authorId,
targetPage: _authorPage.NUMBER_OF_FIRST_RESPONSE_PAGE,
returnDelay: 0
}));
}
// If state.articlesByAuthor[authorId] exists:
var currentPage = articlesDataOfAnAuthor.currentPage,
isFetching = articlesDataOfAnAuthor.isFetching,
hasMore = articlesDataOfAnAuthor.hasMore;
if (!isFetching && hasMore) {
return dispatch(fetchAuthorCollection({
authorId: authorId,
targetPage: currentPage + 1,
returnDelay: _authorPage.RETURN_DELAY_TIME
}));
}
var action = {
type: _actionTypes["default"].dataAlreadyExists,
payload: {
"function": fetchAuthorCollectionIfNeeded.name,
arguments: {
authorId: authorId
},
message: 'Author collection data already exists'
}
};
dispatch(action);
return Promise.resolve(action);
};
}