Skip to content

Commit e157181

Browse files
authored
fix: empty object serialization (#55)
1 parent 1853734 commit e157181

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

src/__tests__/falsykeys.tests.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,40 @@ describe('jsonToGraphQLQuery() - falsy keys', () => {
4646
);
4747
});
4848

49+
it('does not include object with only false keys', () => {
50+
const query = {
51+
query: {
52+
Posts: {
53+
id: true,
54+
name: false
55+
},
56+
Lorem: {
57+
id: false
58+
},
59+
Ipsum: true
60+
}
61+
};
62+
expect(jsonToGraphQLQuery(query)).to.equal(
63+
'query { Posts { id } Ipsum }'
64+
);
65+
});
66+
67+
it('does include object with only false keys if includeFalsyKeys is true', () => {
68+
const query = {
69+
query: {
70+
Posts: {
71+
id: true,
72+
name: false
73+
},
74+
Lorem: {
75+
id: false
76+
},
77+
Ipsum: true
78+
}
79+
};
80+
expect(jsonToGraphQLQuery(query, { includeFalsyKeys: true })).to.equal(
81+
'query { Posts { id name } Lorem { id } Ipsum }'
82+
);
83+
});
84+
4985
});

src/jsonToGraphQLQuery.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,12 @@ function convertQuery(node: any, level: number, output: [string, number][], opti
9090
}
9191
}
9292

93+
// Check if the object would be empty
94+
if (value && Object.keys(value).filter(k => value[k] !== false || options.includeFalsyKeys).length === 0) {
95+
// If so, we don't include it into the query
96+
return;
97+
}
98+
9399
const fieldCount = Object.keys(value)
94100
.filter((keyCount) => filterNonConfigFields(keyCount, options.ignoreFields!)).length;
95101
const subFields = fieldCount > 0;
@@ -116,7 +122,7 @@ function convertQuery(node: any, level: number, output: [string, number][], opti
116122
let dirsStr = '';
117123
if (directivesExist) {
118124
dirsStr = Object.entries(value.__directives)
119-
.map(item => `@${buildDirectives({[item[0]]: item[1]})}`)
125+
.map(item => `@${buildDirectives({ [item[0]]: item[1] })}`)
120126
.join(' ')
121127
}
122128
if (argsExist) {

0 commit comments

Comments
 (0)