Skip to content

Commit c6e90eb

Browse files
author
Curtis Li
committed
Add parser support for string literal aliases
Summary: These are the graphql-js changes for a proposed spec change that changes the definition of an alias from: ``` Alias : Name : ``` ...to: ``` Alias : - Name : - StringValue : ``` At Meta, our GraphQL clients for both web and mobile care a lot about local data consistency. Local data consistency is when the client is able to reconcile data from multiple GraphQL responses in a local client-side cache which can be subscribed to. When data changes, we issue updates to these subscribers — which allows us to keep various screens "in-sync" and show the same view of the data. The canonical example of this on Facebook is if you navigate to the Groups page from a Feed post and join the group, then when you navigate back to Feed we should update the "Join Group" button in the post to "Joined". Local data consistency is supported today by Relay for JS clients (widely adopted within industry) and by Meta's internal mobile GraphQL client for Android/iOS clients. To support consistency, we need to be able to remap aliases/field names into their "canonical names". The canonical name is what we use to keep two fields consistent, as it represents the true definition of a field. Given a field selection: ``` alias: field(arg: "foo") ``` the canonical name would be: ``` field(arg:"foo") ``` Internally, we've explored various ways of doing this. We currently need to embed a lot of information about the schema and query in our clients; for example Relay creates a "normalization AST" with this information, and our internal mobile client requires all the information to be pre-compiled into the app binary. This leads to additional costs, e.g. binary size bloat or wire size costs. We've found that we can more efficiently deliver the canonical name information by embedding it into our response instead, which removes the need for pre-compiled metadata. We run a transform on our queries to add aliases for each field, and use the canonical name as the alias. However since the canonical name may contain non-supported characters (e.g. `(`, `)`, `$`), we are proposing a spec change to allow `StringValue` tokens as the alias. This would allow syntax such as: ``` "field(arg:\"foo\")": field(arg: "foo") ``` We've attempted alternative ways of implementing this, such as doing this transform during server-side execution (a spec violation, and high server overhead!) or delivering encoded aliases to abide by the `NameValue` specification (client parsing overhead for decoding!). Potential side effects / outcomes of this change: 1. Selection set conflict validation should still work out of the box, even if one selection is a string literal and the other is a normal `NameValue`. 2. Here we parse the `StringValue` into a `NameNode` (same as when parsing a `NaveValue`), which doesn't have any requirements on the name itself as far as I can tell. 3. We allow string literal aliases here but not number literals, which abides by the JSON specification. According to the JSON spec, map/object keys must be strings. Test Plan: `npm test`
1 parent 9c90a23 commit c6e90eb

4 files changed

Lines changed: 99 additions & 13 deletions

File tree

src/language/__tests__/parser-test.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { kitchenSinkQuery } from '../../__testUtils__/kitchenSinkQuery.js';
1111
import { inspect } from '../../jsutils/inspect.js';
1212

1313
import { Kind } from '../kinds.js';
14+
import type { ParseOptions } from '../parser.js';
1415
import { parse, parseConstValue, parseType, parseValue } from '../parser.js';
1516
import { Source } from '../source.js';
1617
import { TokenKind } from '../tokenKind.js';
@@ -19,8 +20,8 @@ function parseCCN(source: string) {
1920
return parse(source, { experimentalClientControlledNullability: true });
2021
}
2122

22-
function expectSyntaxError(text: string) {
23-
return expectToThrowJSON(() => parse(text));
23+
function expectSyntaxError(text: string, options?: ParseOptions | undefined) {
24+
return expectToThrowJSON(() => parse(text, options));
2425
}
2526

2627
describe('Parser', () => {
@@ -73,6 +74,13 @@ describe('Parser', () => {
7374
message: 'Syntax Error: Expected Name, found String "".',
7475
locations: [{ line: 1, column: 3 }],
7576
});
77+
78+
expectSyntaxError('{ ""', {
79+
experimentalParseStringLiteralAliases: true,
80+
}).to.deep.include({
81+
message: 'Syntax Error: Expected ":", found <EOF>.',
82+
locations: [{ line: 1, column: 5 }],
83+
});
7684
});
7785

7886
it('parse provides useful error when using source', () => {

src/language/parser.ts

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,23 @@ export interface ParseOptions {
130130
* future.
131131
*/
132132
experimentalClientControlledNullability?: boolean | undefined;
133+
134+
/**
135+
* EXPERIMENTAL:
136+
*
137+
* If enabled, the parser will understand and parse StringValues as aliases.
138+
*
139+
* The syntax looks like the following:
140+
*
141+
* ```graphql
142+
* {
143+
* "alias": field
144+
* }
145+
* ```
146+
* Note: this feature is experimental and may change or be removed in the
147+
* future.
148+
*/
149+
experimentalParseStringLiteralAliases?: boolean | undefined;
133150
}
134151

135152
/**
@@ -236,6 +253,17 @@ export class Parser {
236253
});
237254
}
238255

256+
/**
257+
* Converts a string lex token into a name parse node.
258+
*/
259+
parseStringLiteralAlias(): NameNode {
260+
const token = this.expectToken(TokenKind.STRING);
261+
return this.node<NameNode>(token, {
262+
kind: Kind.NAME,
263+
value: token.value,
264+
});
265+
}
266+
239267
// Implements the parsing rules in the Document section.
240268

241269
/**
@@ -454,14 +482,23 @@ export class Parser {
454482
parseField(): FieldNode {
455483
const start = this._lexer.token;
456484

457-
const nameOrAlias = this.parseName();
458485
let alias;
459486
let name;
460-
if (this.expectOptionalToken(TokenKind.COLON)) {
461-
alias = nameOrAlias;
487+
if (
488+
this._options.experimentalParseStringLiteralAliases &&
489+
this.peek(TokenKind.STRING)
490+
) {
491+
alias = this.parseStringLiteralAlias();
492+
this.expectToken(TokenKind.COLON);
462493
name = this.parseName();
463494
} else {
464-
name = nameOrAlias;
495+
const nameOrAlias = this.parseName();
496+
if (this.expectOptionalToken(TokenKind.COLON)) {
497+
alias = nameOrAlias;
498+
name = this.parseName();
499+
} else {
500+
name = nameOrAlias;
501+
}
465502
}
466503

467504
return this.node<FieldNode>(start, {

src/validation/__tests__/OverlappingFieldsCanBeMergedRule-test.ts

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { describe, it } from 'mocha';
22

3+
import type { ParseOptions } from '../../language/parser.js';
4+
35
import type { GraphQLSchema } from '../../type/schema.js';
46

57
import { buildSchema } from '../../utilities/buildASTSchema.js';
@@ -11,12 +13,16 @@ import {
1113
expectValidationErrorsWithSchema,
1214
} from './harness.js';
1315

14-
function expectErrors(queryStr: string) {
15-
return expectValidationErrors(OverlappingFieldsCanBeMergedRule, queryStr);
16+
function expectErrors(queryStr: string, options?: ParseOptions | undefined) {
17+
return expectValidationErrors(
18+
OverlappingFieldsCanBeMergedRule,
19+
queryStr,
20+
options,
21+
);
1622
}
1723

18-
function expectValid(queryStr: string) {
19-
expectErrors(queryStr).toDeepEqual([]);
24+
function expectValid(queryStr: string, options?: ParseOptions | undefined) {
25+
expectErrors(queryStr, options).toDeepEqual([]);
2026
}
2127

2228
function expectErrorsWithSchema(schema: GraphQLSchema, queryStr: string) {
@@ -242,6 +248,39 @@ describe('Validate: Overlapping fields can be merged', () => {
242248
]);
243249
});
244250

251+
it('Same literal aliases allowed on same field targets', () => {
252+
expectValid(
253+
`
254+
fragment sameLiteralAliasesWithSameFieldTargets on Dog {
255+
"fido": name
256+
fido: name
257+
}
258+
`,
259+
{ experimentalParseStringLiteralAliases: true },
260+
);
261+
});
262+
263+
it('Same literal aliases with different field targets', () => {
264+
expectErrors(
265+
`
266+
fragment sameLiteralAliasesWithDifferentFieldTargets on Dog {
267+
"fido": name
268+
fido: nickname
269+
}
270+
`,
271+
{ experimentalParseStringLiteralAliases: true },
272+
).toDeepEqual([
273+
{
274+
message:
275+
'Fields "fido" conflict because "name" and "nickname" are different fields. Use different aliases on the fields to fetch both if this was intentional.',
276+
locations: [
277+
{ line: 3, column: 9 },
278+
{ line: 4, column: 9 },
279+
],
280+
},
281+
]);
282+
});
283+
245284
it('Same aliases allowed on non-overlapping fields', () => {
246285
// This is valid since no object can be both a "Dog" and a "Cat", thus
247286
// these fields can never overlap.

src/validation/__tests__/harness.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { expectJSON } from '../../__testUtils__/expectJSON.js';
22

33
import type { Maybe } from '../../jsutils/Maybe.js';
44

5+
import type { ParseOptions } from '../../language/parser.js';
56
import { parse } from '../../language/parser.js';
67

78
import type { GraphQLSchema } from '../../type/schema.js';
@@ -128,17 +129,18 @@ export function expectValidationErrorsWithSchema(
128129
schema: GraphQLSchema,
129130
rule: ValidationRule,
130131
queryStr: string,
132+
options?: ParseOptions | undefined,
131133
): any {
132-
const doc = parse(queryStr);
134+
const doc = parse(queryStr, options);
133135
const errors = validate(schema, doc, [rule]);
134136
return expectJSON(errors);
135137
}
136138

137139
export function expectValidationErrors(
138140
rule: ValidationRule,
139-
queryStr: string,
141+
queryStr: string, options?: ParseOptions | undefined,
140142
): any {
141-
return expectValidationErrorsWithSchema(testSchema, rule, queryStr);
143+
return expectValidationErrorsWithSchema(testSchema, rule, queryStr, options);
142144
}
143145

144146
export function expectSDLValidationErrors(

0 commit comments

Comments
 (0)