UNPKG

@etsoo/react

Version:

TypeScript ReactJs UI Independent Framework

81 lines (80 loc) 2.91 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.UserState = exports.UserActionType = void 0; const shared_1 = require("@etsoo/shared"); const State_1 = require("./State"); /** * User action type * Style like 'const enum' will remove definition of the enum and cause module errors */ var UserActionType; (function (UserActionType) { // Login UserActionType["Login"] = "LOGIN"; // Logout UserActionType["Logout"] = "LOGOUT"; // Update UserActionType["Update"] = "UPDATE"; // Unauthorized UserActionType["Unauthorized"] = "UNAUTHORIZED"; })(UserActionType || (exports.UserActionType = UserActionType = {})); /** * User state */ class UserState { /** * Constructor */ constructor() { const { context, provider } = State_1.State.create((state, action) => { // User reducer switch (action.type) { case UserActionType.Login: const lastChangedFields = state.authorized && action.user ? this.getChangedFields(action.user, state) : undefined; return { ...action.user, authorized: true, lastChangedFields }; case UserActionType.Logout: return { ...state, // Keep other user data lastChangedFields: undefined, token: undefined, // Remove token authorized: false // Flag as unauthorized }; case UserActionType.Update: if (action.update) { var newState = { ...state }; action.update(newState); newState.lastChangedFields = this.getChangedFields(newState, state); return newState; } return state; case UserActionType.Unauthorized: // Avoid multiple updates (For example, multiple API calls failed with 405) if (state.authorized === false) return state; return { ...state, // Keep other user data and token for refresh lastChangedFields: undefined, authorized: false // Flag as unauthorized }; default: return state; } }, {}, {}); this.context = context; this.provider = provider; } getChangedFields(input, init) { return shared_1.Utils.objectUpdated(input, init, [ "authorized", "seconds", "lastChangedFields" ]); } } exports.UserState = UserState;