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

feat(packages/sui-pde): add getDecision function #1869

Merged
merged 2 commits into from
Nov 13, 2024
Merged
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
11 changes: 11 additions & 0 deletions packages/sui-pde/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,17 @@ const MyComponent = () => {
}
```

And the function to call elsewhere, like getInitialProps:

```js
import {getDecision} from '@s-ui/pde'

Page.getInitialProps = async ({context}) => {
const {decide} = getDecision(pde)
const {enabled} = decide('ff_web_my_flag')
}
```

#### Attributes

You can pass additional attributes to refine your decision logic:
Expand Down
59 changes: 59 additions & 0 deletions packages/sui-pde/src/getDecision.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import {getPlatformStrategy} from './hooks/common/platformStrategies.js'

/**
* Function to call decide
* @param {object} pde
* @return {function}
*/
export default function getDecision(pde) {
if (!pde) {
throw new Error('[sui-pde: useDecision] sui-pde provider is required to work')
}

const decide = (name, {attributes, trackExperimentViewed, isEventDisabled, queryString, adapterId} = {}) => {
try {
const strategy = getPlatformStrategy({
customTrackExperimentViewed: trackExperimentViewed
})

const forced = strategy.getForcedValue({
key: name,
queryString
})

if (forced) {
if (['on', 'off'].includes(forced)) {
return {enabled: forced === 'on', flagKey: name}
}

return {enabled: true, flagKey: name, variationKey: forced}
}

const notificationId = pde.addDecideListener({
onDecide: ({type, decisionInfo: decision}) => {
const {ruleKey, variationKey, decisionEventDispatched} = decision

if (type === 'flag' && decisionEventDispatched) {
strategy.trackExperiment({variationName: variationKey, experimentName: ruleKey})
}
}
})

const data = strategy.decide({
pde,
name,
attributes,
adapterId,
isEventDisabled
})

pde.removeNotificationListener({notificationId})

return data
} catch (error) {
return {enabled: false, flagKey: name}
}
}

return {decide}
}
56 changes: 3 additions & 53 deletions packages/sui-pde/src/hooks/useDecisionCallback.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {useCallback, useContext} from 'react'

import PdeContext from '../contexts/PdeContext.js'
import {getPlatformStrategy} from './common/platformStrategies.js'
import getDecision from '../getDecision.js'

/**
* Hook to call decide
Expand All @@ -10,57 +10,7 @@ import {getPlatformStrategy} from './common/platformStrategies.js'
export default function useDecisionCallback() {
const {pde} = useContext(PdeContext)

if (pde === null) {
throw new Error('[sui-pde: useDecision] sui-pde provider is required to work')
}
const getDecisionCallback = useCallback(getDecision, [])

const decide = useCallback(
(name, {attributes, trackExperimentViewed, isEventDisabled, queryString, adapterId} = {}) => {
try {
const strategy = getPlatformStrategy({
customTrackExperimentViewed: trackExperimentViewed
})

const forced = strategy.getForcedValue({
key: name,
queryString
})

if (forced) {
if (['on', 'off'].includes(forced)) {
return {enabled: forced === 'on', flagKey: name}
}

return {enabled: true, flagKey: name, variationKey: forced}
}

const notificationId = pde.addDecideListener({
onDecide: ({type, decisionInfo: decision}) => {
const {ruleKey, variationKey, decisionEventDispatched} = decision

if (type === 'flag' && decisionEventDispatched) {
strategy.trackExperiment({variationName: variationKey, experimentName: ruleKey})
}
}
})

const data = strategy.decide({
pde,
name,
attributes,
adapterId,
isEventDisabled
})

pde.removeNotificationListener({notificationId})

return data
} catch (error) {
return {enabled: false, flagKey: name}
}
},
[]
)

return {decide}
return getDecisionCallback(pde)
}
1 change: 1 addition & 0 deletions packages/sui-pde/src/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export {default as PDE} from './pde.js'
export {default as getDecision} from './getDecision.js'
export {default as useFeature} from './hooks/useFeature.js'
export {default as PdeContext} from './contexts/PdeContext.js'
export {default as useExperiment} from './hooks/useExperiment.js'
Expand Down
54 changes: 54 additions & 0 deletions packages/sui-pde/test/common/getDecisionSpec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/* eslint-disable no-console */
import {expect} from 'chai'
import sinon from 'sinon'

import {descriptorsByEnvironmentPatcher} from '@s-ui/test/lib/descriptor-environment-patcher.js'

import {SESSION_STORAGE_KEY as PDE_CACHE_STORAGE_KEY} from '../../src/hooks/common/trackedEventsLocalCache.js'
import getDecision from '../../src/getDecision.js'

descriptorsByEnvironmentPatcher()

describe('getDecision function', () => {
afterEach(() => {
if (typeof window === 'undefined') return
window.sessionStorage.removeItem(PDE_CACHE_STORAGE_KEY)
})

describe('when no pde context is set', () => {
it('should throw an error', () => {
try {
getDecision()
} catch (error) {
expect(error).to.be.instanceOf(Error)
}
})
})

describe('when pde context is set', () => {
let decide, pde
const decision = {
variationKey: 'variation',
enabled: true,
variables: {},
ruleKey: 'rule',
flagKey: 'flag',
userContext: {},
reasons: []
}

before(() => {
const addDecideListener = ({onDecide}) =>
onDecide({type: 'flag', decisionInfo: {...decision, decisionEventDispatched: true}})
const removeNotificationListener = sinon.stub()

decide = () => decision
pde = {decide, addDecideListener, removeNotificationListener}
})

it('should return a decision', () => {
const {decide} = getDecision(pde)
expect(decide('flag')).to.deep.equal(decision)
})
})
})