Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/utilities/__tests__/coerceInputValue-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,13 @@ describe('coerceInputValue', () => {
},
isOneOf: true,
});
const TestInvalidOneOfInputObjectWithDefault = new GraphQLInputObjectType({
name: 'TestInvalidOneOfInputObjectWithDefault',
fields: {
foo: { type: GraphQLInt, default: { value: 123 } },
},
isOneOf: true,
});

it('returns for valid input', () => {
test({ foo: 123 }, TestInputObject, { foo: 123 });
Expand All @@ -203,6 +210,18 @@ describe('coerceInputValue', () => {
test({ bar: null }, TestInputObject, undefined);
});

it('invalid if an omitted field would be filled by a default', () => {
test({}, TestInvalidOneOfInputObjectWithDefault, undefined);
});

it('invalid if an undefined field would be filled by a default', () => {
test(
{ foo: undefined },
TestInvalidOneOfInputObjectWithDefault,
undefined,
);
});

it('invalid for an invalid field', () => {
test({ foo: NaN }, TestInputObject, undefined);
});
Expand Down
17 changes: 10 additions & 7 deletions src/utilities/coerceInputValue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,15 @@ export function coerceInputValue(

const coercedValue: ObjMap<unknown> = Object.create(null);
const fieldDefs = type.getFields();
const hasUndefinedField = Object.keys(inputValue).some(
(name) =>
inputValue[name] !== undefined && !Object.hasOwn(fieldDefs, name),
);
if (hasUndefinedField) {
return; // Invalid: intentionally return no value.
let definedFieldCount = 0;
for (const fieldName of Object.keys(inputValue)) {
if (inputValue[fieldName] === undefined) {
continue;
}
definedFieldCount++;
if (!Object.hasOwn(fieldDefs, fieldName)) {
return; // Invalid: intentionally return no value.
}
}
for (const field of Object.values(fieldDefs)) {
const fieldValue = inputValue[field.name];
Expand All @@ -101,7 +104,7 @@ export function coerceInputValue(

if (type.isOneOf) {
const keys = Object.keys(coercedValue);
if (keys.length !== 1) {
if (definedFieldCount !== 1 || keys.length !== 1) {
return; // Invalid: intentionally return no value.
}

Expand Down
Loading