Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: createSlice() revision proposal #109

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
174 changes: 64 additions & 110 deletions src/createSlice.test.ts
Original file line number Diff line number Diff line change
@@ -1,130 +1,84 @@
import { createSlice } from './createSlice'
import { createAction } from './createAction'
import { createAction, PayloadAction } from './createAction'

describe('createSlice', () => {
describe('when slice is empty', () => {
const { actions, reducer, selectors } = createSlice({
reducers: {
increment: state => state + 1,
multiply: (state, action) => state * action.payload
},
initialState: 0
})

it('should create increment action', () => {
expect(actions.hasOwnProperty('increment')).toBe(true)
})

it('should create multiply action', () => {
expect(actions.hasOwnProperty('multiply')).toBe(true)
})

it('should have the correct action for increment', () => {
expect(actions.increment()).toEqual({
type: 'increment',
payload: undefined
})
})

it('should have the correct action for multiply', () => {
expect(actions.multiply(3)).toEqual({
type: 'multiply',
payload: 3
})
})

describe('when using reducer', () => {
it('should return the correct value from reducer with increment', () => {
expect(reducer(undefined, actions.increment())).toEqual(1)
})

it('should return the correct value from reducer with multiply', () => {
expect(reducer(2, actions.multiply(3))).toEqual(6)
})
})

describe('when using selectors', () => {
it('should create selector with correct name', () => {
expect(selectors.hasOwnProperty('getState')).toBe(true)
})

it('should return the slice state data', () => {
expect(selectors.getState(2)).toEqual(2)
})
})
const slice = createSlice({
name: 'counter',
initialState: 0,
actions: {
increment: state => state + 1,
multiply: (state, { payload }: PayloadAction<number>) => state * payload
}
})

describe('when passing slice', () => {
const { actions, reducer, selectors } = createSlice({
reducers: {
increment: state => state + 1
},
initialState: 0,
slice: 'cool'
})

it('should create increment action', () => {
expect(actions.hasOwnProperty('increment')).toBe(true)
})

it('should have the correct action for increment', () => {
expect(actions.increment()).toEqual({
type: 'cool/increment',
payload: undefined
})
})
it('should create action creators for `actions`', () => {
expect(slice.actions).toHaveProperty('increment')
expect(slice.actions).toHaveProperty('multiply')
})

it('should return the correct value from reducer', () => {
expect(reducer(undefined, actions.increment())).toEqual(1)
})
it('should namespace action types', () => {
expect(slice.actions.increment().type).toBe('counter/increment')
expect(slice.actions.multiply(2).type).toBe('counter/multiply')
})

it('should create selector with correct name', () => {
expect(selectors.hasOwnProperty('getCool')).toBe(true)
})
it('should support action payloads', () => {
expect(slice.actions.multiply(2).payload).toBe(2)
})

it('should return the slice state data', () => {
expect(selectors.getCool({ cool: 2 })).toEqual(2)
})
it('should not generate action creators for `extraReducers`', () => {
expect(slice.actions).not.toHaveProperty('RESET_APP')
})

describe('when mutating state object', () => {
const initialState = { user: '' }
it('should apply case reducers passed in `actions`', () => {
const state1 = slice(undefined, slice.actions.increment())
const state2 = slice(state1, slice.actions.multiply(3))
expect(state1).toBe(1)
expect(state2).toBe(3)
})
})

const { actions, reducer } = createSlice({
reducers: {
setUserName: (state, action) => {
state.user = action.payload
}
},
initialState,
slice: 'user'
})
describe('when mutating state object', () => {
const initialState = { user: '' }

const slice = createSlice({
name: 'user',
actions: {
setUserName: (state, action) => {
state.user = action.payload
}
},
initialState
})

it('should set the username', () => {
expect(reducer(initialState, actions.setUserName('eric'))).toEqual({
user: 'eric'
})
it('should set the username', () => {
expect(slice(initialState, slice.actions.setUserName('eric'))).toEqual({
user: 'eric'
})
})
})

describe('when passing extra reducers', () => {
const addMore = createAction('ADD_MORE')
describe('when passing extra reducers', () => {
const addMore = createAction('ADD_MORE')

const slice = createSlice({
name: 'counter',
actions: {
increment: state => state + 1,
multiply: (state, action) => state * action.payload
},
extraReducers: {
[addMore.type]: (state, action) => state + action.payload.amount
},
initialState: 0
})

const { reducer } = createSlice({
reducers: {
increment: state => state + 1,
multiply: (state, action) => state * action.payload
},
extraReducers: {
[addMore.type]: (state, action) => state + action.payload.amount
},
initialState: 0
})
it('should call extra reducers when their actions are dispatched', () => {
const result = slice(10, addMore({ amount: 5 }))

it('should call extra reducers when their actions are dispatched', () => {
const result = reducer(10, addMore({ amount: 5 }))
expect(result).toBe(15)
})

expect(result).toBe(15)
})
it('should not generate action creators for extra reducers ', () => {
expect(slice.actions).not.toHaveProperty('RESET_APP')
})
})
101 changes: 49 additions & 52 deletions src/createSlice.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,31 @@
import { Action, AnyAction, Reducer } from 'redux'
import { createAction, PayloadAction } from './createAction'
import { createReducer, CaseReducersMapObject } from './createReducer'
import { createSliceSelector, createSelectorName } from './sliceSelector'

/**
* An action creator atttached to a slice.
*/
export type SliceActionCreator<P> = (payload: P) => PayloadAction<P>

/**
* A "slice" is a reducer with attached set of action creators. Each of the
* corresponding action types is considered to be "owned" by the slice, and
* is namespaced with the slice's name.
*/
export interface Slice<
S = any,
A extends Action = AnyAction,
AP extends { [key: string]: any } = { [key: string]: any }
> {
/**
* The slice name.
*/
slice: string

> extends Reducer<S, A> {
/**
* The slice's reducer.
* The slice's name. Used as namespace for the slice's action types.
*/
reducer: Reducer<S, A>
sliceName: string

/**
* Action creators for the types of actions that are handled by the slice
* reducer.
* The action creators for the action types "owned" by the slice.
*/
actions: { [type in keyof AP]: SliceActionCreator<AP[type]> }

/**
* Selectors for the slice reducer state. `createSlice()` inserts a single
* selector that returns the entire slice state and whose name is
* automatically derived from the slice name (e.g., `getCounter` for a slice
* named `counter`).
*/
selectors: { [key: string]: (state: any) => S }
}

/**
Expand All @@ -48,32 +38,34 @@ export interface CreateSliceOptions<
CR2 extends CaseReducersMapObject<S, A> = CaseReducersMapObject<S, A>
> {
/**
* The slice's name. Used to namespace the generated action types and to
* name the selector for retrieving the reducer's state.
* The slice's name. Used to namespace the generated action types.
*/
slice?: string
name: string

/**
* The initial state to be returned by the slice reducer.
*/
initialState: S

/**
* A mapping from action types to action-type-specific *case reducer*
* functions. For every action type, a matching action creator will be
* generated using `createAction()`.
* An object whose keys are names of actions to generate action
* creators for, and whose values are *case reducers* to handle
* these actions. The latter are passed to `createReducer()`
* (together with the case reducers from `extraReducers`, if
* specified) to generate the slice reducer.
*/
reducers: CR
actions: CR

/**
* A mapping from action types to action-type-specific *case reducer*
* functions. These reducers should have existing action types used
* as the keys, and action creators will _not_ be generated.
* functions. No action creators are generated for these action types.
* The case reducers are passed to `createReducer()` (together with
* the ones from `actions`) to generate the slice reducer.
*/
extraReducers?: CR2
}

type ExtractPayloads<
type CaseReducerActionPayloads<
S,
A extends PayloadAction,
CR extends CaseReducersMapObject<S, A>
Expand All @@ -85,7 +77,7 @@ type ExtractPayloads<
: never)
}

function getType(slice: string, actionKey: string): string {
function getSliceActionType(slice: string, actionKey: string): string {
return slice ? `${slice}/${actionKey}` : actionKey
}

Expand All @@ -103,36 +95,41 @@ export function createSlice<
CR extends CaseReducersMapObject<S, A> = CaseReducersMapObject<S, A>
>(
options: CreateSliceOptions<S, A, CR>
): Slice<S, A, ExtractPayloads<S, A, CR>> {
const { slice = '', initialState } = options
const reducers = options.reducers || {}
): Slice<S, A, CaseReducerActionPayloads<S, A, CR>> {
const { name, initialState } = options
const actionCaseReducers = options.actions || {}
const extraReducers = options.extraReducers || {}
const actionKeys = Object.keys(reducers)

const reducerMap = actionKeys.reduce((map, actionKey) => {
map[getType(slice, actionKey)] = reducers[actionKey]
return map
}, extraReducers)

const reducer = createReducer(initialState, reducerMap)
if (!name) {
throw new Error('Missing slice name')
}

const actionMap = actionKeys.reduce(
const actionNames = Object.keys(actionCaseReducers)

const reducer = createReducer(initialState, {
...extraReducers,
...actionNames.reduce(
(map, actionName) => {
const actionType = getSliceActionType(name, actionName)
const caseReducer = actionCaseReducers[actionName]
map[actionType] = caseReducer
return map
},
{} as CaseReducersMapObject<S, A>
)
})

const actions = actionNames.reduce(
(map, action) => {
const type = getType(slice, action)
const type = getSliceActionType(name, action)
map[action] = createAction(type)
return map
},
{} as any
)

const selectors = {
[createSelectorName(slice)]: createSliceSelector(slice)
}

return {
slice,
reducer,
actions: actionMap,
selectors
}
return Object.assign(reducer, {
sliceName: name,
actions
})
}
9 changes: 0 additions & 9 deletions src/sliceSelector.test.ts

This file was deleted.

Loading