Skip to content

Commit

Permalink
feat: clean up di (#1181)
Browse files Browse the repository at this point in the history
Signed-off-by: Jason C. Leach <jason.leach@fullboar.ca>
  • Loading branch information
jleach committed Jul 3, 2024
1 parent f6d5eca commit 0fba088
Show file tree
Hide file tree
Showing 10 changed files with 111 additions and 94 deletions.
24 changes: 14 additions & 10 deletions packages/legacy/app/container-imp.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,29 @@
import { BaseLogger } from '@credo-ts/core'
import { Container, TokenMapping } from '@hyperledger/aries-bifold-core'
import { DependencyContainer } from 'tsyringe'

export class AppContainer implements Container {
private container: DependencyContainer
public constructor(bifoldContainer: Container) {
this.container = bifoldContainer.getContainer().createChildContainer()
private _container: DependencyContainer
private log?: BaseLogger

public constructor(bifoldContainer: Container, log?: BaseLogger) {
this._container = bifoldContainer.container.createChildContainer()
this.log = log
}

public get container(): DependencyContainer {
return this._container
}

public init(): Container {
// eslint-disable-next-line no-console
console.log(`Initializing App container`)
this.log?.info(`Initializing App container`)
// Here you can register any component to override components in core package
// Example: Replacing button in core with custom button
// this.container.registerInstance(TOKENS.COMP_BUTTON, Button)
return this
}

public resolve<K extends keyof TokenMapping>(token: K): TokenMapping[K] {
return this.container.resolve(token) as TokenMapping[K]
}

public getContainer(): DependencyContainer {
return this.container
return this._container.resolve(token) as TokenMapping[K]
}
}
99 changes: 53 additions & 46 deletions packages/legacy/core/App/container-api.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { BaseLogger } from '@credo-ts/core'
import { IndyVdrPoolConfig } from '@credo-ts/indy-vdr'
import { ProofRequestTemplate } from '@hyperledger/aries-bifold-verifier'
import { OCABundleResolverType } from '@hyperledger/aries-oca/build/legacy'
import { StackNavigationProp } from '@react-navigation/stack'
import React, { createContext, useContext } from 'react'
Expand All @@ -11,46 +12,58 @@ import Onboarding from './screens/Onboarding'
import { GenericFn } from './types/fn'
import { AuthenticateStackParams, ScreenOptionsType } from './types/navigators'

export enum PROOF_TOKENS {
GROUP_BY_REFERENT = 'proof.groupByReferant',
CRED_HELP_ACTION_OVERRIDES = 'proof.credHelpActionOverride',
}
export type FN_ONBOARDING_DONE = (
dispatch: React.Dispatch<ReducerAction<unknown>>,
navigation: StackNavigationProp<AuthenticateStackParams>
) => GenericFn

export enum SCREEN_TOKENS {
SCREEN_PREFACE = 'screen.preface',
SCREEN_TERMS = 'screen.terms',
SCREEN_ONBOARDING = 'screen.onboarding',
SCREEN_DEVELOPER = 'screen.developer',
SCREEN_ONBOARDING_ITEM = 'screen.onboarding.item',
}
export enum STACK_TOKENS {
STACK_ONBOARDING = 'stack.onboarding',
}
export enum FN_TOKENS {
FN_ONBOARDING_DONE = 'fn.onboardingDone',
}
type LoadStateFn = (dispatch: React.Dispatch<ReducerAction<unknown>>) => Promise<void>

export enum COMP_TOKENS {
COMP_BUTTON = 'comp.button',
}
type ProofRequestTemplateFn = (useDevTemplates: boolean) => Array<ProofRequestTemplate>

export enum SERVICE_TOKENS {
SERVICE_TERMS = 'screen.terms',
}
export const PROOF_TOKENS = {
GROUP_BY_REFERENT: 'proof.groupByReferant',
CRED_HELP_ACTION_OVERRIDES: 'proof.credHelpActionOverride',
} as const

export enum LOAD_STATE_TOKENS {
LOAD_STATE = 'state.load',
}
export const SCREEN_TOKENS = {
SCREEN_PREFACE: 'screen.preface',
SCREEN_TERMS: 'screen.terms',
SCREEN_ONBOARDING: 'screen.onboarding',
SCREEN_DEVELOPER: 'screen.developer',
SCREEN_ONBOARDING_ITEM: 'screen.onboarding.item',
} as const

export enum OBJECT_TOKENS {
OBJECT_ONBOARDINGCONFIG = 'object.onboarding-config',
}
export const STACK_TOKENS = {
STACK_ONBOARDING: 'stack.onboarding',
} as const

export enum UTILITY_TOKENS {
UTIL_LOGGER = 'utility.logger',
UTIL_OCA_RESOLVER = 'utility.oca-resolver',
UTIL_LEDGERS = 'utility.ledgers',
}
export const FN_TOKENS = {
FN_ONBOARDING_DONE: 'fn.onboardingDone',
} as const

export const COMP_TOKENS = {
COMP_BUTTON: 'comp.button',
} as const

export const SERVICE_TOKENS = {
SERVICE_TERMS: 'screen.terms',
} as const

export const LOAD_STATE_TOKENS = {
LOAD_STATE: 'state.load',
} as const

export const OBJECT_TOKENS = {
OBJECT_ONBOARDING_CONFIG: 'object.onboarding-config',
} as const

export const UTILITY_TOKENS = {
UTIL_LOGGER: 'utility.logger',
UTIL_OCA_RESOLVER: 'utility.oca-resolver',
UTIL_LEDGERS: 'utility.ledgers',
UTIL_PROOF_TEMPLATE: 'utility.proof-template',
} as const

export const TOKENS = {
...PROOF_TOKENS,
Expand All @@ -62,16 +75,9 @@ export const TOKENS = {
...LOAD_STATE_TOKENS,
...OBJECT_TOKENS,
...UTILITY_TOKENS,
}

export type FN_ONBOARDING_DONE = (
dispatch: React.Dispatch<ReducerAction<unknown>>,
navigation: StackNavigationProp<AuthenticateStackParams>
) => GenericFn

type FN_LOADSTATE = (dispatch: React.Dispatch<ReducerAction<unknown>>) => Promise<void>
} as const

export interface TokenMapping {
export type TokenMapping = {
[TOKENS.CRED_HELP_ACTION_OVERRIDES]: {
credDefIds: string[]
schemaIds: string[]
Expand All @@ -84,18 +90,19 @@ export interface TokenMapping {
[TOKENS.SCREEN_DEVELOPER]: React.FC
[TOKENS.SCREEN_ONBOARDING]: typeof Onboarding
[TOKENS.FN_ONBOARDING_DONE]: FN_ONBOARDING_DONE
[TOKENS.LOAD_STATE]: FN_LOADSTATE
[TOKENS.LOAD_STATE]: LoadStateFn
[TOKENS.COMP_BUTTON]: Button
[TOKENS.OBJECT_ONBOARDINGCONFIG]: ScreenOptionsType
[TOKENS.OBJECT_ONBOARDING_CONFIG]: ScreenOptionsType
[TOKENS.UTIL_LOGGER]: BaseLogger
[TOKENS.UTIL_OCA_RESOLVER]: OCABundleResolverType
[TOKENS.UTIL_LEDGERS]: IndyVdrPoolConfig[]
[TOKENS.UTIL_PROOF_TEMPLATE]: ProofRequestTemplateFn | undefined
}

export interface Container {
init(): Container
resolve<K extends keyof TokenMapping>(token: K): TokenMapping[K]
getContainer(): DependencyContainer
get container(): DependencyContainer
}

export const ContainerContext = createContext<Container | undefined>(undefined)
Expand Down
58 changes: 32 additions & 26 deletions packages/legacy/core/App/container-impl.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { BaseLogger } from '@credo-ts/core'
import { useProofRequestTemplates } from '@hyperledger/aries-bifold-verifier'
import { DefaultOCABundleResolver } from '@hyperledger/aries-oca/build/legacy'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { StackNavigationProp } from '@react-navigation/stack'
Expand Down Expand Up @@ -27,29 +29,37 @@ import {
Onboarding as StoreOnboardingState,
Tours as ToursState,
} from './types/state'

export class MainContainer implements Container {
public static readonly TOKENS = TOKENS
private container: DependencyContainer
public constructor(container: DependencyContainer) {
this.container = container
private _container: DependencyContainer
private log?: BaseLogger

public constructor(container: DependencyContainer, log?: BaseLogger) {
this._container = container
this.log = log
}

public get container(): DependencyContainer {
return this._container
}

public init(): Container {
// eslint-disable-next-line no-console
console.log(`Initializing Bifold container`)
this.container.registerInstance(TOKENS.SCREEN_PREFACE, Preface)
this.container.registerInstance(TOKENS.SCREEN_DEVELOPER, Developer)
this.container.registerInstance(TOKENS.SCREEN_TERMS, { screen: ScreenTerms, version: TermsVersion })
this.container.registerInstance(TOKENS.SCREEN_ONBOARDING, Onboarding)
this.container.registerInstance(TOKENS.STACK_ONBOARDING, OnboardingStack)
this.container.registerInstance(TOKENS.COMP_BUTTON, Button)
this.container.registerInstance(TOKENS.GROUP_BY_REFERENT, false)
this.container.registerInstance(TOKENS.CRED_HELP_ACTION_OVERRIDES, [])
this.container.registerInstance(TOKENS.OBJECT_ONBOARDINGCONFIG, DefaultScreenOptionsDictionary)
this.container.registerInstance(TOKENS.UTIL_LOGGER, new ConsoleLogger())
this.container.registerInstance(TOKENS.UTIL_OCA_RESOLVER, new DefaultOCABundleResolver(bundle))
this.container.registerInstance(TOKENS.UTIL_LEDGERS, defaultIndyLedgers)
this.container.registerInstance(
this.log?.info(`Initializing Bifold container`)

this._container.registerInstance(TOKENS.SCREEN_PREFACE, Preface)
this._container.registerInstance(TOKENS.SCREEN_DEVELOPER, Developer)
this._container.registerInstance(TOKENS.SCREEN_TERMS, { screen: ScreenTerms, version: TermsVersion })
this._container.registerInstance(TOKENS.SCREEN_ONBOARDING, Onboarding)
this._container.registerInstance(TOKENS.STACK_ONBOARDING, OnboardingStack)
this._container.registerInstance(TOKENS.COMP_BUTTON, Button)
this._container.registerInstance(TOKENS.GROUP_BY_REFERENT, false)
this._container.registerInstance(TOKENS.CRED_HELP_ACTION_OVERRIDES, [])
this._container.registerInstance(TOKENS.OBJECT_ONBOARDING_CONFIG, DefaultScreenOptionsDictionary)
this._container.registerInstance(TOKENS.UTIL_LOGGER, new ConsoleLogger())
this._container.registerInstance(TOKENS.UTIL_OCA_RESOLVER, new DefaultOCABundleResolver(bundle))
this._container.registerInstance(TOKENS.UTIL_LEDGERS, defaultIndyLedgers)
this._container.registerInstance(TOKENS.UTIL_PROOF_TEMPLATE, useProofRequestTemplates)
this._container.registerInstance(
TOKENS.FN_ONBOARDING_DONE,
(dispatch: React.Dispatch<ReducerAction<unknown>>, navigation: StackNavigationProp<AuthenticateStackParams>) => {
return () => {
Expand All @@ -61,8 +71,7 @@ export class MainContainer implements Container {
}
}
)

this.container.registerInstance(TOKENS.LOAD_STATE, async (dispatch: React.Dispatch<ReducerAction<unknown>>) => {
this._container.registerInstance(TOKENS.LOAD_STATE, async (dispatch: React.Dispatch<ReducerAction<unknown>>) => {
const loadState = async <Type>(key: LocalStorageKeys, updateVal: (newVal: Type) => void) => {
const data = await AsyncStorage.getItem(key)
if (data) {
Expand Down Expand Up @@ -97,18 +106,15 @@ export class MainContainer implements Container {
tours: { ...defaultState.tours, ...tours },
onboarding: { ...defaultState.onboarding, ...onboarding },
}

dispatch({ type: DispatchAction.STATE_DISPATCH, payload: [state] })
})

return this
}

public resolve<K extends keyof TokenMapping>(token: K): TokenMapping[K] {
return this.container.resolve(token) as TokenMapping[K]
}

public getContainer(): DependencyContainer {
return this.container
return this._container.resolve(token) as TokenMapping[K]
}
}

Expand Down
2 changes: 0 additions & 2 deletions packages/legacy/core/App/contexts/configuration.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Agent } from '@credo-ts/core'
import { ProofRequestTemplate } from '@hyperledger/aries-bifold-verifier'
import { StackNavigationOptions, StackScreenProps } from '@react-navigation/stack'
import { ReducerAction, createContext, useContext } from 'react'

Expand Down Expand Up @@ -49,7 +48,6 @@ export interface ConfigurationContext {
supportedLanguages: Locales[]
connectionTimerDelay?: number
autoRedirectConnectionToHome?: boolean
proofRequestTemplates?: (useDevTemplates: boolean) => Array<ProofRequestTemplate>
enableTours?: boolean
enableImplicitInvitations?: boolean
enableReuseConnections?: boolean
Expand Down
3 changes: 0 additions & 3 deletions packages/legacy/core/App/defaultConfiguration.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { useProofRequestTemplates } from '@hyperledger/aries-bifold-verifier'

import EmptyList from './components/misc/EmptyList'
import Record from './components/record/Record'
import HomeFooterView from './components/views/HomeFooterView'
Expand Down Expand Up @@ -39,7 +37,6 @@ export const defaultConfiguration: ConfigurationContext = {
buttonTitle: '',
pageTitle: '',
},
proofRequestTemplates: useProofRequestTemplates,
enableTours: false,
supportedLanguages: Object.keys(translationResources) as Locales[],
showPreface: false,
Expand Down
1 change: 1 addition & 0 deletions packages/legacy/core/App/hooks/proof-request-templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export const useTemplates = (): Array<ProofRequestTemplate> => {
}
})
}, [])

return proofRequestTemplates
}

Expand Down
2 changes: 2 additions & 0 deletions packages/legacy/core/App/hooks/proofs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { retrieveCredentialsForProof } from '../utils/helpers'

export const useProofsByConnectionId = (connectionId: string): ProofExchangeRecord[] => {
const { records: proofs } = useProofs()

return useMemo(
() => proofs.filter((proof: ProofExchangeRecord) => proof.connectionId === connectionId),
[proofs, connectionId]
Expand All @@ -21,6 +22,7 @@ export const useAllCredentialsForProof = (proofId: string) => {
const proof = useProofById(proofId)
const container = useContainer()
const groupByReferent = container.resolve(TOKENS.GROUP_BY_REFERENT)

return useMemo(() => {
if (!proof || !agent) {
return
Expand Down
2 changes: 1 addition & 1 deletion packages/legacy/core/App/navigators/OnboardingStack.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ const OnboardingStack: React.FC = () => {
const onTutorialCompleted = container.resolve(TOKENS.FN_ONBOARDING_DONE)(dispatch, navigation)
const { screen: Terms } = container.resolve(TOKENS.SCREEN_TERMS)
const Developer = container.resolve(TOKENS.SCREEN_DEVELOPER)
const ScreenOptionsDictionary = container.resolve(TOKENS.OBJECT_ONBOARDINGCONFIG)
const ScreenOptionsDictionary = container.resolve(TOKENS.OBJECT_ONBOARDING_CONFIG)
const Preface = container.resolve(TOKENS.SCREEN_PREFACE)

const onAuthenticated = (status: boolean): void => {
Expand Down
12 changes: 8 additions & 4 deletions packages/legacy/core/App/utils/proofBundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import {
} from '@hyperledger/aries-bifold-verifier'
import axios, { AxiosError } from 'axios'

import { useConfiguration } from '../contexts/configuration'
import { TOKENS, useContainer } from '../container-api'

type ProofRequestTemplateFn = (useDevTemplates: boolean) => Array<ProofRequestTemplate>

const calculatePreviousYear = (yearOffset: number) => {
const pastDate = new Date()
Expand Down Expand Up @@ -73,7 +75,10 @@ export const useRemoteProofBundleResolver = (
if (indexFileBaseUrl) {
return new RemoteProofBundleResolver(indexFileBaseUrl, log)
} else {
return new DefaultProofBundleResolver()
const container = useContainer()
const proofRequestTemplates = container.resolve(TOKENS.UTIL_PROOF_TEMPLATE)

return new DefaultProofBundleResolver(proofRequestTemplates)
}
}

Expand Down Expand Up @@ -149,8 +154,7 @@ export class RemoteProofBundleResolver implements ProofBundleResolverType {
export class DefaultProofBundleResolver implements ProofBundleResolverType {
private proofRequestTemplates

public constructor() {
const { proofRequestTemplates } = useConfiguration()
public constructor(proofRequestTemplates: ProofRequestTemplateFn | undefined) {
this.proofRequestTemplates = proofRequestTemplates ?? useProofRequestTemplates
}

Expand Down
2 changes: 0 additions & 2 deletions packages/legacy/core/__tests__/contexts/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { ConfigurationContext } from '../../App'
import Record from '../../App/components/record/Record'
import { useNotifications } from '../../App/hooks/notifications'
import { Locales } from '../../App/localization'
import { useProofRequestTemplates } from '@hyperledger/aries-bifold-verifier'

const configurationContext: ConfigurationContext = {
pages: () => [],
Expand Down Expand Up @@ -41,7 +40,6 @@ const configurationContext: ConfigurationContext = {
pageTitle: '',
},
useCustomNotifications: useNotifications,
proofRequestTemplates: useProofRequestTemplates,
supportedLanguages: [Locales.en, Locales.fr, Locales.ptBr],
whereToUseWalletUrl: 'https://example.com',
}
Expand Down

0 comments on commit 0fba088

Please sign in to comment.