blob: ce80d60603c86ab844858ca9fa3b03f3f95a475f [file] [log] [blame]
Copybara854996b2021-09-07 19:36:02 +00001// Copyright 2019 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5export const createReducer = (initialState, handlers) => {
6 return function reducer(state = initialState, action) {
7 if (handlers.hasOwnProperty(action.type)) {
8 return handlers[action.type](state, action);
9 } else {
10 return state;
11 }
12 };
13};
14
15const DEFAULT_REQUEST_KEY = '*';
16
17export const createKeyedRequestReducer = (start, success, failure) => {
18 return createReducer({}, {
19 [start]: (state, {requestKey = DEFAULT_REQUEST_KEY}) => {
20 return {
21 ...state,
22 [requestKey]: {
23 requesting: true,
24 error: null,
25 },
26 };
27 },
28 [success]: (state, {requestKey = DEFAULT_REQUEST_KEY}) =>{
29 return {
30 ...state,
31 [requestKey]: {
32 requesting: false,
33 error: null,
34 },
35 };
36 },
37 [failure]: (state, {requestKey = DEFAULT_REQUEST_KEY, error}) => {
38 return {
39 ...state,
40 [requestKey]: {
41 requesting: false,
42 error,
43 },
44 };
45 },
46 });
47};
48
49export const createRequestReducer = (start, success, failure) => {
50 return createReducer({requesting: false, error: null}, {
51 [start]: (_state, _action) => ({
52 requesting: true,
53 error: null,
54 }),
55 [success]: (_state, _action) =>({
56 requesting: false,
57 error: null,
58 }),
59 [failure]: (_state, {error}) => ({
60 requesting: false,
61 error,
62 }),
63 });
64};