Skip to content

Commit 2d3bc38

Browse files
authored
Fix union of models or references. Fixes #29 (#89)
1 parent 4723648 commit 2d3bc38

File tree

4 files changed

+43
-4
lines changed

4 files changed

+43
-4
lines changed

packages/mst-query/package-lock.json

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

packages/mst-query/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "mst-query",
3-
"version": "4.2.0",
3+
"version": "4.2.1",
44
"description": "Query library for mobx-state-tree",
55
"source": "src/index.ts",
66
"type": "module",

packages/mst-query/src/utils.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,14 @@ export function getSubType(t: any, data?: any): any {
3232
return getSubType(t._subtype);
3333
}
3434
const subTypes = t._types.map((t: any) => getSubType(t, data));
35-
const modelWithProperties = subTypes.find((x: any) => isModelType(x) || isReferenceType(x));
35+
// Every subtype is a model type or reference type - return the union type and let mst
36+
// handle reconciling the types.
37+
if (subTypes.every((x: any) => isModelType(x) || isReferenceType(x))) {
38+
return t;
39+
}
40+
// If we have a union of models and primitives (null/undefined), we need to find the first model or reference type
41+
// to enumerate the properties of the object.
42+
const modelWithProperties = subTypes.find((x: any) => isModelType(x) || isReferenceType(x));
3643
if (modelWithProperties) {
3744
return getSubType(modelWithProperties, data);
3845
}

packages/mst-query/tests/mstQuery.test.tsx

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1307,3 +1307,35 @@ test('initial data should only be set on mount', async () => {
13071307

13081308
configureMobx({ enforceActions: 'observed' });
13091309
});
1310+
1311+
test('union of array models', () => {
1312+
const data = {
1313+
rules: [
1314+
{
1315+
kind: 'FIXED',
1316+
fixedValue: 'Fixed value',
1317+
},
1318+
{
1319+
kind: 'FORMAT',
1320+
formatValue: 'Formatted value',
1321+
},
1322+
],
1323+
};
1324+
const Model = types.model('UnionArrayTestModel', {
1325+
rules: types.array(
1326+
types.union(
1327+
types.late(() => types.model('FixedModel', {
1328+
kind: types.literal('FIXED'),
1329+
fixedValue: types.string,
1330+
})),
1331+
types.model('FormatModel', {
1332+
kind: types.literal('FORMAT'),
1333+
formatValue: types.string,
1334+
}),
1335+
),
1336+
),
1337+
});
1338+
const result = merge(data, Model, {});
1339+
expect(result.rules[0].fixedValue).toBe('Fixed value');
1340+
expect(result.rules[1].formatValue).toBe('Formatted value');
1341+
});

0 commit comments

Comments
 (0)