Skip to content

Commit

Permalink
start removing redux
Browse files Browse the repository at this point in the history
  • Loading branch information
edolix committed Apr 3, 2023
1 parent c8efd77 commit d5b4983
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 110 deletions.
33 changes: 1 addition & 32 deletions packages/core/src/redux/connect.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { configureJestStore } from '../testUtils'
import { BaseComponent } from '../BaseComponent'
import { connect } from './connect'
import { componentActions, sessionActions } from './features'
import { componentActions } from './features'
import { EventEmitter } from '../utils/EventEmitter'
import { SDKStore } from './'

Expand All @@ -10,34 +10,16 @@ describe('Connect', () => {
let instance: any
let updateStateAction: any
let updateRemoteSDPAction: any
const mockOnRemoteSDP = jest.fn()

Object.defineProperties(BaseComponent.prototype, {
onAuth: {
value: jest.fn(),
},
checkRaceOne: {
value: jest.fn(),
},
checkRaceTwo: {
value: jest.fn(),
},
})

beforeEach(() => {
store = configureJestStore()
instance = connect({
store,
sessionListeners: {
authStatus: 'onAuth',
},
Component: BaseComponent,
})({
emitter: new EventEmitter(),
})
instance.onAuth.mockClear()
instance.emit = jest.fn()
mockOnRemoteSDP.mockClear()

updateStateAction = componentActions.upsert({
id: instance.__uuid,
Expand All @@ -64,17 +46,4 @@ describe('Connect', () => {
store.dispatch(updateRemoteSDPAction)
expect(instance.emit).not.toHaveBeenCalled()
})

it('should invoke the function within sessionListeners', () => {
store.dispatch(sessionActions.authStatus('authorized'))

expect(instance.onAuth).toHaveBeenCalledTimes(1)
expect(instance.onAuth).toHaveBeenCalledWith({
protocol: '',
iceServers: [],
authStatus: 'authorized',
authError: undefined,
authCount: 0,
})
})
})
48 changes: 2 additions & 46 deletions packages/core/src/redux/connect.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,13 @@
import { SessionState, CustomSaga } from './interfaces'
import { CustomSaga } from './interfaces'
import { SDKStore } from './'
import { getSession } from './features/session/sessionSelectors'
import type { BaseComponent } from '../BaseComponent'
import { EventEmitter } from '../utils/EventEmitter'

type SessionEventHandler = (session: SessionState) => unknown
interface Connect<T> {
sessionListeners?: Partial<
Record<ReduxSessionKeys, string | SessionEventHandler>
>
store: SDKStore
Component: new (o: any) => T
customSagas?: Array<CustomSaga<T>>
}
type ReduxSessionKeys = keyof SessionState

export const connect = <
EventTypes extends EventEmitter.ValidEventTypes,
Expand All @@ -28,55 +22,17 @@ export const connect = <
>(
options: Connect<T>
) => {
const { sessionListeners = {}, store, Component, customSagas = [] } = options
const sessionKeys = Object.keys(sessionListeners) as ReduxSessionKeys[]
const { store, Component, customSagas = [] } = options

return (userOptions: any): TargetType => {
const instance = new Component({ ...userOptions, store })
const cacheMap = new Map<string, any>()
/**
* Stop the execution of the redux listeners if `destroyer`
* below was called in the meantime.
*/
let run = true

const storeUnsubscribe = store.subscribe(() => {
const state = store.getState()

const session = getSession(state)
for (const reduxKey of sessionKeys) {
if (run === false) {
return
}
const cacheKey = `session.${reduxKey}`
const current = cacheMap.get(cacheKey)
const updatedValue = session[reduxKey]

if (updatedValue !== undefined && current !== updatedValue) {
cacheMap.set(cacheKey, updatedValue)
const fnName = sessionListeners[reduxKey]

if (typeof fnName === 'string') {
// FIXME: proper types for fnName
// @ts-ignore
instance[fnName](session)
} else if (typeof fnName === 'function') {
fnName(session)
}
}
}
})

// Run all the custom sagas
const taskList = customSagas?.map((saga) => {
return store.runSaga(saga, { instance, runSaga: store.runSaga })
})

instance.destroyer = () => {
run = false
storeUnsubscribe()
cacheMap.clear()

// Cancel all the custom sagas
if (taskList?.length) {
taskList.forEach((task) => task.cancel())
Expand Down
35 changes: 4 additions & 31 deletions packages/core/src/redux/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
import { Store } from 'redux'
import createSagaMiddleware, {
channel,
multicastChannel,
Saga,
Task,
} from '@redux-saga/core'
import { configureStore as rtConfigureStore } from './toolkit'
import { rootReducer } from './rootReducer'
import { channel, multicastChannel, Saga, Task } from '@redux-saga/core'
// import { configureStore as rtConfigureStore } from './toolkit'
import rootSaga from './rootSaga'
import {
PubSubChannel,
Expand Down Expand Up @@ -44,7 +37,6 @@ const configureStore = (options: ConfigureStoreOptions) => {
preloadedState = {},
runSagaMiddleware = true,
} = options
const sagaMiddleware = createSagaMiddleware()
const rootChannel: PubSubChannel = multicastChannel()
const pubSubChannel: PubSubChannel = multicastChannel()
const swEventChannel: SwEventChannel = multicastChannel()
Expand All @@ -59,20 +51,8 @@ const configureStore = (options: ConfigureStoreOptions) => {
swEventChannel,
sessionChannel,
}
const store = rtConfigureStore({
devTools: userOptions?.devTools ?? true,
reducer: rootReducer,
preloadedState,
middleware: (getDefaultMiddleware) =>
// It is preferrable to use the chainable .concat(...) and
// .prepend(...) methods of the returned MiddlewareArray instead
// of the array spread operator, as the latter can lose valuable
// type information under some circumstances.
// @see https://redux-toolkit.js.org/api/getDefaultMiddleware#intended-usage
getDefaultMiddleware().concat(sagaMiddleware),
}) as Store

const swStore = createSWStore({ channels })
const swStore = createSWStore({ channels, preloadedState })

let session: BaseSession
const initSession = () => {
Expand Down Expand Up @@ -121,16 +101,9 @@ const configureStore = (options: ConfigureStoreOptions) => {
}

return {
...store,
...swStore,
runSaga,
channels,
dispatch: (action: any) => {
return swStore.dispatch(action)
},
getState: () => {
return swStore.getState()
// return store.getState()
},
}
}

Expand Down
7 changes: 6 additions & 1 deletion packages/core/src/redux/swStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,13 @@ import { AnyAction } from './toolkit'

interface CreateSwStoreParams {
channels: InternalChannels
preloadedState: Partial<SDKState>
}

export const createSWStore = ({ channels }: CreateSwStoreParams) => {
export const createSWStore = ({
channels,
preloadedState,
}: CreateSwStoreParams) => {
const logger = getLogger()
let rootTask: Task
const state: SDKState = {
Expand All @@ -24,6 +28,7 @@ export const createSWStore = ({ channels }: CreateSwStoreParams) => {
authError: undefined,
authCount: 0,
},
...preloadedState,
}

const getState = () => {
Expand Down

0 comments on commit d5b4983

Please sign in to comment.