( lDefinition: ILoaderDefinition<I, O, C>, )
| 43 | } |
| 44 | |
| 45 | export function createLoader<I, O, C>( |
| 46 | lDefinition: ILoaderDefinition<I, O, C>, |
| 47 | ): ILoader<I, O, C> { |
| 48 | const state = { |
| 49 | defaultLocale: undefined as string | undefined, |
| 50 | originalInput: undefined as I | undefined | null, |
| 51 | // Store pullInput and pullOutput per-locale to avoid race conditions |
| 52 | // when multiple locales are processed concurrently |
| 53 | pullInputByLocale: new Map<string, I | null>(), |
| 54 | pullOutputByLocale: new Map<string, O | null>(), |
| 55 | initCtx: undefined as C | undefined, |
| 56 | }; |
| 57 | return { |
| 58 | async init() { |
| 59 | if (state.initCtx) { |
| 60 | return state.initCtx; |
| 61 | } |
| 62 | state.initCtx = await lDefinition.init?.(); |
| 63 | return state.initCtx as C; |
| 64 | }, |
| 65 | setDefaultLocale(locale) { |
| 66 | if (state.defaultLocale) { |
| 67 | throw new Error("Default locale already set"); |
| 68 | } |
| 69 | state.defaultLocale = locale; |
| 70 | return this; |
| 71 | }, |
| 72 | async pullHints(originalInput?: I) { |
| 73 | return lDefinition.pullHints?.(originalInput || state.originalInput!); |
| 74 | }, |
| 75 | async pull(locale, input) { |
| 76 | if (!state.defaultLocale) { |
| 77 | throw new Error("Default locale not set"); |
| 78 | } |
| 79 | if (state.originalInput === undefined && locale !== state.defaultLocale) { |
| 80 | throw new Error("The first pull must be for the default locale"); |
| 81 | } |
| 82 | if (locale === state.defaultLocale) { |
| 83 | state.originalInput = input || null; |
| 84 | } |
| 85 | |
| 86 | state.pullInputByLocale.set(locale, input || null); |
| 87 | const result = await lDefinition.pull( |
| 88 | locale, |
| 89 | input, |
| 90 | state.initCtx!, |
| 91 | state.defaultLocale, |
| 92 | state.originalInput!, |
| 93 | ); |
| 94 | state.pullOutputByLocale.set(locale, result); |
| 95 | |
| 96 | return result; |
| 97 | }, |
| 98 | async push(locale, data) { |
| 99 | if (!state.defaultLocale) { |
| 100 | throw new Error("Default locale not set"); |
| 101 | } |
| 102 | if (state.originalInput === undefined) { |
no outgoing calls
no test coverage detected