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

semantic nullability proposal with single GraphQLSemanticNullable wrapper type #4338

Draft
wants to merge 36 commits into
base: 16.x.x
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
fb9bd1f
New GraphQLSemanticNonNull type
benjie Sep 14, 2024
0c64761
Handle isNonNullType
benjie Sep 14, 2024
934c634
More fixes
benjie Sep 14, 2024
48c7b53
More fixes
benjie Sep 14, 2024
b758b67
Yet more updates
benjie Sep 14, 2024
e309ed5
Recognize in introspection, enable disabling null bubbling
benjie Sep 14, 2024
f599c4e
Lint fixes
benjie Sep 14, 2024
b7e2c7f
More missing pieces
benjie Sep 14, 2024
033e917
More fixes
benjie Sep 14, 2024
2787de0
Fix schema
benjie Sep 14, 2024
e029b6d
Fix another test
benjie Sep 14, 2024
f69db21
More minor test fixes
benjie Sep 14, 2024
e73c4ba
Fix introspection test
benjie Sep 14, 2024
8cc7fab
Add support for * to lexer
benjie Sep 14, 2024
6b0611d
Allow specifying errorPropagation at top level
benjie Sep 14, 2024
dd60b9e
Factor into getIntrospectionQuery
benjie Sep 14, 2024
3e01bb2
Lint
benjie Sep 14, 2024
0df7bdc
Prettier
benjie Sep 14, 2024
36b3cf2
parser tests passing
twof Oct 30, 2024
69739eb
Add semantic optional type
twof Nov 7, 2024
4dcf01c
printer and parser tests passing
twof Nov 7, 2024
509d0c6
some new semanticNullability execution tests
twof Nov 8, 2024
71e4057
SemanticNonNull halts null propagation
twof Nov 8, 2024
5cdbf81
SemanticOptional cleared
twof Nov 8, 2024
3099d63
logging cleanup
twof Nov 8, 2024
9e4bf7d
rename to SemanticNullable
twof Nov 8, 2024
7002eb1
better SemanticNullable docs
twof Nov 8, 2024
6a63f91
move semantic nullability tests to their own file
twof Nov 8, 2024
3d7cd06
fix git status
twof Nov 8, 2024
9247ff2
run prettier
twof Nov 8, 2024
e6c2239
Add comment to parser about document directive
twof Nov 8, 2024
f45b474
use semantic nullable wrapper only
yaacovCR Nov 10, 2024
e6afbfd
use expectJSON and other usual testing shorthands
yaacovCR Nov 10, 2024
7c737fe
fix sp
yaacovCR Feb 2, 2025
4ad3587
fix types
yaacovCR Feb 2, 2025
a0ca9d9
add actually printing the semantic nullability directive
yaacovCR Feb 2, 2025
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
1 change: 1 addition & 0 deletions src/__tests__/starWarsIntrospection-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ describe('Star Wars Introspection Tests', () => {
{ name: '__TypeKind' },
{ name: '__Field' },
{ name: '__InputValue' },
{ name: '__TypeNullability' },
{ name: '__EnumValue' },
{ name: '__Directive' },
{ name: '__DirectiveLocation' },
Expand Down
2 changes: 2 additions & 0 deletions src/execution/__tests__/executor-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,7 @@ describe('Execute: Handles basic execution tasks', () => {
'rootValue',
'operation',
'variableValues',
'errorPropagation',
);

const operation = document.definitions[0];
Expand All @@ -275,6 +276,7 @@ describe('Execute: Handles basic execution tasks', () => {
schema,
rootValue,
operation,
errorPropagation: true,
});

const field = operation.selectionSet.selections[0];
Expand Down
180 changes: 180 additions & 0 deletions src/execution/__tests__/semantic-nullability-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
import { describe, it } from 'mocha';

import { expectJSON } from '../../__testUtils__/expectJSON';

import type { ObjMap } from '../../jsutils/ObjMap';

import { parse } from '../../language/parser';

import {
GraphQLNonNull,
GraphQLObjectType,
GraphQLSemanticNullable,
} from '../../type/definition';
import { GraphQLString } from '../../type/scalars';
import { GraphQLSchema } from '../../type/schema';

import { execute } from '../execute';

describe('Execute: Handles Semantic Nullability', () => {
const DeepDataType = new GraphQLObjectType({
name: 'DeepDataType',
fields: {
f: { type: new GraphQLNonNull(GraphQLString) },
},
});

const DataType: GraphQLObjectType = new GraphQLObjectType({
name: 'DataType',
fields: () => ({
a: { type: new GraphQLSemanticNullable(GraphQLString) },
b: { type: GraphQLString },
c: { type: new GraphQLNonNull(GraphQLString) },
d: { type: DeepDataType },
}),
});

const schema = new GraphQLSchema({
useSemanticNullability: true,
query: DataType,
});

function executeWithSemanticNullability(
query: string,
rootValue: ObjMap<unknown>,
) {
return execute({
schema,
document: parse(query),
rootValue,
});
}

it('SemanticNonNull throws error on null without error', async () => {
const data = {
b: () => null,
};

const query = `
query {
b
}
`;

const result = await executeWithSemanticNullability(query, data);

expectJSON(result).toDeepEqual({
data: {
b: null,
},
errors: [
{
message:
'Cannot return null for semantic-non-nullable field DataType.b.',
path: ['b'],
locations: [{ line: 3, column: 9 }],
},
],
});
});

it('SemanticNonNull succeeds on null with error', async () => {
const data = {
b: () => {
throw new Error('Something went wrong');
},
};

const query = `
query {
b
}
`;

const result = await executeWithSemanticNullability(query, data);

expectJSON(result).toDeepEqual({
data: {
b: null,
},
errors: [
{
message: 'Something went wrong',
path: ['b'],
locations: [{ line: 3, column: 9 }],
},
],
});
});

it('SemanticNonNull halts null propagation', async () => {
const data = {
d: () => ({
f: () => null,
}),
};

const query = `
query {
d {
f
}
}
`;

const result = await executeWithSemanticNullability(query, data);

expectJSON(result).toDeepEqual({
data: {
d: null,
},
errors: [
{
message: 'Cannot return null for non-nullable field DeepDataType.f.',
path: ['d', 'f'],
locations: [{ line: 4, column: 11 }],
},
],
});
});

it('SemanticNullable allows null values', async () => {
const data = {
a: () => null,
};

const query = `
query {
a
}
`;

const result = await executeWithSemanticNullability(query, data);

expectJSON(result).toDeepEqual({
data: {
a: null,
},
});
});

it('SemanticNullable allows non-null values', async () => {
const data = {
a: () => 'Apple',
};

const query = `
query {
a
}
`;

const result = await executeWithSemanticNullability(query, data);

expectJSON(result).toDeepEqual({
data: {
a: 'Apple',
},
});
});
});
116 changes: 66 additions & 50 deletions src/execution/execute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import {
isListType,
isNonNullType,
isObjectType,
isSemanticNullableType,
} from '../type/definition';
import {
SchemaMetaFieldDef,
Expand Down Expand Up @@ -115,6 +116,7 @@ export interface ExecutionContext {
typeResolver: GraphQLTypeResolver<any, any>;
subscribeFieldResolver: GraphQLFieldResolver<any, any>;
errors: Array<GraphQLError>;
errorPropagation: boolean;
}

/**
Expand Down Expand Up @@ -152,6 +154,12 @@ export interface ExecutionArgs {
fieldResolver?: Maybe<GraphQLFieldResolver<any, any>>;
typeResolver?: Maybe<GraphQLTypeResolver<any, any>>;
subscribeFieldResolver?: Maybe<GraphQLFieldResolver<any, any>>;
/**
* Set to `false` to disable error propagation. Experimental.
*
* @experimental
*/
errorPropagation?: boolean;
}

/**
Expand Down Expand Up @@ -286,6 +294,7 @@ export function buildExecutionContext(
fieldResolver,
typeResolver,
subscribeFieldResolver,
errorPropagation,
} = args;

let operation: OperationDefinitionNode | undefined;
Expand Down Expand Up @@ -347,6 +356,7 @@ export function buildExecutionContext(
typeResolver: typeResolver ?? defaultTypeResolver,
subscribeFieldResolver: subscribeFieldResolver ?? defaultFieldResolver,
errors: [],
errorPropagation: errorPropagation ?? true,
};
}

Expand Down Expand Up @@ -585,6 +595,7 @@ export function buildResolveInfo(
rootValue: exeContext.rootValue,
operation: exeContext.operation,
variableValues: exeContext.variableValues,
errorPropagation: exeContext.errorPropagation,
};
}

Expand All @@ -595,7 +606,7 @@ function handleFieldError(
): null {
// If the field type is non-nullable, then it is resolved without any
// protection from errors, however it still properly locates the error.
if (isNonNullType(returnType)) {
if (exeContext.errorPropagation && isNonNullType(returnType)) {
throw error;
}

Expand Down Expand Up @@ -639,78 +650,83 @@ function completeValue(
throw result;
}

// If field type is NonNull, complete for inner type, and throw field error
// if result is null.
let nonNull;
let semanticNull;
let nullableType;
if (isNonNullType(returnType)) {
const completed = completeValue(
exeContext,
returnType.ofType,
fieldNodes,
info,
path,
result,
);
if (completed === null) {
throw new Error(
`Cannot return null for non-nullable field ${info.parentType.name}.${info.fieldName}.`,
);
}
return completed;
nonNull = true;
nullableType = returnType.ofType;
} else if (isSemanticNullableType(returnType)) {
semanticNull = true;
nullableType = returnType.ofType;
} else {
nullableType = returnType;
}

// If result value is null or undefined then return null.
let completed;
if (result == null) {
return null;
}

// If field type is List, complete each item in the list with the inner type
if (isListType(returnType)) {
return completeListValue(
// If result value is null or undefined then return null.
completed = null;
} else if (isListType(nullableType)) {
// If field type is List, complete each item in the list with the inner type
completed = completeListValue(
exeContext,
returnType,
nullableType,
fieldNodes,
info,
path,
result,
);
}

// If field type is a leaf type, Scalar or Enum, serialize to a valid value,
// returning null if serialization is not possible.
if (isLeafType(returnType)) {
return completeLeafValue(returnType, result);
}

// If field type is an abstract type, Interface or Union, determine the
// runtime Object type and complete for that type.
if (isAbstractType(returnType)) {
return completeAbstractValue(
} else if (isLeafType(nullableType)) {
// If field type is a leaf type, Scalar or Enum, serialize to a valid value,
// returning null if serialization is not possible.
completed = completeLeafValue(nullableType, result);
} else if (isAbstractType(nullableType)) {
// If field type is an abstract type, Interface or Union, determine the
// runtime Object type and complete for that type.
completed = completeAbstractValue(
exeContext,
returnType,
nullableType,
fieldNodes,
info,
path,
result,
);
}

// If field type is Object, execute and complete all sub-selections.
if (isObjectType(returnType)) {
return completeObjectValue(
} else if (isObjectType(nullableType)) {
// If field type is Object, execute and complete all sub-selections.
completed = completeObjectValue(
exeContext,
returnType,
nullableType,
fieldNodes,
info,
path,
result,
);
} else {
/* c8 ignore next 6 */
// Not reachable, all possible output types have been considered.
invariant(
false,
'Cannot complete value of unexpected output type: ' +
inspect(nullableType),
);
}
/* c8 ignore next 6 */
// Not reachable, all possible output types have been considered.
invariant(
false,
'Cannot complete value of unexpected output type: ' + inspect(returnType),
);

if (completed === null) {
if (nonNull) {
throw new Error(
`Cannot return null for non-nullable field ${info.parentType.name}.${info.fieldName}.`,
);
}

if (!semanticNull && exeContext.schema.usingSemanticNullability) {
throw new Error(
`Cannot return null for semantic-non-nullable field ${info.parentType.name}.${info.fieldName}.`,
);
}
}

return completed;
}

/**
Expand Down
Loading
Loading