aboutsummaryrefslogtreecommitdiff
path: root/src/client/react/users.ts
blob: a16e40f4c597638056e07e98b257e856483a09cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/* global USERS */

import { combineReducers, createStore } from 'redux';
import { AnyAction } from 'redux';
import { Reducer } from 'redux';
import { ReducersMapObject } from 'redux';

export interface User {
  type: string,
  value: string,
  id: string,
}

type Action = {
  type: 'USERS/ADD_USER',
  user: User,
}

declare global {
  interface Window {
    USERS: User[];
  }
}

const getId = ({ type, value }: User) => `${type}/${value}`;

type ByIdState = {
  [userId: string]: User,
}

const byId = (state: ByIdState = {}, action: Action): ByIdState => {
  switch (action.type) {
    case 'USERS/ADD_USER':
      return {
        ...state,
        [action.user.id]: {
          ...action.user,
        },
      };
    default:
      return state;
  }
};

type AllIdsState = string[]

const allIds = (state: AllIdsState = [], action: Action): AllIdsState => {
  switch (action.type) {
    case 'USERS/ADD_USER':
      return [
        ...state,
        action.user.id,
      ];
    default:
      return state;
  }
};

type AllUsersState = User[];

const allUsers = (state: AllUsersState = [], action: Action): AllUsersState => {
  switch (action.type) {
    case 'USERS/ADD_USER':
      return [
        ...state,
        {
          ...action.user,
        },
      ];
    default:
      return state;
  }
};

interface State {
  byId: ByIdState,
  allIds: AllIdsState,
  allUsers: AllUsersState,
}

const store = createStore(combineReducers<State>({
  byId,
  allIds,
  allUsers,
}));

window.USERS.forEach((user) => {
  store.dispatch({
    type: 'USERS/ADD_USER',
    user: {
      type: user.type,
      value: user.value,
      id: getId(user),
    },
  });
});

const users = store.getState();

export default users;