UNPKG

@twreporter/redux

Version:

redux actions and reducers for twreporter website

356 lines (343 loc) 15.1 kB
"use strict"; function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } Object.defineProperty(exports, "__esModule", { value: true }); exports.createSingleBookmark = createSingleBookmark; exports.deleteSingleBookmark = deleteSingleBookmark; exports.getMultipleBookmarks = getMultipleBookmarks; exports.getSingleBookmark = getSingleBookmark; var _url = require("../utils/url"); var _apiConfig = _interopRequireDefault(require("../constants/api-config")); var _errorActionCreators = _interopRequireDefault(require("./error-action-creators")); var _reduxStateFieldNames = _interopRequireDefault(require("../constants/redux-state-field-names")); var _actionTypes = _interopRequireDefault(require("../constants/action-types")); var _get = _interopRequireDefault(require("lodash/get")); var _excluded = ["published_date"]; // lodash function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } var _ = { get: _get["default"] }; var apiTimeout = _apiConfig["default"].timeout; /** * @typedef {Object} userData * @property {string} email - email of user * @property {string} id - id of user * @property {string} jwt - json web token issued by backend for this certain user */ /** * https://github.com/twreporter/go-api#get-bookmarks * https://github.com/twreporter/go-api/blob/master/models/bookmark.go * @typedef {Object} Bookmark * @property {number} id * @property {string} created_at * @property {string} updated_at * @property {string} deleted_at * @property {number} published_date * @property {string} slug * @property {string} host_name * @property {string} is_external * @property {string} title * @property {string} desc * @property {string} thumbnail */ /** * https://github.com/twreporter/go-api#create-a-bookmark * https://github.com/twreporter/go-api/blob/master/models/bookmark.go * @typedef {Object} BookmarkToBeCreated * @property {string} slug * @property {string} host * @property {string} is_external * @property {string} title * @property {string} desc * @property {string} thumbnail * @property {string} published_date * @property {string} post_id */ /** * @typedef {Object} RequestAction * @property {string} type - The type of action * @property {string} payload.method - The HTTP request method * @property {string} payload.url - The target to send request * @property {Object} payload.body - The request body with POST, PUT, DELETE, or PATCH request * @property {Object} payload.headers - The request header */ /** * @typedef {Object} SuccessAction * @property {string} type - The type of action * @property {string} payload * @property {Object} payload.data - Response data * @property {Object} payload.headers - The response header * @property {string} payload.statusCode - Response status code * @property {Object} payload.config - details of response */ /** * @param {Object} axiosResponse * @param {string} actionType * @returns {SuccessAction} */ function buildSuccessActionFromRes(axiosResponse, actionType) { return { type: actionType, payload: { config: _.get(axiosResponse, 'config'), data: _.get(axiosResponse, 'data'), headers: _.get(axiosResponse, 'headers'), statusCode: _.get(axiosResponse, 'status') } }; } /** * @typedef {Object} FailAction * @property {string} type - Action error type * @property {string} payload * @property {string} payload.statusCode - Response status code * @property {string} payload.message - Error message * @property {object} payload.error - Error object */ /** * * * @export * @param {string} jwt - access_token granted for the user * @param {number} userID - id of user * @param {BookmarkToBeCreated} bookmarkToBeCreated * @return {Function} - function will be executed in Redux Thunk middleware */ function createSingleBookmark(jwt, userID, bookmarkToBeCreated) { /* go-api takes `published_date` as an unix timestamp (in secs) int */ // eslint-disable-next-line camelcase var published_date = bookmarkToBeCreated.published_date, passedBookmarkProperties = _objectWithoutProperties(bookmarkToBeCreated, _excluded); /** * @param {Function} dispatch - Redux store dispatch function * @param {Function} getState - Redux store getState function * @param {Object} option * @param {Object} option.httpClientWithToken * @return {Promise} resolve with success action or reject with fail action */ return function (dispatch, getState, _ref) { var httpClientWithToken = _ref.httpClientWithToken; var state = getState(); var apiOrigin = _.get(state, [_reduxStateFieldNames["default"].origins, 'api']); var url = (0, _url.formURL)(apiOrigin, "/v1/users/".concat(userID, "/bookmarks"), {}, false); var axiosConfig = { timeout: apiTimeout, headers: { 'Content-Type': 'application/json', Authorization: "Bearer ".concat(jwt) } }; var interceptor = httpClientWithToken.interceptors.request.use(function (config) { var method = config.method, url = config.url, headers = config.headers, data = config.data; dispatch({ type: _actionTypes["default"].singleBookmark.create.request, payload: { method: method, url: url, headers: headers, body: data } }); httpClientWithToken.interceptors.request.eject(interceptor); return config; }); return httpClientWithToken.post(url, _objectSpread({ published_date: Math.ceil(new Date(published_date).getTime() / 1000) }, passedBookmarkProperties), axiosConfig).then(function (res) { var successAction = buildSuccessActionFromRes(res, _actionTypes["default"].singleBookmark.create.success); dispatch(successAction); return successAction; })["catch"](function (error) { var failAction = _errorActionCreators["default"].axios(error, _actionTypes["default"].singleBookmark.create.failure); dispatch(failAction); return Promise.reject(failAction); }); }; } /** * * * @export * @param {string} jwt - access_token granted for the user * @param {number} userID - id of user * @param {number} offset - the offset of the request * @param {number} limit - max amount of records per fetch * @return {Function} - function will be executed in Redux Thunk middleware */ function getMultipleBookmarks(jwt, userID, offset, limit) { /** * @param {Function} dispatch - Redux store dispatch function * @param {Function} getState - Redux store getState function * @param {Object} option * @param {Object} option.httpClientWithToken * @return {Promise} resolve with success action or reject with fail action */ return function (dispatch, getState, _ref2) { var httpClientWithToken = _ref2.httpClientWithToken; var state = getState(); var apiOrigin = _.get(state, [_reduxStateFieldNames["default"].origins, 'api']); var url = (0, _url.formURL)(apiOrigin, "/v1/users/".concat(userID, "/bookmarks"), { offset: offset, limit: limit }, false); var axiosConfig = { timeout: apiTimeout, headers: { Authorization: "Bearer ".concat(jwt) } }; var interceptor = httpClientWithToken.interceptors.request.use(function (config) { var method = config.method, url = config.url, headers = config.headers, data = config.data; dispatch({ type: _actionTypes["default"].multipleBookMarks.read.request, payload: { method: method, url: url, headers: headers, body: data } }); httpClientWithToken.interceptors.request.eject(interceptor); return config; }); return httpClientWithToken.get(url, axiosConfig).then(function (res) { var successAction = buildSuccessActionFromRes(res, _actionTypes["default"].multipleBookMarks.read.success); dispatch(successAction); return successAction; })["catch"](function (error) { var failAction = _errorActionCreators["default"].axios(error, _actionTypes["default"].multipleBookMarks.read.failure); dispatch(failAction); return Promise.reject(failAction); }); }; } /** * * * @export * @param {string} jwt - access_token granted for the user * @param {number} userID - id of user * @param {string} bookmarkSlug - the article slug of the bookmark. Ex: xxx-xxx-xxxxxxx-xx * @param {string} bookmarkHost - the hostname of the bookmark. Ex: 'https://www.xxxx.xx' * @return {Function} - function will be executed in Redux Thunk middleware */ function getSingleBookmark(jwt, userID, bookmarkSlug, bookmarkHost) { /** * @param {Function} dispatch - Redux store dispatch function * @param {Function} getState - Redux store getState function * @param {Object} option * @param {Object} option.httpClientWithToken * @return {Promise} resolve with success action or reject with fail action */ return function (dispatch, getState, _ref3) { var httpClientWithToken = _ref3.httpClientWithToken; var state = getState(); var apiOrigin = _.get(state, [_reduxStateFieldNames["default"].origins, 'api']); var url = (0, _url.formURL)(apiOrigin, "/v1/users/".concat(userID, "/bookmarks/").concat(bookmarkSlug), { host: bookmarkHost }, false); var axiosConfig = { timeout: apiTimeout, headers: { Authorization: "Bearer ".concat(jwt) } }; var interceptor = httpClientWithToken.interceptors.request.use(function (config) { var method = config.method, url = config.url, headers = config.headers, data = config.data; dispatch({ type: _actionTypes["default"].singleBookmark.read.request, payload: { method: method, url: url, headers: headers, body: data } }); httpClientWithToken.interceptors.request.eject(interceptor); return config; }); return httpClientWithToken.get(url, axiosConfig).then(function (res) { var successAction = buildSuccessActionFromRes(res, _actionTypes["default"].singleBookmark.read.success); dispatch(successAction); return successAction; })["catch"](function (error) { var failAction = _errorActionCreators["default"].axios(error, _actionTypes["default"].singleBookmark.read.failure); dispatch(failAction); return Promise.reject(failAction); }); }; } /** * * * @export * @param {string} jwt - access_token granted for the user * @param {number} userID - id of user * @param {number} bookmarkID - id of bookmark * @return {Function} - function will be executed in Redux Thunk middleware */ function deleteSingleBookmark(jwt, userID, bookmarkID) { /** * @param {Function} dispatch - Redux store dispatch function * @param {Function} getState - Redux store getState function * @param {Object} option * @param {Object} option.httpClientWithToken * @return {Promise} resolve with success action or reject with fail action */ return function (dispatch, getState, _ref4) { var httpClientWithToken = _ref4.httpClientWithToken; var state = getState(); var apiOrigin = _.get(state, [_reduxStateFieldNames["default"].origins, 'api']); var url = (0, _url.formURL)(apiOrigin, "/v1/users/".concat(userID, "/bookmarks/").concat(bookmarkID), {}, false); var axiosConfig = { timeout: apiTimeout, headers: { Authorization: "Bearer ".concat(jwt) } }; var interceptor = httpClientWithToken.interceptors.request.use(function (config) { var method = config.method, url = config.url, headers = config.headers, data = config.data; dispatch({ type: _actionTypes["default"].singleBookmark["delete"].request, payload: { method: method, url: url, headers: headers, body: data } }); httpClientWithToken.interceptors.request.eject(interceptor); return config; }); return httpClientWithToken["delete"](url, axiosConfig).then(function (res) { var successAction = buildSuccessActionFromRes(res, _actionTypes["default"].singleBookmark["delete"].success); successAction.payload.bookmarkID = bookmarkID; dispatch(successAction); return successAction; })["catch"](function (error) { var failAction = _errorActionCreators["default"].axios(error, _actionTypes["default"].singleBookmark["delete"].failure); dispatch(failAction); return Promise.reject(failAction); }); }; }