UNPKG

1.5 kBPlain TextView Raw
1import { Config, Model, Models, NamedModel, RematchBag } from './types'
2import { validateModel } from './validate'
3
4/**
5 * Creates and returns a 'Rematch Bag', which is a set of configuration options
6 * used by the Rematch library in various functions.
7 */
8export default function createRematchBag<
9 TModels extends Models<TModels>,
10 TExtraModels extends Models<TModels>
11>(config: Config<TModels, TExtraModels>): RematchBag<TModels, TExtraModels> {
12 return {
13 models: createNamedModels(config.models),
14 reduxConfig: config.redux,
15 forEachPlugin(method, fn): void {
16 config.plugins.forEach((plugin) => {
17 if (plugin[method]) {
18 fn(plugin[method]!)
19 }
20 })
21 },
22 effects: {},
23 }
24}
25
26/**
27 * Transforms mapping from a model name to a model object, into an array of
28 * 'named' models - models with embedded name and default value for reducers
29 * if user didn't provide any.
30 */
31function createNamedModels<TModels extends Models<TModels>>(
32 models: TModels | Partial<TModels>
33): NamedModel<TModels>[] {
34 return Object.keys(models).map((modelName: string) => {
35 const model = createNamedModel(modelName, (models as TModels)[modelName])
36 validateModel(model)
37 return model
38 })
39}
40
41/**
42 * Transforms a model into 'named' model - model which contains 'name' and
43 * 'reducers' properties if user didn't provide any.
44 */
45function createNamedModel<TModels extends Models<TModels>>(
46 name: string,
47 model: Model<TModels>
48): NamedModel<TModels> {
49 return {
50 name,
51 reducers: {},
52 ...model,
53 }
54}