Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve defaultValue literals #3074

Closed
wants to merge 1 commit into from
Closed
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
15 changes: 11 additions & 4 deletions src/execution/values.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { typeFromAST } from '../utilities/typeFromAST';
import {
coerceInputValue,
coerceInputLiteral,
coerceDefaultValue,
} from '../utilities/coerceInputValue';

type CoercedVariableValues =
Expand Down Expand Up @@ -177,8 +178,11 @@ export function getArgumentValues(
const argumentNode = argNodeMap[name];

if (!argumentNode) {
if (argDef.defaultValue !== undefined) {
coercedValues[name] = argDef.defaultValue;
if (argDef.defaultValue) {
coercedValues[name] = coerceDefaultValue(
argDef.defaultValue,
argDef.type,
);
} else if (isNonNullType(argType)) {
throw new GraphQLError(
`Argument ${argDef} of required type ${argType} was not provided.`,
Expand All @@ -197,8 +201,11 @@ export function getArgumentValues(
variableValues == null ||
!hasOwnProperty(variableValues, variableName)
) {
if (argDef.defaultValue !== undefined) {
coercedValues[name] = argDef.defaultValue;
if (argDef.defaultValue) {
coercedValues[name] = coerceDefaultValue(
argDef.defaultValue,
argDef.type,
);
} else if (isNonNullType(argType)) {
throw new GraphQLError(
`Argument ${argDef} of required type ${argType} ` +
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ export type {
GraphQLScalarSerializer,
GraphQLScalarValueParser,
GraphQLScalarLiteralParser,
GraphQLDefaultValueUsage,
} from './type/index';

/** Parse and operate on GraphQL language source files. */
Expand Down
63 changes: 63 additions & 0 deletions src/type/__tests__/definition-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -826,6 +826,69 @@ describe('Type System: Input Objects', () => {
);
});
});

describe('Input Object fields may have default values', () => {
it('accepts an Input Object type with a default value', () => {
const inputObjType = new GraphQLInputObjectType({
name: 'SomeInputObject',
fields: {
f: { type: ScalarType, defaultValue: 3 },
},
});
expect(inputObjType.getFields()).to.deep.equal({
f: {
coordinate: 'SomeInputObject.f',
name: 'f',
description: undefined,
type: ScalarType,
defaultValue: { value: 3 },
deprecationReason: undefined,
extensions: undefined,
astNode: undefined,
},
});
});

it('accepts an Input Object type with a default value literal', () => {
const inputObjType = new GraphQLInputObjectType({
name: 'SomeInputObject',
fields: {
f: {
type: ScalarType,
defaultValueLiteral: { kind: 'IntValue', value: '3' },
},
},
});
expect(inputObjType.getFields()).to.deep.equal({
f: {
coordinate: 'SomeInputObject.f',
name: 'f',
description: undefined,
type: ScalarType,
defaultValue: { literal: { kind: 'IntValue', value: '3' } },
deprecationReason: undefined,
extensions: undefined,
astNode: undefined,
},
});
});

it('rejects an Input Object type with potentially conflicting default values', () => {
const inputObjType = new GraphQLInputObjectType({
name: 'SomeInputObject',
fields: {
f: {
type: ScalarType,
defaultValue: 3,
defaultValueLiteral: { kind: 'IntValue', value: '3' },
},
},
});
expect(() => inputObjType.getFields()).to.throw(
'f has both a defaultValue and a defaultValueLiteral property, but only one must be provided.',
);
});
});
});

describe('Type System: List', () => {
Expand Down
37 changes: 31 additions & 6 deletions src/type/definition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { print } from '../language/printer';
import type {
FieldNode,
ValueNode,
ConstValueNode,
OperationDefinitionNode,
FragmentDefinitionNode,
ScalarTypeDefinitionNode,
Expand Down Expand Up @@ -964,6 +965,7 @@ export interface GraphQLArgumentConfig {
description?: Maybe<string>;
type: GraphQLInputType;
defaultValue?: unknown;
defaultValueLiteral?: ConstValueNode;
deprecationReason?: Maybe<string>;
extensions?: Maybe<Readonly<GraphQLArgumentExtensions>>;
astNode?: Maybe<InputValueDefinitionNode>;
Expand Down Expand Up @@ -1049,7 +1051,7 @@ export class GraphQLArgument extends GraphQLSchemaElement {
name: string;
description: Maybe<string>;
type: GraphQLInputType;
defaultValue: unknown;
defaultValue: GraphQLDefaultValueUsage | undefined;
deprecationReason: Maybe<string>;
extensions: Maybe<Readonly<GraphQLArgumentExtensions>>;
astNode: Maybe<InputValueDefinitionNode>;
Expand All @@ -1064,7 +1066,7 @@ export class GraphQLArgument extends GraphQLSchemaElement {
this.name = name;
this.description = config.description;
this.type = config.type;
this.defaultValue = config.defaultValue;
this.defaultValue = defineDefaultValue(coordinate, config);
this.deprecationReason = config.deprecationReason;
this.extensions = config.extensions && toObjMap(config.extensions);
this.astNode = config.astNode;
Expand All @@ -1074,7 +1076,8 @@ export class GraphQLArgument extends GraphQLSchemaElement {
return {
description: this.description,
type: this.type,
defaultValue: this.defaultValue,
defaultValue: this.defaultValue?.value,
defaultValueLiteral: this.defaultValue?.literal,
deprecationReason: this.deprecationReason,
extensions: this.extensions,
astNode: this.astNode,
Expand All @@ -1090,6 +1093,26 @@ export type GraphQLFieldMap<TSource, TContext> = ObjMap<
GraphQLField<TSource, TContext>
>;

export type GraphQLDefaultValueUsage =
| { value: unknown; literal?: never }
| { literal: ConstValueNode; value?: never };

function defineDefaultValue(
coordinate: string,
config: GraphQLArgumentConfig | GraphQLInputFieldConfig,
): GraphQLDefaultValueUsage | undefined {
if (config.defaultValue === undefined && !config.defaultValueLiteral) {
return;
}
devAssert(
!(config.defaultValue !== undefined && config.defaultValueLiteral),
`${coordinate} has both a defaultValue and a defaultValueLiteral property, but only one must be provided.`,
);
return config.defaultValueLiteral
? { literal: config.defaultValueLiteral }
: { value: config.defaultValue };
}

/**
* Custom extensions
*
Expand Down Expand Up @@ -1694,6 +1717,7 @@ export interface GraphQLInputFieldConfig {
description?: Maybe<string>;
type: GraphQLInputType;
defaultValue?: unknown;
defaultValueLiteral?: ConstValueNode;
deprecationReason?: Maybe<string>;
extensions?: Maybe<Readonly<GraphQLInputFieldExtensions>>;
astNode?: Maybe<InputValueDefinitionNode>;
Expand All @@ -1705,7 +1729,7 @@ export class GraphQLInputField extends GraphQLSchemaElement {
name: string;
description: Maybe<string>;
type: GraphQLInputType;
defaultValue: unknown;
defaultValue: GraphQLDefaultValueUsage | undefined;
deprecationReason: Maybe<string>;
extensions: Maybe<Readonly<GraphQLInputFieldExtensions>>;
astNode: Maybe<InputValueDefinitionNode>;
Expand All @@ -1726,7 +1750,7 @@ export class GraphQLInputField extends GraphQLSchemaElement {
this.name = name;
this.description = config.description;
this.type = config.type;
this.defaultValue = config.defaultValue;
this.defaultValue = defineDefaultValue(coordinate, config);
this.deprecationReason = config.deprecationReason;
this.extensions = config.extensions && toObjMap(config.extensions);
this.astNode = config.astNode;
Expand All @@ -1736,7 +1760,8 @@ export class GraphQLInputField extends GraphQLSchemaElement {
return {
description: this.description,
type: this.type,
defaultValue: this.defaultValue,
defaultValue: this.defaultValue?.value,
defaultValueLiteral: this.defaultValue?.literal,
extensions: this.extensions,
astNode: this.astNode,
};
Expand Down
1 change: 1 addition & 0 deletions src/type/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ export type {
GraphQLScalarSerializer,
GraphQLScalarValueParser,
GraphQLScalarLiteralParser,
GraphQLDefaultValueUsage,
} from './definition';

export {
Expand Down
9 changes: 7 additions & 2 deletions src/type/introspection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -384,8 +384,13 @@ export const __InputValue: GraphQLObjectType = new GraphQLObjectType({
'A GraphQL-formatted string representing the default value for this input value.',
resolve(inputValue) {
const { type, defaultValue } = inputValue;
const valueAST = astFromValue(defaultValue, type);
return valueAST ? print(valueAST) : null;
if (!defaultValue) {
return null;
}
const literal =
defaultValue.literal ?? astFromValue(defaultValue.value, type);
invariant(literal, 'Invalid default value');
return print(literal);
},
},
isDeprecated: {
Expand Down
5 changes: 3 additions & 2 deletions src/utilities/TypeInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import type {
GraphQLArgument,
GraphQLInputField,
GraphQLEnumValue,
GraphQLDefaultValueUsage,
} from '../type/definition';
import {
isObjectType,
Expand Down Expand Up @@ -49,7 +50,7 @@ export class TypeInfo {
private _parentTypeStack: Array<Maybe<GraphQLCompositeType>>;
private _inputTypeStack: Array<Maybe<GraphQLInputType>>;
private _fieldDefStack: Array<Maybe<GraphQLField<unknown, unknown>>>;
private _defaultValueStack: Array<Maybe<unknown>>;
private _defaultValueStack: Array<GraphQLDefaultValueUsage | undefined>;
private _directive: Maybe<GraphQLDirective>;
private _argument: Maybe<GraphQLArgument>;
private _enumValue: Maybe<GraphQLEnumValue>;
Expand Down Expand Up @@ -119,7 +120,7 @@ export class TypeInfo {
}
}

getDefaultValue(): Maybe<unknown> {
getDefaultValue(): GraphQLDefaultValueUsage | undefined {
if (this._defaultValueStack.length > 0) {
return this._defaultValueStack[this._defaultValueStack.length - 1];
}
Expand Down
23 changes: 23 additions & 0 deletions src/utilities/__tests__/buildClientSchema-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,7 @@ describe('Type System: build schema from introspection', () => {
}

type Query {
defaultID(intArg: ID = "123"): String
defaultInt(intArg: Int = 30): String
defaultList(listArg: [Int] = [1, 2, 3]): String
defaultObject(objArg: Geo = {lat: 37.485, lon: -122.148}): String
Expand Down Expand Up @@ -599,6 +600,28 @@ describe('Type System: build schema from introspection', () => {
expect(result.data).to.deep.equal({ foo: 'bar' });
});

it('can use client schema for execution if resolvers are added', () => {
const schema = buildSchema(`
type Query {
foo(bar: String = "abc"): String
}
`);

const introspection = introspectionFromSchema(schema);
const clientSchema = buildClientSchema(introspection);

const QueryType: GraphQLObjectType = clientSchema.getType('Query') as any;
QueryType.getFields().foo.resolve = (_value, args) => args.bar;

const result = graphqlSync({
schema: clientSchema,
source: '{ foo }',
});

expect(result.data).to.deep.equal({ foo: 'abc' });
expect(result.data).to.deep.equal({ foo: 'abc' });
});

it('can build invalid schema', () => {
const schema = buildSchema('type Query', { assumeValid: true });

Expand Down
35 changes: 33 additions & 2 deletions src/utilities/__tests__/coerceInputValue-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,11 @@ import {
GraphQLInputObjectType,
} from '../../type/definition';

import { coerceInputValue, coerceInputLiteral } from '../coerceInputValue';
import {
coerceInputValue,
coerceInputLiteral,
coerceDefaultValue,
} from '../coerceInputValue';

interface CoerceResult {
value: unknown;
Expand Down Expand Up @@ -610,10 +614,14 @@ describe('coerceInputLiteral', () => {
name: 'TestInput',
fields: {
int: { type: GraphQLInt, defaultValue: 42 },
float: {
type: GraphQLFloat,
defaultValueLiteral: { kind: 'FloatValue', value: '3.14' },
},
},
});

test('{}', type, { int: 42 });
test('{}', type, { int: 42, float: 3.14 });
});

const testInputObj = new GraphQLInputObjectType({
Expand Down Expand Up @@ -681,3 +689,26 @@ describe('coerceInputLiteral', () => {
});
});
});

describe('coerceDefaultValue', () => {
it('memoizes coercion', () => {
const parseValueCalls: any = [];

const spyScalar = new GraphQLScalarType({
name: 'SpyScalar',
parseValue(value) {
parseValueCalls.push(value);
return value;
},
});

const defaultValueUsage = {
literal: { kind: 'StringValue', value: 'hello' },
} as const;
expect(coerceDefaultValue(defaultValueUsage, spyScalar)).to.equal('hello');

// Call a second time
expect(coerceDefaultValue(defaultValueUsage, spyScalar)).to.equal('hello');
expect(parseValueCalls).to.deep.equal(['hello']);
});
});
4 changes: 2 additions & 2 deletions src/utilities/astFromValue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { isObjectLike } from '../jsutils/isObjectLike';
import { isIterableObject } from '../jsutils/isIterableObject';
import type { Maybe } from '../jsutils/Maybe';

import type { ValueNode } from '../language/ast';
import type { ConstValueNode } from '../language/ast';
import { Kind } from '../language/kinds';

import type { GraphQLInputType } from '../type/definition';
Expand Down Expand Up @@ -41,7 +41,7 @@ import {
export function astFromValue(
value: unknown,
type: GraphQLInputType,
): Maybe<ValueNode> {
): Maybe<ConstValueNode> {
if (isNonNullType(type)) {
const astValue = astFromValue(value, type.ofType);
if (astValue?.kind === Kind.NULL) {
Expand Down
Loading