Skip to content

Commit 3fcff2e

Browse files
committed
fix(forms/utils): flattenSchemaProperties() broken for >1 depth form jsonSchema
1 parent e8c8b5f commit 3fcff2e

2 files changed

Lines changed: 52 additions & 15 deletions

File tree

__tests__/forms/utils.spec.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,39 @@ describe('forms/utils', () => {
5757
}
5858
});
5959
});
60+
61+
test('should expand definitions for 2 levels properties', () => {
62+
const todoSchema: JSONSchema6 = require('../mocks/todo-json-schema.json');
63+
const mySchema: JSONSchema6 = {
64+
'$schema': 'http://json-schema.org/draft-06/schema#',
65+
properties: {
66+
a: {
67+
type: 'object',
68+
properties: {
69+
b: { '$ref': '#/definitions/Todo' }
70+
}
71+
}
72+
},
73+
definitions: todoSchema.definitions
74+
};
75+
expect(
76+
flattenSchemaProperties(mySchema)
77+
).toEqual({
78+
a: {
79+
type: 'object',
80+
properties: {
81+
b: {
82+
type: 'object',
83+
properties: {
84+
completed: { type: 'boolean' },
85+
id: { type: 'string' },
86+
name: { type: 'string' }
87+
}, required: ['id', 'name']
88+
}
89+
}
90+
}
91+
});
92+
});
6093
});
6194

6295
describe('applyConditionsToSchema()', () => {

lib/forms/utils.ts

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// tslint:disable:no-any
22
import { PureQueryOptions } from 'apollo-client';
3-
import { every } from 'async';
3+
import { every, reduce } from 'async';
44
import { DocumentNode } from 'graphql';
55
import { JSONSchema6 } from 'json-schema';
66
import {
@@ -57,20 +57,24 @@ export const isMutationConfig = (config: ApolloFormConfig): config is ApolloForm
5757
};
5858

5959
// Given a schema, expand properties that reference a definition
60-
export const flattenSchemaProperties = (schema: any): any => {
61-
// FIXME: do not work for >1 depth properties !
62-
return transform(
63-
schema.properties,
64-
(result, value, key) => {
65-
if (get(value, '$ref')) {
66-
result[key] = retrieveSchema(value, schema.definitions);
67-
} else {
68-
result[key] = value;
69-
}
70-
return result;
71-
},
72-
{}
73-
);
60+
export const flattenSchemaProperties = (entrySchema: any): any => {
61+
const reducer = (schema: any, definitions: any) => {
62+
return transform(
63+
schema.properties,
64+
(result, value, key) => {
65+
if (get(value, '$ref')) {
66+
result[key] = retrieveSchema(value, definitions);
67+
} else {
68+
result[key] = has(value, 'properties') ?
69+
{ ...value, properties: reducer(value, definitions) }
70+
: value;
71+
}
72+
return result;
73+
},
74+
{}
75+
);
76+
};
77+
return reducer(entrySchema, entrySchema.definitions || {});
7478
};
7579

7680
// Given a UiSchema, a JSON Schema and data

0 commit comments

Comments
 (0)