Skip to content

Commit

Permalink
Preserve defaultValue literals
Browse files Browse the repository at this point in the history
Fixes graphql#3051

This change solves the problem of default values defined via SDL not always resolving correctly through introspection by preserving the original GraphQL literal in the schema definition. This changes argument and input field definitions `defaultValue` field from just the "value" to a new `GraphQLDefaultValueUsage` type which contains either or both "value" and "literal" fields.

Since either of these fields may be set, new functions for resolving a value or literal from either have been added - `getLiteralDefaultValue` and `getCoercedDefaultValue` - these replace uses that either assumed a set value or were manually converting a value back to a literal.

Here is the flow for how a default value defined in an SDL would be converted into a functional schema and back to an SDL:

**Before this change:**

```
(SDL) --parse-> (AST) --coerceInputLiteral--> (defaultValue config) --valueToAST--> (AST) --print --> (SDL)
```

`coerceInputLiteral` performs coercion which is a one-way function, and `valueToAST` is unsafe and set to be deprecated in graphql#3049.

**After this change:**

```
(SDL) --parse-> (defaultValue literal config) --print --> (SDL)
```
  • Loading branch information
leebyron authored and yaacovCR committed Feb 6, 2023
1 parent 96b2fcc commit ba6c1e6
Show file tree
Hide file tree
Showing 17 changed files with 233 additions and 49 deletions.
15 changes: 11 additions & 4 deletions src/execution/values.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import type { GraphQLDirective } from '../type/directives.js';
import type { GraphQLSchema } from '../type/schema.js';

import {
coerceDefaultValue,
coerceInputLiteral,
coerceInputValue,
} from '../utilities/coerceInputValue.js';
Expand Down Expand Up @@ -170,8 +171,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 @@ -190,8 +194,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 @@ -199,6 +199,7 @@ export type {
GraphQLScalarSerializer,
GraphQLScalarValueParser,
GraphQLScalarLiteralParser,
GraphQLDefaultValueUsage,
} from './type/index.js';

// Parse and operate on GraphQL language source files.
Expand Down
60 changes: 60 additions & 0 deletions src/type/__tests__/definition-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { describe, it } from 'mocha';
import { identityFunc } from '../../jsutils/identityFunc.js';
import { inspect } from '../../jsutils/inspect.js';

import { Kind } from '../../language/kinds.js';
import { parseValue } from '../../language/parser.js';

import type { GraphQLNullableType, GraphQLType } from '../definition.js';
Expand Down Expand Up @@ -617,6 +618,65 @@ describe('Type System: Input Objects', () => {
'not used anymore',
);
});

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().f).to.deep.include({
coordinate: 'SomeInputObject.f',
name: 'f',
description: undefined,
type: ScalarType,
defaultValue: { value: 3 },
deprecationReason: undefined,
extensions: {},
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: Kind.INT, value: '3' },
},
},
});
expect(inputObjType.getFields().f).to.deep.include({
coordinate: 'SomeInputObject.f',
name: 'f',
description: undefined,
type: ScalarType,
defaultValue: { literal: { kind: 'IntValue', value: '3' } },
deprecationReason: undefined,
extensions: {},
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: Kind.INT, 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 @@ -16,6 +16,7 @@ import { toObjMap } from '../jsutils/toObjMap.js';
import { GraphQLError } from '../error/GraphQLError.js';

import type {
ConstValueNode,
EnumTypeDefinitionNode,
EnumTypeExtensionNode,
EnumValueDefinitionNode,
Expand Down Expand Up @@ -908,6 +909,7 @@ export interface GraphQLArgumentConfig {
description?: Maybe<string>;
type: GraphQLInputType;
defaultValue?: unknown;
defaultValueLiteral?: ConstValueNode | undefined;
deprecationReason?: Maybe<string>;
extensions?: Maybe<Readonly<GraphQLArgumentExtensions>>;
astNode?: Maybe<InputValueDefinitionNode>;
Expand Down Expand Up @@ -984,7 +986,7 @@ export class GraphQLArgument extends GraphQLSchemaElement {
name: string;
description: Maybe<string>;
type: GraphQLInputType;
defaultValue: unknown;
defaultValue: GraphQLDefaultValueUsage | undefined;
deprecationReason: Maybe<string>;
extensions: Readonly<GraphQLArgumentExtensions>;
astNode: Maybe<InputValueDefinitionNode>;
Expand All @@ -999,7 +1001,7 @@ export class GraphQLArgument extends GraphQLSchemaElement {
this.name = assertName(name);
this.description = config.description;
this.type = config.type;
this.defaultValue = config.defaultValue;
this.defaultValue = defineDefaultValue(coordinate, config);
this.deprecationReason = config.deprecationReason;
this.extensions = toObjMap(config.extensions);
this.astNode = config.astNode;
Expand All @@ -1013,7 +1015,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 @@ -1029,6 +1032,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 @@ -1608,6 +1631,7 @@ export interface GraphQLInputFieldConfig {
description?: Maybe<string>;
type: GraphQLInputType;
defaultValue?: unknown;
defaultValueLiteral?: ConstValueNode | undefined;
deprecationReason?: Maybe<string>;
extensions?: Maybe<Readonly<GraphQLInputFieldExtensions>>;
astNode?: Maybe<InputValueDefinitionNode>;
Expand All @@ -1619,7 +1643,7 @@ export class GraphQLInputField extends GraphQLSchemaElement {
name: string;
description: Maybe<string>;
type: GraphQLInputType;
defaultValue: unknown;
defaultValue: GraphQLDefaultValueUsage | undefined;
deprecationReason: Maybe<string>;
extensions: Readonly<GraphQLInputFieldExtensions>;
astNode: Maybe<InputValueDefinitionNode>;
Expand All @@ -1640,7 +1664,7 @@ export class GraphQLInputField extends GraphQLSchemaElement {
this.name = assertName(name);
this.description = config.description;
this.type = config.type;
this.defaultValue = config.defaultValue;
this.defaultValue = defineDefaultValue(coordinate, config);
this.deprecationReason = config.deprecationReason;
this.extensions = toObjMap(config.extensions);
this.astNode = config.astNode;
Expand All @@ -1654,7 +1678,8 @@ export class GraphQLInputField 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 Down
1 change: 1 addition & 0 deletions src/type/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ export type {
GraphQLScalarSerializer,
GraphQLScalarValueParser,
GraphQLScalarLiteralParser,
GraphQLDefaultValueUsage,
} from './definition.js';

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 @@ -395,8 +395,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 != null, '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 @@ -9,6 +9,7 @@ import { getEnterLeaveForKind } from '../language/visitor.js';
import type {
GraphQLArgument,
GraphQLCompositeType,
GraphQLDefaultValueUsage,
GraphQLEnumValue,
GraphQLField,
GraphQLInputField,
Expand Down Expand Up @@ -43,7 +44,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 @@ -117,7 +118,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 @@ -445,6 +445,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 @@ -600,6 +601,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
36 changes: 34 additions & 2 deletions src/utilities/__tests__/coerceInputValue-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { identityFunc } from '../../jsutils/identityFunc.js';
import { invariant } from '../../jsutils/invariant.js';
import type { ObjMap } from '../../jsutils/ObjMap.js';

import { Kind } from '../../language/kinds.js';
import { parseValue } from '../../language/parser.js';
import { print } from '../../language/printer.js';

Expand All @@ -24,7 +25,11 @@ import {
GraphQLString,
} from '../../type/scalars.js';

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

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

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

const testInputObj = new GraphQLInputObjectType({
Expand Down Expand Up @@ -681,3 +690,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: Kind.STRING, 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']);
});
});
Loading

0 comments on commit ba6c1e6

Please sign in to comment.