UNPKG

@etsoo/react

Version:

TypeScript ReactJs UI Independent Framework

77 lines (76 loc) 2.71 kB
import { Utils } from "@etsoo/shared"; import { State } from "./State"; /** * User action type * Style like 'const enum' will remove definition of the enum and cause module errors */ export var UserActionType; (function (UserActionType) { // Login UserActionType["Login"] = "LOGIN"; // Logout UserActionType["Logout"] = "LOGOUT"; // Update UserActionType["Update"] = "UPDATE"; // Unauthorized UserActionType["Unauthorized"] = "UNAUTHORIZED"; })(UserActionType || (UserActionType = {})); /** * User state */ export class UserState { /** * Constructor */ constructor() { const { context, provider } = 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 Utils.objectUpdated(input, init, [ "authorized", "seconds", "lastChangedFields" ]); } }