Generate Swift operation IDs and operation <--> operation ID mapping file (#147)

* Initial progress on Swift operationId generation

* Add dependency on crypto library for SHA256

* In Swift, operationId is computed and output with every operation class

* Factor out Swift operationId into its own function

* Write to a JSON file the mapping between operations and their ids (Swift-only)

* Update operationIds map to be keyed by operation name (which are guaranteed by apollo-codegen to be unique) and providing values with both operation id and source

* OperationIds map is keyed by id, and operation name is part of the value

* Use === instead of ==

* Update Swift Jest snapshots with new newline

* Fix missing comma

* Add fragments to classDeclarationForOperation invocation in Swift tests

* Add unit tests exercising operation id generation in Swift

* Move generation of operation IDs and operation source + fragments to compilation step rather than code generation step.
Also, when generating operation source + fragments, handle possibility of nested fragment references.

* Remove obsolete test checking for generated mapping between operation ids and sources on context (it's no longer done that way)

* Improve readability of generateOperationIds option in compileFromSource function in Swif tests

* Add Swift code generation test that verifies that, when there are nested fragment refrences, the correct source + fragments is generated for the operation id mapping file

* Fix typescript error related to operation ids map

* PR feedback and tweaks:
- Improve CLI message
- Remove unnecessary parameter in a function call
- Rename Swift operationId to operationIdentifier

* Update test snapshot
This commit is contained in:
kompfner authored and GitHub committed 2017-06-29 11:30:36 -07:00
1 parent c042a3b392
commit 703edf2586
7 files changed
+360 -21

No files matched your search

+1
View File
@@ -41,6 +41,7 @@
"inflected": "^2.0.2",
"mkdirp": "^0.5.1",
"node-fetch": "^1.5.3",
"sjcl": "^1.0.6",
"source-map-support": "^0.4.15",
"yargs": "^8.0.1"
},
+9 -1
View File
@@ -136,6 +136,12 @@ yargs
demand: false,
describe: "Name of the template literal tag used to identify template literals containing GraphQL queries in Javascript/Typescript code",
default: 'gql'
},
"operation-ids-path": {
demand: false,
describe: "Path to an operation id JSON map file. If specified, also stores the operation ids (hashes) as properties on operation types [currently Swift-only]",
default: null,
normalize: true
}
},
argv => {
@@ -155,7 +161,9 @@ yargs
passthroughCustomScalars: argv["passthrough-custom-scalars"] || argv["custom-scalars-prefix"] !== '',
customScalarsPrefix: argv["custom-scalars-prefix"] || '',
addTypename: argv["add-typename"],
namespace: argv.namespace
namespace: argv.namespace,
operationIdsPath: argv["operation-ids-path"],
generateOperationIds: !!argv["operation-ids-path"]
};
generate(inputPaths, argv.schema, argv.output, argv.target, argv.tagName, options);
+34
View File
@@ -44,6 +44,13 @@ import {
indent
} from './utilities/printing';
import {
flatMap,
uniqBy
} from 'lodash';
import * as sjcl from 'sjcl';
// Parts of this code are adapted from graphql-js
export function compileToIR(schema, document, options = { mergeInFieldsFromFragmentSpreads: true }) {
@@ -65,6 +72,10 @@ export function compileToIR(schema, document, options = { mergeInFieldsFromFragm
fragments[fragment.name.value] = compiler.compileFragment(fragment)
});
Object.values(operations).forEach(operation => {
augmentCompiledOperationWithFragments(operation, fragments)
});
const typesUsed = compiler.typesUsed;
return { schema, operations, fragments, typesUsed };
@@ -417,6 +428,29 @@ export class Compiler {
}
}
function augmentCompiledOperationWithFragments(compiledOperation, compiledFragments) {
const operationAndFragments = operationAndRelatedFragments(compiledOperation, compiledFragments);
compiledOperation.sourceWithFragments = operationAndFragments.map(operationOrFragment => {
return operationOrFragment.source;
}).join('\n');
const idBits = sjcl.hash.sha256.hash(compiledOperation.sourceWithFragments);
compiledOperation.operationId = sjcl.codec.hex.fromBits(idBits);
}
function operationAndRelatedFragments(compiledOperationOrFragment, allCompiledFragments) {
let result = flatMap(compiledOperationOrFragment.fragmentsReferenced, (fragmentName) => {
return operationAndRelatedFragments(allCompiledFragments[fragmentName], allCompiledFragments);
});
result.unshift(compiledOperationOrFragment);
result = uniqBy(result, (compiledOperationOrFragment) => {
return compiledOperationOrFragment.fragmentName;
});
result = result.sort((a, b) => {
return a.fragmentName > b.fragmentName;
});
return result;
}
function argumentsFromAST(args) {
return args && args.map(arg => {
return { name: arg.name.value, value: valueFromValueNode(arg.value) };
+21 -1
View File
@@ -1,4 +1,4 @@
import * as fs from 'fs'
import * as fs from 'fs';
import { ToolError, logError } from './errors'
import { loadSchema, loadAndMergeQueryDocuments } from './loading'
@@ -56,4 +56,24 @@ export default function generate(
} else {
console.log(output);
}
if (context.generateOperationIds) {
writeOperationIdsMap(context)
}
}
interface OperationIdsMap {
name: string,
source: string
}
function writeOperationIdsMap(context: any) {
let operationIdsMap: { [id: string]: OperationIdsMap } = {};
Object.values(context.operations).forEach(operation => {
operationIdsMap[operation.operationId] = {
name: operation.operationName,
source: operation.sourceWithFragments
};
});
fs.writeFileSync(context.operationIdsPath, JSON.stringify(operationIdsMap, null, 2));
}
+14
View File
@@ -92,6 +92,8 @@ export function classDeclarationForOperation(
fragmentSpreads,
fragmentsReferenced,
source,
sourceWithFragments,
operationId
}
) {
let className;
@@ -122,7 +124,10 @@ export function classDeclarationForOperation(
});
}
operationIdentifier(generator, { operationName, sourceWithFragments, operationId });
if (fragmentsReferenced && fragmentsReferenced.length > 0) {
generator.printNewlineIfNeeded();
generator.printOnNewline('public static var requestString: String { return operationString');
fragmentsReferenced.forEach(fragment => {
generator.print(`.appending(${structNameForFragmentName(fragment)}.fragmentString)`)
@@ -376,6 +381,15 @@ export function structDeclarationForSelectionSet(
});
}
function operationIdentifier(generator, { operationName, sourceWithFragments, operationId }) {
if (!generator.context.generateOperationIds) {
return
}
generator.printNewlineIfNeeded();
generator.printOnNewline(`public static let operationIdentifier = "${operationId}"`);
}
function propertyDeclarationForField(generator, field) {
const { kind, propertyName, typeName, type, isConditional, description } = propertyFromField(generator.context, field);
const responseName = field.responseName;
@@ -98,6 +98,7 @@ exports[`Swift code generation #classDeclarationForOperation() should generate a
\\" }\\" +
\\" }\\" +
\\"}\\"
public static var requestString: String { return operationString.appending(HeroDetails.fragmentString) }
public init() {
@@ -223,6 +224,7 @@ exports[`Swift code generation #classDeclarationForOperation() should generate a
\\" ...DroidDetails\\" +
\\" }\\" +
\\"}\\"
public static var requestString: String { return operationString.appending(DroidDetails.fragmentString) }
public init() {
@@ -372,6 +374,7 @@ exports[`Swift code generation #classDeclarationForOperation() should generate a
\\" ...HeroDetails\\" +
\\" }\\" +
\\"}\\"
public static var requestString: String { return operationString.appending(HeroDetails.fragmentString) }
public init() {
@@ -540,6 +543,120 @@ exports[`Swift code generation #classDeclarationForOperation() should generate a
}"
`;
exports[`Swift code generation #classDeclarationForOperation() when generateOperationIds is specified should generate a class declaration with an operationId property 1`] = `
"public final class HeroQuery: GraphQLQuery {
public static let operationString =
\\"query Hero {\\" +
\\" hero {\\" +
\\" ...HeroDetails\\" +
\\" }\\" +
\\"}\\"
public static let operationIdentifier = \\"90d0d674eb6a7b33776f63200d6cec3d09f881247c360a2ac9a29037a02210c4\\"
public static var requestString: String { return operationString.appending(HeroDetails.fragmentString) }
public init() {
}
public struct Data: GraphQLSelectionSet {
public static let possibleTypes = [\\"Query\\"]
public static let selections: [Selection] = [
Field(\\"hero\\", type: .object(Data.Hero.self)),
]
public var snapshot: Snapshot
public init(snapshot: Snapshot) {
self.snapshot = snapshot
}
public init(hero: Hero? = nil) {
self.init(snapshot: [\\"__typename\\": \\"Query\\", \\"hero\\": hero])
}
public var hero: Hero? {
get {
return (snapshot[\\"hero\\"]! as! Snapshot?).flatMap { Hero(snapshot: $0) }
}
set {
snapshot.updateValue(newValue?.snapshot, forKey: \\"hero\\")
}
}
public struct Hero: GraphQLSelectionSet {
public static let possibleTypes = [\\"Human\\", \\"Droid\\"]
public static let selections: [Selection] = [
Field(\\"name\\", type: .nonNull(.scalar(String.self))),
]
public var snapshot: Snapshot
public init(snapshot: Snapshot) {
self.snapshot = snapshot
}
public static func makeHuman(name: String) -> Hero {
return Hero(snapshot: [\\"__typename\\": \\"Human\\", \\"name\\": name])
}
public static func makeDroid(name: String) -> Hero {
return Hero(snapshot: [\\"__typename\\": \\"Droid\\", \\"name\\": name])
}
/// The name of the character
public var name: String {
get {
return snapshot[\\"name\\"]! as! String
}
set {
snapshot.updateValue(newValue, forKey: \\"name\\")
}
}
public var fragments: Fragments {
get {
return Fragments(snapshot: snapshot)
}
set {
snapshot = newValue.snapshot
}
}
public struct Fragments {
public var snapshot: Snapshot
public var heroDetails: HeroDetails {
get {
return HeroDetails(snapshot: snapshot)
}
set {
snapshot = newValue.snapshot
}
}
}
}
}
}"
`;
exports[`Swift code generation #classDeclarationForOperation() when generateOperationIds is specified should generate appropriate operation id mapping source when there are nested fragment references 1`] = `
"query Hero {
hero {
...HeroDetails
}
}
fragment HeroDetails on Character {
...HeroName
appearsIn
}
fragment HeroName on Character {
name
}"
`;
exports[`Swift code generation #initializerDeclarationForProperties() should generate initializer for a property 1`] = `
"public init(episode: Episode) {
self.episode = episode
+164 -19
View File
@@ -33,22 +33,26 @@ import { compileToIR } from '../../src/compilation';
describe('Swift code generation', function() {
let generator;
let resetGenerator;
let compileFromSource;
let addFragment;
beforeEach(function() {
const context = {
schema: schema,
operations: {},
fragments: {},
typesUsed: {}
}
generator = new CodeGenerator(context);
resetGenerator = () => {
const context = {
schema: schema,
operations: {},
fragments: {},
typesUsed: {}
}
generator = new CodeGenerator(context);
};
compileFromSource = (source) => {
compileFromSource = (source, options = { generateOperationIds: false }) => {
const document = parse(source);
const context = compileToIR(schema, document);
let context = compileToIR(schema, document);
options.generateOperationIds && Object.assign(context, { generateOperationIds: true, operationIdsMap: {} });
generator.context = context;
return context;
};
@@ -56,11 +60,13 @@ describe('Swift code generation', function() {
addFragment = (fragment) => {
generator.context.fragments[fragment.fragmentName] = fragment;
};
resetGenerator();
});
describe('#classDeclarationForOperation()', function() {
test(`should generate a class declaration for a query with variables`, function() {
const { operations } = compileFromSource(`
const { operations, fragments } = compileFromSource(`
query HeroName($episode: Episode) {
hero(episode: $episode) {
name
@@ -68,12 +74,12 @@ describe('Swift code generation', function() {
}
`);
classDeclarationForOperation(generator, operations['HeroName']);
classDeclarationForOperation(generator, operations['HeroName'], Object.values(fragments));
expect(generator.output).toMatchSnapshot();
});
test(`should generate a class declaration for a query with fragment spreads`, function() {
const { operations } = compileFromSource(`
const { operations, fragments } = compileFromSource(`
query Hero {
hero {
...HeroDetails
@@ -85,12 +91,12 @@ describe('Swift code generation', function() {
}
`);
classDeclarationForOperation(generator, operations['Hero']);
classDeclarationForOperation(generator, operations['Hero'], Object.values(fragments));
expect(generator.output).toMatchSnapshot();
});
test(`should generate a class declaration for a query with conditional fragment spreads`, function() {
const { operations } = compileFromSource(`
const { operations, fragments } = compileFromSource(`
query Hero {
hero {
...DroidDetails
@@ -102,12 +108,12 @@ describe('Swift code generation', function() {
}
`);
classDeclarationForOperation(generator, operations['Hero']);
classDeclarationForOperation(generator, operations['Hero'], Object.values(fragments));
expect(generator.output).toMatchSnapshot();
});
test(`should generate a class declaration for a query with a fragment spread nested in an inline fragment`, function() {
const { operations } = compileFromSource(`
const { operations, fragments } = compileFromSource(`
query Hero {
hero {
... on Droid {
@@ -121,13 +127,13 @@ describe('Swift code generation', function() {
}
`);
classDeclarationForOperation(generator, operations['Hero']);
classDeclarationForOperation(generator, operations['Hero'], Object.values(fragments));
expect(generator.output).toMatchSnapshot();
});
test(`should generate a class declaration for a mutation with variables`, function() {
const { operations } = compileFromSource(`
const { operations, fragments } = compileFromSource(`
mutation CreateReview($episode: Episode) {
createReview(episode: $episode, review: { stars: 5, commentary: "Wow!" }) {
stars
@@ -136,10 +142,149 @@ describe('Swift code generation', function() {
}
`);
classDeclarationForOperation(generator, operations['CreateReview']);
classDeclarationForOperation(generator, operations['CreateReview'], Object.values(fragments));
expect(generator.output).toMatchSnapshot();
});
describe(`when generateOperationIds is specified`, function() {
let compileOptions = { generateOperationIds: true };
test(`should generate a class declaration with an operationId property`, function() {
const context = compileFromSource(`
query Hero {
hero {
...HeroDetails
}
}
fragment HeroDetails on Character {
name
}
`, compileOptions);
classDeclarationForOperation(generator, context.operations['Hero'], Object.values(context.fragments));
expect(generator.output).toMatchSnapshot();
});
test(`should generate different operation ids for different operations`, function() {
const context1 = compileFromSource(`
query Hero {
hero {
...HeroDetails
}
}
fragment HeroDetails on Character {
name
}
`, compileOptions);
classDeclarationForOperation(generator, context1.operations['Hero'], Object.values(context1.fragments));
const output1 = generator.output;
resetGenerator();
const context2 = compileFromSource(`
query Hero {
hero {
...HeroDetails
}
}
fragment HeroDetails on Character {
appearsIn
}
`, compileOptions);
classDeclarationForOperation(generator, context2.operations['Hero'], Object.values(context2.fragments));
const output2 = generator.output;
expect(output1).not.toBe(output2);
});
test(`should generate the same operation id regardless of operation formatting/commenting`, function() {
const context1 = compileFromSource(`
query HeroName($episode: Episode) {
hero(episode: $episode) {
name
}
}
`, compileOptions);
classDeclarationForOperation(generator, context1.operations['HeroName'], Object.values(context1.fragments));
const output1 = generator.output;
resetGenerator();
const context2 = compileFromSource(`
# Profound comment
query HeroName($episode:Episode) { hero(episode: $episode) { name } }
# Deeply meaningful comment
`, compileOptions);
classDeclarationForOperation(generator, context2.operations['HeroName'], Object.values(context2.fragments));
const output2 = generator.output;
expect(output1).toBe(output2);
});
test(`should generate the same operation id regardless of fragment order`, function() {
const context1 = compileFromSource(`
query Hero {
hero {
...HeroName
...HeroAppearsIn
}
}
fragment HeroName on Character {
name
}
fragment HeroAppearsIn on Character {
appearsIn
}
`, compileOptions);
classDeclarationForOperation(generator, context1.operations['Hero'], Object.values(context1.fragments));
const output1 = generator.output;
resetGenerator();
const context2 = compileFromSource(`
query Hero {
hero {
...HeroName
...HeroAppearsIn
}
}
fragment HeroAppearsIn on Character {
appearsIn
}
fragment HeroName on Character {
name
}
`, compileOptions);
classDeclarationForOperation(generator, context2.operations['Hero'], Object.values(context2.fragments));
const output2 = generator.output;
expect(output1).toBe(output2);
});
test(`should generate appropriate operation id mapping source when there are nested fragment references`, function() {
const source = `
query Hero {
hero {
...HeroDetails
}
}
fragment HeroName on Character {
name
}
fragment HeroDetails on Character {
...HeroName
appearsIn
}
`;
const context = compileFromSource(source, true);
expect(context.operations['Hero'].sourceWithFragments).toMatchSnapshot();
});
});
});
describe('#initializerDeclarationForProperties()', function() {