apollo-codegen-scala
Advanced tools
Comparing version 0.27.0 to 0.27.3
@@ -1,6 +0,6 @@ | ||
import CodeGenerator from 'apollo-codegen-core/lib/utilities/CodeGenerator'; | ||
import { LegacyCompilerContext, LegacyOperation, LegacyFragment, LegacyField, LegacyInlineFragment } from 'apollo-codegen-core/lib/compiler/legacyIR'; | ||
import { GraphQLType } from 'graphql'; | ||
import { Property } from './language'; | ||
import { GraphQLCompositeType } from 'graphql'; | ||
import CodeGenerator from "apollo-codegen-core/lib/utilities/CodeGenerator"; | ||
import { LegacyCompilerContext, LegacyOperation, LegacyFragment, LegacyField, LegacyInlineFragment } from "apollo-codegen-core/lib/compiler/legacyIR"; | ||
import { GraphQLType } from "graphql"; | ||
import { Property } from "./language"; | ||
import { GraphQLCompositeType } from "graphql"; | ||
export declare function generateSource(context: LegacyCompilerContext): string; | ||
@@ -7,0 +7,0 @@ export declare function classDeclarationForOperation(generator: CodeGenerator<LegacyCompilerContext, any>, { operationName, operationType, rootType, variables, fields, inlineFragments, fragmentSpreads, fragmentsReferenced, source, operationId }: LegacyOperation): void; |
@@ -13,3 +13,3 @@ "use strict"; | ||
const generator = new CodeGenerator_1.default(context); | ||
generator.printOnNewline('// This file was automatically generated and should not be edited.'); | ||
generator.printOnNewline("// This file was automatically generated and should not be edited."); | ||
generator.printNewline(); | ||
@@ -35,9 +35,9 @@ if (context.options.namespace) { | ||
switch (operationType) { | ||
case 'query': | ||
case "query": | ||
objectName = `${naming_1.operationClassName(operationName)}Query`; | ||
protocol = 'com.apollographql.scalajs.GraphQLQuery'; | ||
protocol = "com.apollographql.scalajs.GraphQLQuery"; | ||
break; | ||
case 'mutation': | ||
case "mutation": | ||
objectName = `${naming_1.operationClassName(operationName)}Mutation`; | ||
protocol = 'com.apollographql.scalajs.GraphQLMutation'; | ||
protocol = "com.apollographql.scalajs.GraphQLMutation"; | ||
break; | ||
@@ -49,6 +49,6 @@ default: | ||
objectName, | ||
superclass: protocol, | ||
superclass: protocol | ||
}, () => { | ||
if (source) { | ||
generator.printOnNewline('val operationString ='); | ||
generator.printOnNewline("val operationString ="); | ||
generator.withIndent(() => { | ||
@@ -63,11 +63,11 @@ values_1.multilineString(generator, source); | ||
generator.printNewlineIfNeeded(); | ||
generator.printOnNewline('val requestString: String = { operationString'); | ||
generator.printOnNewline("val requestString: String = { operationString"); | ||
fragmentsReferenced.forEach(fragment => { | ||
generator.print(` + ${naming_1.caseClassNameForFragmentName(fragment)}.fragmentString`); | ||
}); | ||
generator.print(' }'); | ||
generator.printOnNewline('val operation = com.apollographql.scalajs.gql(requestString)'); | ||
generator.print(" }"); | ||
generator.printOnNewline("val operation = com.apollographql.scalajs.gql(requestString)"); | ||
} | ||
else { | ||
generator.printOnNewline('val operation = com.apollographql.scalajs.gql(operationString)'); | ||
generator.printOnNewline("val operation = com.apollographql.scalajs.gql(operationString)"); | ||
} | ||
@@ -82,3 +82,6 @@ generator.printNewlineIfNeeded(); | ||
}); | ||
language_1.caseClassDeclaration(generator, { caseClassName: 'Variables', description: '', params: properties.map(p => { | ||
language_1.caseClassDeclaration(generator, { | ||
caseClassName: "Variables", | ||
description: "", | ||
params: properties.map(p => { | ||
return { | ||
@@ -88,6 +91,7 @@ name: p.propertyName, | ||
}; | ||
}) }, () => { }); | ||
}) | ||
}, () => { }); | ||
} | ||
else { | ||
generator.printOnNewline('type Variables = Unit'); | ||
generator.printOnNewline("type Variables = Unit"); | ||
} | ||
@@ -114,3 +118,3 @@ caseClassDeclarationForSelectionSet(generator, { | ||
if (source) { | ||
generator.printOnNewline('val fragmentString ='); | ||
generator.printOnNewline("val fragmentString ="); | ||
generator.withIndent(() => { | ||
@@ -124,3 +128,5 @@ values_1.multilineString(generator, source); | ||
function caseClassDeclarationForSelectionSet(generator, { caseClassName, parentType, fields, inlineFragments, fragmentSpreads, viewableAs }, objectClosure) { | ||
const possibleTypes = parentType ? types_1.possibleTypesForType(generator.context, parentType) : null; | ||
const possibleTypes = parentType | ||
? types_1.possibleTypesForType(generator.context, parentType) | ||
: null; | ||
if (!possibleTypes || possibleTypes.length == 1) { | ||
@@ -130,8 +136,11 @@ const properties = fields | ||
.filter(field => field.propertyName != "__typename"); | ||
language_1.caseClassDeclaration(generator, { caseClassName, params: properties.map(p => { | ||
language_1.caseClassDeclaration(generator, { | ||
caseClassName, | ||
params: properties.map(p => { | ||
return { | ||
name: p.responseName, | ||
type: p.typeName, | ||
type: p.typeName | ||
}; | ||
}) }, () => { }); | ||
}) | ||
}, () => { }); | ||
} | ||
@@ -143,10 +152,14 @@ else { | ||
.filter(field => field.propertyName != "__typename"); | ||
language_1.caseClassDeclaration(generator, { caseClassName, params: properties.map(p => { | ||
language_1.caseClassDeclaration(generator, { | ||
caseClassName, | ||
params: properties.map(p => { | ||
return { | ||
name: p.responseName, | ||
type: p.typeName, | ||
type: p.typeName | ||
}; | ||
}), superclass: 'slinky.readwrite.WithRaw' }, () => { | ||
}), | ||
superclass: "slinky.readwrite.WithRaw" | ||
}, () => { | ||
if (inlineFragments && inlineFragments.length > 0) { | ||
inlineFragments.forEach((inlineFragment) => { | ||
inlineFragments.forEach(inlineFragment => { | ||
const fragClass = naming_1.caseClassNameForInlineFragment(inlineFragment); | ||
@@ -175,3 +188,3 @@ generator.printOnNewline(`def as${inlineFragment.typeCondition}`); | ||
if (inlineFragments && inlineFragments.length > 0) { | ||
inlineFragments.forEach((inlineFragment) => { | ||
inlineFragments.forEach(inlineFragment => { | ||
caseClassDeclarationForSelectionSet(generator, { | ||
@@ -184,4 +197,4 @@ caseClassName: naming_1.caseClassNameForInlineFragment(inlineFragment), | ||
caseClassName, | ||
properties, | ||
}, | ||
properties | ||
} | ||
}); | ||
@@ -194,8 +207,10 @@ }); | ||
generator.printNewlineIfNeeded(); | ||
generator.printOnNewline('val possibleTypes = scala.collection.Set('); | ||
generator.print(printing_1.join(Array.from(possibleTypes).map(type => `"${String(type)}"`), ', ')); | ||
generator.print(')'); | ||
generator.printOnNewline("val possibleTypes = scala.collection.Set("); | ||
generator.print(printing_1.join(Array.from(possibleTypes).map(type => `"${String(type)}"`), ", ")); | ||
generator.print(")"); | ||
} | ||
if (viewableAs) { | ||
generator.printOnNewline(`implicit def to${viewableAs.caseClassName}(a: ${caseClassName}): ${viewableAs.caseClassName} = ${viewableAs.caseClassName}(${viewableAs.properties.map(p => "a." + p.responseName).join(', ')})`); | ||
generator.printOnNewline(`implicit def to${viewableAs.caseClassName}(a: ${caseClassName}): ${viewableAs.caseClassName} = ${viewableAs.caseClassName}(${viewableAs.properties | ||
.map(p => "a." + p.responseName) | ||
.join(", ")})`); | ||
} | ||
@@ -207,7 +222,11 @@ if (fragmentSpreads) { | ||
if (alwaysDefined) { | ||
generator.printOnNewline(`implicit def to${s}(a: ${caseClassName}): ${s} = ${s}(${(fragment.fields || []).map(p => "a." + p.responseName).join(', ')})`); | ||
generator.printOnNewline(`implicit def to${s}(a: ${caseClassName}): ${s} = ${s}(${(fragment.fields || []) | ||
.map(p => "a." + p.responseName) | ||
.join(", ")})`); | ||
} | ||
}); | ||
} | ||
fields.filter(field => graphql_1.isCompositeType(graphql_1.getNamedType(field.type))).forEach(field => { | ||
fields | ||
.filter(field => graphql_1.isCompositeType(graphql_1.getNamedType(field.type))) | ||
.forEach(field => { | ||
caseClassDeclarationForSelectionSet(generator, { | ||
@@ -261,3 +280,6 @@ caseClassName: naming_1.caseClassNameForPropertyName(field.responseName), | ||
const properties = fields.map(field => naming_1.propertyFromInputField(generator.context, field, generator.context.options.namespace)); | ||
language_1.caseClassDeclaration(generator, { caseClassName, description: description || undefined, params: properties.map(p => { | ||
language_1.caseClassDeclaration(generator, { | ||
caseClassName, | ||
description: description || undefined, | ||
params: properties.map(p => { | ||
return { | ||
@@ -268,4 +290,5 @@ name: p.propertyName, | ||
}; | ||
}) }, () => { }); | ||
}) | ||
}, () => { }); | ||
} | ||
//# sourceMappingURL=codeGeneration.js.map |
@@ -1,1 +0,1 @@ | ||
export { generateSource } from './codeGeneration'; | ||
export { generateSource } from "./codeGeneration"; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
function comment(generator, comment) { | ||
const split = comment ? comment.split('\n') : []; | ||
const split = comment ? comment.split("\n") : []; | ||
if (split.length > 0) { | ||
generator.printOnNewline('/**'); | ||
generator.printOnNewline("/**"); | ||
split.forEach(line => { | ||
generator.printOnNewline(` * ${line.trim()}`); | ||
}); | ||
generator.printOnNewline(' */'); | ||
generator.printOnNewline(" */"); | ||
} | ||
@@ -22,3 +22,3 @@ } | ||
generator.printNewlineIfNeeded(); | ||
generator.printOnNewline(`object ${objectName}` + (superclass ? ` extends ${superclass}` : '')); | ||
generator.printOnNewline(`object ${objectName}` + (superclass ? ` extends ${superclass}` : "")); | ||
generator.pushScope({ typeName: objectName }); | ||
@@ -36,6 +36,9 @@ if (closure) { | ||
} | ||
const paramsSection = (params || []).map(v => { | ||
return v.name + ": " + v.type + (v.defaultValue ? ` = ${v.defaultValue}` : ""); | ||
}).join(', '); | ||
generator.printOnNewline(`case class ${caseClassName}(${paramsSection})` + (superclass ? ` extends ${superclass}` : '')); | ||
const paramsSection = (params || []) | ||
.map(v => { | ||
return (v.name + ": " + v.type + (v.defaultValue ? ` = ${v.defaultValue}` : "")); | ||
}) | ||
.join(", "); | ||
generator.printOnNewline(`case class ${caseClassName}(${paramsSection})` + | ||
(superclass ? ` extends ${superclass}` : "")); | ||
generator.pushScope({ typeName: caseClassName }); | ||
@@ -63,10 +66,29 @@ if (closure) { | ||
const reservedKeywords = new Set([ | ||
'case', 'catch', 'class', 'def', 'do', 'else', | ||
'extends', 'false', 'final', 'for', 'if', 'match', | ||
'new', 'null', 'throw', 'trait', 'true', 'try', 'until', | ||
'val', 'var', 'while', 'with' | ||
"case", | ||
"catch", | ||
"class", | ||
"def", | ||
"do", | ||
"else", | ||
"extends", | ||
"false", | ||
"final", | ||
"for", | ||
"if", | ||
"match", | ||
"new", | ||
"null", | ||
"throw", | ||
"trait", | ||
"true", | ||
"try", | ||
"until", | ||
"val", | ||
"var", | ||
"while", | ||
"with" | ||
]); | ||
function escapeIdentifierIfNeeded(identifier) { | ||
if (reservedKeywords.has(identifier)) { | ||
return '`' + identifier + '`'; | ||
return "`" + identifier + "`"; | ||
} | ||
@@ -73,0 +95,0 @@ else { |
@@ -1,4 +0,4 @@ | ||
import { Property } from './language'; | ||
import { LegacyCompilerContext, LegacyField, LegacyInlineFragment } from 'apollo-codegen-core/lib/compiler/legacyIR'; | ||
import { GraphQLInputField } from 'graphql'; | ||
import { Property } from "./language"; | ||
import { LegacyCompilerContext, LegacyField, LegacyInlineFragment } from "apollo-codegen-core/lib/compiler/legacyIR"; | ||
import { GraphQLInputField } from "graphql"; | ||
export declare function enumCaseName(name: string): string; | ||
@@ -5,0 +5,0 @@ export declare function operationClassName(name: string): string; |
@@ -26,3 +26,3 @@ "use strict"; | ||
function caseClassNameForInlineFragment(inlineFragment) { | ||
return 'As' + change_case_1.pascalCase(String(inlineFragment.typeCondition)); | ||
return "As" + change_case_1.pascalCase(String(inlineFragment.typeCondition)); | ||
} | ||
@@ -43,9 +43,15 @@ exports.caseClassNameForInlineFragment = caseClassNameForInlineFragment; | ||
language_1.escapeIdentifierIfNeeded(change_case_1.pascalCase(Inflector.singularize(name))) | ||
], '.'); | ||
], "."); | ||
const typeName = types_1.typeNameFromGraphQLType(context, type, bareTypeName, isOptional, true); | ||
return Object.assign({}, field, { propertyName, typeName, isOptional, isList, description: field.description || undefined }); | ||
return Object.assign({}, field, { propertyName, | ||
typeName, | ||
isOptional, | ||
isList, description: field.description || undefined }); | ||
} | ||
else { | ||
const typeName = types_1.typeNameFromGraphQLType(context, type, undefined, isOptional, true); | ||
return Object.assign({}, field, { propertyName, typeName, isOptional, isList, description: field.description || undefined }); | ||
return Object.assign({}, field, { propertyName, | ||
typeName, | ||
isOptional, | ||
isList, description: field.description || undefined }); | ||
} | ||
@@ -67,3 +73,3 @@ } | ||
language_1.escapeIdentifierIfNeeded(change_case_1.pascalCase(Inflector.singularize(name))) | ||
], '.'); | ||
], "."); | ||
const typeName = types_1.typeNameFromGraphQLType(context, type, bareTypeName, isOptional); | ||
@@ -70,0 +76,0 @@ return Object.assign({}, field, { propertyName, typeName, isOptional, isList }); |
@@ -1,5 +0,5 @@ | ||
import { GraphQLList, GraphQLNonNull, GraphQLScalarType, GraphQLEnumType } from 'graphql'; | ||
import { LegacyCompilerContext } from 'apollo-codegen-core/lib/compiler/legacyIR'; | ||
import { GraphQLType } from 'graphql'; | ||
import { GraphQLList, GraphQLNonNull, GraphQLScalarType, GraphQLEnumType } from "graphql"; | ||
import { LegacyCompilerContext } from "apollo-codegen-core/lib/compiler/legacyIR"; | ||
import { GraphQLType } from "graphql"; | ||
export declare function possibleTypesForType(context: LegacyCompilerContext, type: GraphQLType): ReadonlyArray<import("graphql/type/definition").GraphQLObjectType> | (GraphQLScalarType | import("graphql/type/definition").GraphQLObjectType | GraphQLEnumType | import("graphql/type/definition").GraphQLInputObjectType | GraphQLList<any> | GraphQLNonNull<any>)[]; | ||
export declare function typeNameFromGraphQLType(context: LegacyCompilerContext, type: GraphQLType, bareTypeName?: string, isOptional?: boolean, isInputObject?: boolean): string; |
@@ -5,7 +5,7 @@ "use strict"; | ||
const builtInScalarMap = { | ||
[graphql_1.GraphQLString.name]: 'String', | ||
[graphql_1.GraphQLInt.name]: 'Int', | ||
[graphql_1.GraphQLFloat.name]: 'Double', | ||
[graphql_1.GraphQLBoolean.name]: 'Boolean', | ||
[graphql_1.GraphQLID.name]: 'String', | ||
[graphql_1.GraphQLString.name]: "String", | ||
[graphql_1.GraphQLInt.name]: "Int", | ||
[graphql_1.GraphQLFloat.name]: "Double", | ||
[graphql_1.GraphQLBoolean.name]: "Boolean", | ||
[graphql_1.GraphQLID.name]: "String" | ||
}; | ||
@@ -30,3 +30,6 @@ function possibleTypesForType(context, type) { | ||
if (type instanceof graphql_1.GraphQLList) { | ||
typeName = 'Seq[' + typeNameFromGraphQLType(context, type.ofType, bareTypeName) + ']'; | ||
typeName = | ||
"Seq[" + | ||
typeNameFromGraphQLType(context, type.ofType, bareTypeName) + | ||
"]"; | ||
} | ||
@@ -42,8 +45,15 @@ else if (type instanceof graphql_1.GraphQLScalarType) { | ||
} | ||
return isOptional ? (isInputObject ? `scala.scalajs.js.UndefOr[${typeName}]` : `Option[${typeName}]`) : typeName; | ||
return isOptional | ||
? isInputObject | ||
? `scala.scalajs.js.UndefOr[${typeName}]` | ||
: `Option[${typeName}]` | ||
: typeName; | ||
} | ||
exports.typeNameFromGraphQLType = typeNameFromGraphQLType; | ||
function typeNameForScalarType(context, type) { | ||
return builtInScalarMap[type.name] || (context.options.passthroughCustomScalars ? context.options.customScalarsPrefix + type.name : graphql_1.GraphQLString.name); | ||
return (builtInScalarMap[type.name] || | ||
(context.options.passthroughCustomScalars | ||
? context.options.customScalarsPrefix + type.name | ||
: graphql_1.GraphQLString.name)); | ||
} | ||
//# sourceMappingURL=types.js.map |
@@ -1,4 +0,4 @@ | ||
import { LegacyCompilerContext } from 'apollo-codegen-core/lib/compiler/legacyIR'; | ||
import CodeGenerator from 'apollo-codegen-core/lib/utilities/CodeGenerator'; | ||
import { LegacyCompilerContext } from "apollo-codegen-core/lib/compiler/legacyIR"; | ||
import CodeGenerator from "apollo-codegen-core/lib/utilities/CodeGenerator"; | ||
export declare function escapedString(string: string): string; | ||
export declare function multilineString(generator: CodeGenerator<LegacyCompilerContext, any>, string: string): void; |
@@ -8,6 +8,6 @@ "use strict"; | ||
function multilineString(generator, string) { | ||
const lines = string.split('\n'); | ||
const lines = string.split("\n"); | ||
lines.forEach((line, index) => { | ||
const isLastLine = index != lines.length - 1; | ||
generator.printOnNewline(`"${escapedString(line)}"` + (isLastLine ? ' +' : '')); | ||
generator.printOnNewline(`"${escapedString(line)}"` + (isLastLine ? " +" : "")); | ||
}); | ||
@@ -14,0 +14,0 @@ } |
{ | ||
"name": "apollo-codegen-scala", | ||
"description": "Scala generator module for Apollo Codegen", | ||
"version": "0.27.0", | ||
"main": "./lib/index.js", | ||
"version": "0.27.3", | ||
"author": "Apollo GraphQL <opensource@apollographql.com>", | ||
"license": "MIT", | ||
"repository": { | ||
"type": "git", | ||
"url": "git+https://github.com/apollographql/apollo-cli.git" | ||
}, | ||
"homepage": "https://github.com/apollographql/apollo-cli", | ||
"bugs": "https://github.com/apollographql/apollo-cli/issues", | ||
"main": "lib/index.js", | ||
"types": "lib/index.d.ts", | ||
"scripts": { | ||
"clean": "rm -rf lib", | ||
"prebuild": "npm run clean", | ||
"build": "tsc -p .", | ||
"watch": "tsc -w -p .", | ||
"test": "./node_modules/.bin/jest", | ||
"prepack": "npm run build" | ||
"build": "tsc", | ||
"prepare": "npm run build" | ||
}, | ||
"repository": { | ||
"type": "git", | ||
"url": "apollographql/apollo-cli" | ||
}, | ||
"author": "Martijn Walraven <martijn@martijnwalraven.com>", | ||
"license": "MIT", | ||
"engines": { | ||
"node": ">=6.0", | ||
"npm": ">=5.0" | ||
"node": ">=8", | ||
"npm": ">=6" | ||
}, | ||
"devDependencies": { | ||
"@types/graphql": "^0.13.1", | ||
"@types/inflected": "^1.1.29", | ||
"graphql": "^0.13.1", | ||
"jest": "^22.0.3", | ||
"jest-matcher-utils": "^22.0.3", | ||
"lerna": "^2.11.0", | ||
"ts-jest": "^22.0.0", | ||
"typescript": "^2.6.2" | ||
}, | ||
"dependencies": { | ||
"apollo-codegen-core": "^0.27.0", | ||
"apollo-codegen-core": "0.27.3", | ||
"change-case": "^3.0.1", | ||
@@ -66,3 +57,4 @@ "inflected": "^2.0.3" | ||
} | ||
} | ||
}, | ||
"gitHead": "e8d31998beae239ea92e140c670f45412ca0ffd4" | ||
} |
@@ -7,3 +7,3 @@ import { | ||
GraphQLEnumType | ||
} from 'graphql'; | ||
} from "graphql"; | ||
@@ -15,13 +15,15 @@ import { | ||
caseClassDeclarationForSelectionSet, | ||
typeDeclarationForGraphQLType, | ||
} from '../codeGeneration'; | ||
typeDeclarationForGraphQLType | ||
} from "../codeGeneration"; | ||
import { loadSchema } from 'apollo-codegen-core/lib/loading'; | ||
const schema = loadSchema(require.resolve('../../../common-test/fixtures/starwars/schema.json')); | ||
import { loadSchema } from "apollo-codegen-core/lib/loading"; | ||
const schema = loadSchema( | ||
require.resolve("../../../common-test/fixtures/starwars/schema.json") | ||
); | ||
import CodeGenerator from 'apollo-codegen-core/lib/utilities/CodeGenerator'; | ||
import CodeGenerator from "apollo-codegen-core/lib/utilities/CodeGenerator"; | ||
import { compileToLegacyIR } from 'apollo-codegen-core/lib/compiler/legacyIR'; | ||
import { compileToLegacyIR } from "apollo-codegen-core/lib/compiler/legacyIR"; | ||
describe('Scala code generation', function() { | ||
describe("Scala code generation", function() { | ||
let generator; | ||
@@ -33,3 +35,2 @@ let resetGenerator; | ||
beforeEach(function() { | ||
resetGenerator = () => { | ||
@@ -41,3 +42,3 @@ const context = { | ||
typesUsed: {} | ||
} | ||
}; | ||
generator = new CodeGenerator(context); | ||
@@ -49,4 +50,9 @@ }; | ||
let context = compileToLegacyIR(schema, document); | ||
options.generateOperationIds && Object.assign(context.options, { generateOperationIds: true, operationIdsMap: {} }); | ||
options.namespace && Object.assign(context.options, { namespace: options.namespace }); | ||
options.generateOperationIds && | ||
Object.assign(context.options, { | ||
generateOperationIds: true, | ||
operationIdsMap: {} | ||
}); | ||
options.namespace && | ||
Object.assign(context.options, { namespace: options.namespace }); | ||
generator.context = context; | ||
@@ -56,3 +62,3 @@ return context; | ||
addFragment = (fragment) => { | ||
addFragment = fragment => { | ||
generator.context.fragments[fragment.fragmentName] = fragment; | ||
@@ -64,5 +70,6 @@ }; | ||
describe('#generateSource()', function() { | ||
describe("#generateSource()", function() { | ||
test(`should emit a package declaration when the namespace option is specified`, function() { | ||
const context = compileFromSource(` | ||
const context = compileFromSource( | ||
` | ||
query HeroName($episode: Episode) { | ||
@@ -73,3 +80,5 @@ hero(episode: $episode) { | ||
} | ||
`, { namespace: "hello.world" }); | ||
`, | ||
{ namespace: "hello.world" } | ||
); | ||
@@ -80,3 +89,3 @@ expect(generateSource(context)).toMatchSnapshot(); | ||
describe('#classDeclarationForOperation()', function() { | ||
describe("#classDeclarationForOperation()", function() { | ||
test(`should generate a class declaration for a query with variables`, function() { | ||
@@ -91,3 +100,7 @@ const { operations, fragments } = compileFromSource(` | ||
classDeclarationForOperation(generator, operations['HeroName'], Object.values(fragments)); | ||
classDeclarationForOperation( | ||
generator, | ||
operations["HeroName"], | ||
Object.values(fragments) | ||
); | ||
expect(generator.output).toMatchSnapshot(); | ||
@@ -109,3 +122,7 @@ }); | ||
classDeclarationForOperation(generator, operations['Hero'], Object.values(fragments)); | ||
classDeclarationForOperation( | ||
generator, | ||
operations["Hero"], | ||
Object.values(fragments) | ||
); | ||
expect(generator.output).toMatchSnapshot(); | ||
@@ -127,3 +144,7 @@ }); | ||
classDeclarationForOperation(generator, operations['Hero'], Object.values(fragments)); | ||
classDeclarationForOperation( | ||
generator, | ||
operations["Hero"], | ||
Object.values(fragments) | ||
); | ||
expect(generator.output).toMatchSnapshot(); | ||
@@ -147,3 +168,7 @@ }); | ||
classDeclarationForOperation(generator, operations['Hero'], Object.values(fragments)); | ||
classDeclarationForOperation( | ||
generator, | ||
operations["Hero"], | ||
Object.values(fragments) | ||
); | ||
@@ -163,3 +188,7 @@ expect(generator.output).toMatchSnapshot(); | ||
classDeclarationForOperation(generator, operations['CreateReview'], Object.values(fragments)); | ||
classDeclarationForOperation( | ||
generator, | ||
operations["CreateReview"], | ||
Object.values(fragments) | ||
); | ||
@@ -173,3 +202,4 @@ expect(generator.output).toMatchSnapshot(); | ||
test(`should generate a class declaration with an operationId property`, function() { | ||
const context = compileFromSource(` | ||
const context = compileFromSource( | ||
` | ||
query Hero { | ||
@@ -183,5 +213,11 @@ hero { | ||
} | ||
`, compileOptions); | ||
`, | ||
compileOptions | ||
); | ||
classDeclarationForOperation(generator, context.operations['Hero'], Object.values(context.fragments)); | ||
classDeclarationForOperation( | ||
generator, | ||
context.operations["Hero"], | ||
Object.values(context.fragments) | ||
); | ||
expect(generator.output).toMatchSnapshot(); | ||
@@ -191,3 +227,4 @@ }); | ||
test(`should generate different operation ids for different operations`, function() { | ||
const context1 = compileFromSource(` | ||
const context1 = compileFromSource( | ||
` | ||
query Hero { | ||
@@ -201,9 +238,16 @@ hero { | ||
} | ||
`, compileOptions); | ||
`, | ||
compileOptions | ||
); | ||
classDeclarationForOperation(generator, context1.operations['Hero'], Object.values(context1.fragments)); | ||
classDeclarationForOperation( | ||
generator, | ||
context1.operations["Hero"], | ||
Object.values(context1.fragments) | ||
); | ||
const output1 = generator.output; | ||
resetGenerator(); | ||
const context2 = compileFromSource(` | ||
const context2 = compileFromSource( | ||
` | ||
query Hero { | ||
@@ -217,5 +261,11 @@ hero { | ||
} | ||
`, compileOptions); | ||
`, | ||
compileOptions | ||
); | ||
classDeclarationForOperation(generator, context2.operations['Hero'], Object.values(context2.fragments)); | ||
classDeclarationForOperation( | ||
generator, | ||
context2.operations["Hero"], | ||
Object.values(context2.fragments) | ||
); | ||
const output2 = generator.output; | ||
@@ -227,3 +277,4 @@ | ||
test(`should generate the same operation id regardless of operation formatting/commenting`, function() { | ||
const context1 = compileFromSource(` | ||
const context1 = compileFromSource( | ||
` | ||
query HeroName($episode: Episode) { | ||
@@ -234,15 +285,28 @@ hero(episode: $episode) { | ||
} | ||
`, compileOptions); | ||
`, | ||
compileOptions | ||
); | ||
classDeclarationForOperation(generator, context1.operations['HeroName'], Object.values(context1.fragments)); | ||
classDeclarationForOperation( | ||
generator, | ||
context1.operations["HeroName"], | ||
Object.values(context1.fragments) | ||
); | ||
const output1 = generator.output; | ||
resetGenerator(); | ||
const context2 = compileFromSource(` | ||
const context2 = compileFromSource( | ||
` | ||
# Profound comment | ||
query HeroName($episode:Episode) { hero(episode: $episode) { name } } | ||
# Deeply meaningful comment | ||
`, compileOptions); | ||
`, | ||
compileOptions | ||
); | ||
classDeclarationForOperation(generator, context2.operations['HeroName'], Object.values(context2.fragments)); | ||
classDeclarationForOperation( | ||
generator, | ||
context2.operations["HeroName"], | ||
Object.values(context2.fragments) | ||
); | ||
const output2 = generator.output; | ||
@@ -254,3 +318,4 @@ | ||
test(`should generate the same operation id regardless of fragment order`, function() { | ||
const context1 = compileFromSource(` | ||
const context1 = compileFromSource( | ||
` | ||
query Hero { | ||
@@ -268,9 +333,16 @@ hero { | ||
} | ||
`, compileOptions); | ||
`, | ||
compileOptions | ||
); | ||
classDeclarationForOperation(generator, context1.operations['Hero'], Object.values(context1.fragments)); | ||
classDeclarationForOperation( | ||
generator, | ||
context1.operations["Hero"], | ||
Object.values(context1.fragments) | ||
); | ||
const output1 = generator.output; | ||
resetGenerator(); | ||
const context2 = compileFromSource(` | ||
const context2 = compileFromSource( | ||
` | ||
query Hero { | ||
@@ -288,5 +360,11 @@ hero { | ||
} | ||
`, compileOptions); | ||
`, | ||
compileOptions | ||
); | ||
classDeclarationForOperation(generator, context2.operations['Hero'], Object.values(context2.fragments)); | ||
classDeclarationForOperation( | ||
generator, | ||
context2.operations["Hero"], | ||
Object.values(context2.fragments) | ||
); | ||
const output2 = generator.output; | ||
@@ -313,9 +391,10 @@ | ||
const context = compileFromSource(source, true); | ||
expect(context.operations['Hero'].sourceWithFragments).toMatchSnapshot(); | ||
expect( | ||
context.operations["Hero"].sourceWithFragments | ||
).toMatchSnapshot(); | ||
}); | ||
}); | ||
}); | ||
describe('#caseClassDeclarationForFragment()', function() { | ||
describe("#caseClassDeclarationForFragment()", function() { | ||
test(`should generate a caseClass declaration for a fragment with an abstract type condition`, function() { | ||
@@ -329,3 +408,3 @@ const { fragments } = compileFromSource(` | ||
caseClassDeclarationForFragment(generator, fragments['HeroDetails']); | ||
caseClassDeclarationForFragment(generator, fragments["HeroDetails"]); | ||
@@ -343,3 +422,3 @@ expect(generator.output).toMatchSnapshot(); | ||
caseClassDeclarationForFragment(generator, fragments['DroidDetails']); | ||
caseClassDeclarationForFragment(generator, fragments["DroidDetails"]); | ||
@@ -359,3 +438,3 @@ expect(generator.output).toMatchSnapshot(); | ||
caseClassDeclarationForFragment(generator, fragments['HeroDetails']); | ||
caseClassDeclarationForFragment(generator, fragments["HeroDetails"]); | ||
@@ -377,3 +456,3 @@ expect(generator.output).toMatchSnapshot(); | ||
caseClassDeclarationForFragment(generator, fragments['HeroDetails']); | ||
caseClassDeclarationForFragment(generator, fragments["HeroDetails"]); | ||
@@ -384,11 +463,11 @@ expect(generator.output).toMatchSnapshot(); | ||
describe('#caseClassDeclarationForSelectionSet()', function() { | ||
describe("#caseClassDeclarationForSelectionSet()", function() { | ||
test(`should generate a caseClass declaration for a selection set`, function() { | ||
caseClassDeclarationForSelectionSet(generator, { | ||
caseClassName: 'Hero', | ||
parentType: schema.getType('Character'), | ||
caseClassName: "Hero", | ||
parentType: schema.getType("Character"), | ||
fields: [ | ||
{ | ||
responseName: 'name', | ||
fieldName: 'name', | ||
responseName: "name", | ||
fieldName: "name", | ||
type: GraphQLString | ||
@@ -404,8 +483,8 @@ } | ||
caseClassDeclarationForSelectionSet(generator, { | ||
caseClassName: 'Hero', | ||
parentType: schema.getType('Character'), | ||
caseClassName: "Hero", | ||
parentType: schema.getType("Character"), | ||
fields: [ | ||
{ | ||
responseName: 'private', | ||
fieldName: 'name', | ||
responseName: "private", | ||
fieldName: "name", | ||
type: GraphQLString | ||
@@ -421,13 +500,13 @@ } | ||
caseClassDeclarationForSelectionSet(generator, { | ||
caseClassName: 'Hero', | ||
parentType: schema.getType('Character'), | ||
caseClassName: "Hero", | ||
parentType: schema.getType("Character"), | ||
fields: [ | ||
{ | ||
responseName: 'friends', | ||
fieldName: 'friends', | ||
type: new GraphQLList(schema.getType('Character')), | ||
responseName: "friends", | ||
fieldName: "friends", | ||
type: new GraphQLList(schema.getType("Character")), | ||
fields: [ | ||
{ | ||
responseName: 'name', | ||
fieldName: 'name', | ||
responseName: "name", | ||
fieldName: "name", | ||
type: GraphQLString | ||
@@ -445,14 +524,14 @@ } | ||
addFragment({ | ||
fragmentName: 'HeroDetails', | ||
typeCondition: schema.getType('Character') | ||
fragmentName: "HeroDetails", | ||
typeCondition: schema.getType("Character") | ||
}); | ||
caseClassDeclarationForSelectionSet(generator, { | ||
caseClassName: 'Hero', | ||
parentType: schema.getType('Character'), | ||
fragmentSpreads: ['HeroDetails'], | ||
caseClassName: "Hero", | ||
parentType: schema.getType("Character"), | ||
fragmentSpreads: ["HeroDetails"], | ||
fields: [ | ||
{ | ||
responseName: 'name', | ||
fieldName: 'name', | ||
responseName: "name", | ||
fieldName: "name", | ||
type: GraphQLString | ||
@@ -468,14 +547,14 @@ } | ||
addFragment({ | ||
fragmentName: 'DroidDetails', | ||
typeCondition: schema.getType('Droid') | ||
fragmentName: "DroidDetails", | ||
typeCondition: schema.getType("Droid") | ||
}); | ||
caseClassDeclarationForSelectionSet(generator, { | ||
caseClassName: 'Hero', | ||
parentType: schema.getType('Character'), | ||
fragmentSpreads: ['DroidDetails'], | ||
caseClassName: "Hero", | ||
parentType: schema.getType("Character"), | ||
fragmentSpreads: ["DroidDetails"], | ||
fields: [ | ||
{ | ||
responseName: 'name', | ||
fieldName: 'name', | ||
responseName: "name", | ||
fieldName: "name", | ||
type: GraphQLString | ||
@@ -491,8 +570,8 @@ } | ||
caseClassDeclarationForSelectionSet(generator, { | ||
caseClassName: 'Hero', | ||
parentType: schema.getType('Character'), | ||
caseClassName: "Hero", | ||
parentType: schema.getType("Character"), | ||
fields: [ | ||
{ | ||
responseName: 'name', | ||
fieldName: 'name', | ||
responseName: "name", | ||
fieldName: "name", | ||
type: new GraphQLNonNull(GraphQLString) | ||
@@ -503,13 +582,13 @@ } | ||
{ | ||
typeCondition: schema.getType('Droid'), | ||
possibleTypes: ['Droid'], | ||
typeCondition: schema.getType("Droid"), | ||
possibleTypes: ["Droid"], | ||
fields: [ | ||
{ | ||
responseName: 'name', | ||
fieldName: 'name', | ||
responseName: "name", | ||
fieldName: "name", | ||
type: new GraphQLNonNull(GraphQLString) | ||
}, | ||
{ | ||
responseName: 'primaryFunction', | ||
fieldName: 'primaryFunction', | ||
responseName: "primaryFunction", | ||
fieldName: "primaryFunction", | ||
type: GraphQLString | ||
@@ -527,16 +606,16 @@ } | ||
addFragment({ | ||
fragmentName: 'HeroDetails', | ||
typeCondition: schema.getType('Character') | ||
fragmentName: "HeroDetails", | ||
typeCondition: schema.getType("Character") | ||
}); | ||
caseClassDeclarationForSelectionSet(generator, { | ||
caseClassName: 'Hero', | ||
parentType: schema.getType('Character'), | ||
caseClassName: "Hero", | ||
parentType: schema.getType("Character"), | ||
fields: [], | ||
inlineFragments: [ | ||
{ | ||
typeCondition: schema.getType('Droid'), | ||
possibleTypes: ['Droid'], | ||
typeCondition: schema.getType("Droid"), | ||
possibleTypes: ["Droid"], | ||
fields: [], | ||
fragmentSpreads: ['HeroDetails'], | ||
fragmentSpreads: ["HeroDetails"] | ||
} | ||
@@ -550,7 +629,7 @@ ] | ||
describe('#typeDeclarationForGraphQLType()', function() { | ||
test('should generate an enum declaration for a GraphQLEnumType', function() { | ||
const generator = new CodeGenerator({options: {}}); | ||
describe("#typeDeclarationForGraphQLType()", function() { | ||
test("should generate an enum declaration for a GraphQLEnumType", function() { | ||
const generator = new CodeGenerator({ options: {} }); | ||
typeDeclarationForGraphQLType(generator, schema.getType('Episode')); | ||
typeDeclarationForGraphQLType(generator, schema.getType("Episode")); | ||
@@ -560,7 +639,7 @@ expect(generator.output).toMatchSnapshot(); | ||
test('should escape identifiers in cases of enum declaration for a GraphQLEnumType', function() { | ||
const generator = new CodeGenerator({options: {}}); | ||
test("should escape identifiers in cases of enum declaration for a GraphQLEnumType", function() { | ||
const generator = new CodeGenerator({ options: {} }); | ||
const albumPrivaciesEnum = new GraphQLEnumType({ | ||
name: 'AlbumPrivacies', | ||
name: "AlbumPrivacies", | ||
values: { PUBLIC: { value: "PUBLIC" }, PRIVATE: { value: "PRIVATE" } } | ||
@@ -574,6 +653,6 @@ }); | ||
test('should generate a caseClass declaration for a GraphQLInputObjectType', function() { | ||
const generator = new CodeGenerator({options: {}}); | ||
test("should generate a caseClass declaration for a GraphQLInputObjectType", function() { | ||
const generator = new CodeGenerator({ options: {} }); | ||
typeDeclarationForGraphQLType(generator, schema.getType('ReviewInput')); | ||
typeDeclarationForGraphQLType(generator, schema.getType("ReviewInput")); | ||
@@ -580,0 +659,0 @@ expect(generator.output).toMatchSnapshot(); |
@@ -1,4 +0,4 @@ | ||
import { stripIndent } from 'common-tags'; | ||
import { stripIndent } from "common-tags"; | ||
import CodeGenerator from 'apollo-codegen-core/lib/utilities/CodeGenerator'; | ||
import CodeGenerator from "apollo-codegen-core/lib/utilities/CodeGenerator"; | ||
@@ -8,6 +8,6 @@ import { | ||
caseClassDeclaration, | ||
propertyDeclaration, | ||
} from '../language'; | ||
propertyDeclaration | ||
} from "../language"; | ||
describe('Scala code generation: Basic language constructs', function() { | ||
describe("Scala code generation: Basic language constructs", function() { | ||
let generator; | ||
@@ -20,5 +20,13 @@ | ||
test(`should generate a object declaration`, function() { | ||
objectDeclaration(generator, { objectName: 'Hero' }, () => { | ||
propertyDeclaration(generator, { propertyName: 'name', typeName: 'String' }, () => {}); | ||
propertyDeclaration(generator, { propertyName: 'age', typeName: 'Int' }, () => {}); | ||
objectDeclaration(generator, { objectName: "Hero" }, () => { | ||
propertyDeclaration( | ||
generator, | ||
{ propertyName: "name", typeName: "String" }, | ||
() => {} | ||
); | ||
propertyDeclaration( | ||
generator, | ||
{ propertyName: "age", typeName: "Int" }, | ||
() => {} | ||
); | ||
}); | ||
@@ -37,3 +45,10 @@ | ||
test(`should generate a case class declaration`, function() { | ||
caseClassDeclaration(generator, { caseClassName: 'Hero', params: [{name: 'name', type: 'String'}, {name: 'age', type: 'Int'}] }, () => {}); | ||
caseClassDeclaration( | ||
generator, | ||
{ | ||
caseClassName: "Hero", | ||
params: [{ name: "name", type: "String" }, { name: "age", type: "Int" }] | ||
}, | ||
() => {} | ||
); | ||
@@ -47,5 +62,19 @@ expect(generator.output).toBe(stripIndent` | ||
test(`should generate nested case class declarations`, function() { | ||
caseClassDeclaration(generator, { caseClassName: 'Hero', params: [{name: 'name', type: 'String'}, {name: 'age', type: 'Int'}] }, () => { | ||
caseClassDeclaration(generator, { caseClassName: 'Friend', params: [{name: 'name', type: 'String'}] }, () => {}); | ||
}); | ||
caseClassDeclaration( | ||
generator, | ||
{ | ||
caseClassName: "Hero", | ||
params: [{ name: "name", type: "String" }, { name: "age", type: "Int" }] | ||
}, | ||
() => { | ||
caseClassDeclaration( | ||
generator, | ||
{ | ||
caseClassName: "Friend", | ||
params: [{ name: "name", type: "String" }] | ||
}, | ||
() => {} | ||
); | ||
} | ||
); | ||
@@ -61,6 +90,26 @@ expect(generator.output).toBe(stripIndent` | ||
test(`should handle multi-line descriptions`, () => { | ||
caseClassDeclaration(generator, { caseClassName: 'Hero', description: 'A hero' }, () => { | ||
propertyDeclaration(generator, { propertyName: 'name', typeName: 'String', description: `A multiline comment \n on the hero's name.` }, () => {}); | ||
propertyDeclaration(generator, { propertyName: 'age', typeName: 'String', description: `A multiline comment \n on the hero's age.` }, () => {}); | ||
}); | ||
caseClassDeclaration( | ||
generator, | ||
{ caseClassName: "Hero", description: "A hero" }, | ||
() => { | ||
propertyDeclaration( | ||
generator, | ||
{ | ||
propertyName: "name", | ||
typeName: "String", | ||
description: `A multiline comment \n on the hero's name.` | ||
}, | ||
() => {} | ||
); | ||
propertyDeclaration( | ||
generator, | ||
{ | ||
propertyName: "age", | ||
typeName: "String", | ||
description: `A multiline comment \n on the hero's age.` | ||
}, | ||
() => {} | ||
); | ||
} | ||
); | ||
@@ -67,0 +116,0 @@ expect(generator.output).toMatchSnapshot(); |
@@ -9,72 +9,138 @@ import { | ||
GraphQLNonNull, | ||
GraphQLScalarType, | ||
} from 'graphql'; | ||
GraphQLScalarType | ||
} from "graphql"; | ||
import { loadSchema } from 'apollo-codegen-core/lib/loading' | ||
const schema = loadSchema(require.resolve('../../../common-test/fixtures/starwars/schema.json')); | ||
import { loadSchema } from "apollo-codegen-core/lib/loading"; | ||
const schema = loadSchema( | ||
require.resolve("../../../common-test/fixtures/starwars/schema.json") | ||
); | ||
import { typeNameFromGraphQLType } from '../types' | ||
import { typeNameFromGraphQLType } from "../types"; | ||
describe('Scala code generation: Types', function() { | ||
describe('#typeNameFromGraphQLType()', function() { | ||
test('should return Option[String] for GraphQLString', function() { | ||
expect(typeNameFromGraphQLType({options:{}}, GraphQLString)).toBe('Option[String]'); | ||
describe("Scala code generation: Types", function() { | ||
describe("#typeNameFromGraphQLType()", function() { | ||
test("should return Option[String] for GraphQLString", function() { | ||
expect(typeNameFromGraphQLType({ options: {} }, GraphQLString)).toBe( | ||
"Option[String]" | ||
); | ||
}); | ||
test('should return String for GraphQLNonNull(GraphQLString)', function() { | ||
expect(typeNameFromGraphQLType({options:{}}, new GraphQLNonNull(GraphQLString))).toBe('String'); | ||
test("should return String for GraphQLNonNull(GraphQLString)", function() { | ||
expect( | ||
typeNameFromGraphQLType( | ||
{ options: {} }, | ||
new GraphQLNonNull(GraphQLString) | ||
) | ||
).toBe("String"); | ||
}); | ||
test('should return Option[Seq[Option[String]]] for GraphQLList(GraphQLString)', function() { | ||
expect(typeNameFromGraphQLType({options:{}}, new GraphQLList(GraphQLString))).toBe('Option[Seq[Option[String]]]'); | ||
test("should return Option[Seq[Option[String]]] for GraphQLList(GraphQLString)", function() { | ||
expect( | ||
typeNameFromGraphQLType({ options: {} }, new GraphQLList(GraphQLString)) | ||
).toBe("Option[Seq[Option[String]]]"); | ||
}); | ||
test('should return Seq[String] for GraphQLNonNull(GraphQLList(GraphQLString))', function() { | ||
expect(typeNameFromGraphQLType({options:{}}, new GraphQLNonNull(new GraphQLList(GraphQLString)))).toBe('Seq[Option[String]]'); | ||
test("should return Seq[String] for GraphQLNonNull(GraphQLList(GraphQLString))", function() { | ||
expect( | ||
typeNameFromGraphQLType( | ||
{ options: {} }, | ||
new GraphQLNonNull(new GraphQLList(GraphQLString)) | ||
) | ||
).toBe("Seq[Option[String]]"); | ||
}); | ||
test('should return Option[Seq[String]] for GraphQLList(GraphQLNonNull(GraphQLString))', function() { | ||
expect(typeNameFromGraphQLType({options:{}}, new GraphQLList(new GraphQLNonNull(GraphQLString)))).toBe('Option[Seq[String]]'); | ||
test("should return Option[Seq[String]] for GraphQLList(GraphQLNonNull(GraphQLString))", function() { | ||
expect( | ||
typeNameFromGraphQLType( | ||
{ options: {} }, | ||
new GraphQLList(new GraphQLNonNull(GraphQLString)) | ||
) | ||
).toBe("Option[Seq[String]]"); | ||
}); | ||
test('should return Seq[String] for GraphQLNonNull(GraphQLList(GraphQLNonNull(GraphQLString)))', function() { | ||
expect(typeNameFromGraphQLType({options:{}}, new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLString))))).toBe('Seq[String]'); | ||
test("should return Seq[String] for GraphQLNonNull(GraphQLList(GraphQLNonNull(GraphQLString)))", function() { | ||
expect( | ||
typeNameFromGraphQLType( | ||
{ options: {} }, | ||
new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLString))) | ||
) | ||
).toBe("Seq[String]"); | ||
}); | ||
test('should return Option[Seq[Option[Seq[Option[String]]]]] for GraphQLList(GraphQLList(GraphQLString))', function() { | ||
expect(typeNameFromGraphQLType({options:{}}, new GraphQLList(new GraphQLList(GraphQLString)))).toBe('Option[Seq[Option[Seq[Option[String]]]]]'); | ||
test("should return Option[Seq[Option[Seq[Option[String]]]]] for GraphQLList(GraphQLList(GraphQLString))", function() { | ||
expect( | ||
typeNameFromGraphQLType( | ||
{ options: {} }, | ||
new GraphQLList(new GraphQLList(GraphQLString)) | ||
) | ||
).toBe("Option[Seq[Option[Seq[Option[String]]]]]"); | ||
}); | ||
test('should return Option[Seq[Seq[Option[String]]]] for GraphQLList(GraphQLNonNull(GraphQLList(GraphQLString)))', function() { | ||
expect(typeNameFromGraphQLType({options:{}}, new GraphQLList(new GraphQLNonNull(new GraphQLList(GraphQLString))))).toBe('Option[Seq[Seq[Option[String]]]]'); | ||
test("should return Option[Seq[Seq[Option[String]]]] for GraphQLList(GraphQLNonNull(GraphQLList(GraphQLString)))", function() { | ||
expect( | ||
typeNameFromGraphQLType( | ||
{ options: {} }, | ||
new GraphQLList(new GraphQLNonNull(new GraphQLList(GraphQLString))) | ||
) | ||
).toBe("Option[Seq[Seq[Option[String]]]]"); | ||
}); | ||
test('should return Option[Int] for GraphQLInt', function() { | ||
expect(typeNameFromGraphQLType({options:{}}, GraphQLInt)).toBe('Option[Int]'); | ||
test("should return Option[Int] for GraphQLInt", function() { | ||
expect(typeNameFromGraphQLType({ options: {} }, GraphQLInt)).toBe( | ||
"Option[Int]" | ||
); | ||
}); | ||
test('should return Option[Double] for GraphQLFloat', function() { | ||
expect(typeNameFromGraphQLType({options:{}}, GraphQLFloat)).toBe('Option[Double]'); | ||
test("should return Option[Double] for GraphQLFloat", function() { | ||
expect(typeNameFromGraphQLType({ options: {} }, GraphQLFloat)).toBe( | ||
"Option[Double]" | ||
); | ||
}); | ||
test('should return Option[Boolean] for GraphQLBoolean', function() { | ||
expect(typeNameFromGraphQLType({options:{}}, GraphQLBoolean)).toBe('Option[Boolean]'); | ||
test("should return Option[Boolean] for GraphQLBoolean", function() { | ||
expect(typeNameFromGraphQLType({ options: {} }, GraphQLBoolean)).toBe( | ||
"Option[Boolean]" | ||
); | ||
}); | ||
test('should return Option[String] for GraphQLID', function() { | ||
expect(typeNameFromGraphQLType({options:{}}, GraphQLID)).toBe('Option[String]'); | ||
test("should return Option[String] for GraphQLID", function() { | ||
expect(typeNameFromGraphQLType({ options: {} }, GraphQLID)).toBe( | ||
"Option[String]" | ||
); | ||
}); | ||
test('should return Option[String] for a custom scalar type', function() { | ||
expect(typeNameFromGraphQLType({options:{}}, new GraphQLScalarType({ name: 'CustomScalarType', serialize: String }))).toBe('Option[String]'); | ||
test("should return Option[String] for a custom scalar type", function() { | ||
expect( | ||
typeNameFromGraphQLType( | ||
{ options: {} }, | ||
new GraphQLScalarType({ name: "CustomScalarType", serialize: String }) | ||
) | ||
).toBe("Option[String]"); | ||
}); | ||
test('should return a passed through custom scalar type with the passthroughCustomScalars option', function() { | ||
expect(typeNameFromGraphQLType({options: { passthroughCustomScalars: true, customScalarsPrefix: '' } }, new GraphQLScalarType({ name: 'CustomScalarType', serialize: String }))).toBe('Option[CustomScalarType]'); | ||
test("should return a passed through custom scalar type with the passthroughCustomScalars option", function() { | ||
expect( | ||
typeNameFromGraphQLType( | ||
{ | ||
options: { passthroughCustomScalars: true, customScalarsPrefix: "" } | ||
}, | ||
new GraphQLScalarType({ name: "CustomScalarType", serialize: String }) | ||
) | ||
).toBe("Option[CustomScalarType]"); | ||
}); | ||
test('should return a passed through custom scalar type with a prefix with the customScalarsPrefix option', function() { | ||
expect(typeNameFromGraphQLType({options: { passthroughCustomScalars: true, customScalarsPrefix: 'My' } }, new GraphQLScalarType({ name: 'CustomScalarType', serialize: String }))).toBe('Option[MyCustomScalarType]'); | ||
test("should return a passed through custom scalar type with a prefix with the customScalarsPrefix option", function() { | ||
expect( | ||
typeNameFromGraphQLType( | ||
{ | ||
options: { | ||
passthroughCustomScalars: true, | ||
customScalarsPrefix: "My" | ||
} | ||
}, | ||
new GraphQLScalarType({ name: "CustomScalarType", serialize: String }) | ||
) | ||
).toBe("Option[MyCustomScalarType]"); | ||
}); | ||
}); | ||
}); |
@@ -8,9 +8,7 @@ import { | ||
GraphQLInputObjectType | ||
} from 'graphql' | ||
} from "graphql"; | ||
import { isTypeProperSuperTypeOf } from 'apollo-codegen-core/lib/utilities/graphql' | ||
import { isTypeProperSuperTypeOf } from "apollo-codegen-core/lib/utilities/graphql"; | ||
import { | ||
join, | ||
} from 'apollo-codegen-core/lib/utilities/printing'; | ||
import { join } from "apollo-codegen-core/lib/utilities/printing"; | ||
@@ -23,3 +21,3 @@ import { | ||
comment | ||
} from './language'; | ||
} from "./language"; | ||
@@ -33,24 +31,27 @@ import { | ||
propertyFromLegacyField, | ||
propertyFromInputField, | ||
} from './naming'; | ||
propertyFromInputField | ||
} from "./naming"; | ||
import { | ||
multilineString, | ||
} from './values'; | ||
import { multilineString } from "./values"; | ||
import { possibleTypesForType, typeNameFromGraphQLType } from "./types"; | ||
import CodeGenerator from "apollo-codegen-core/lib/utilities/CodeGenerator"; | ||
import { | ||
possibleTypesForType, | ||
typeNameFromGraphQLType, | ||
} from './types'; | ||
LegacyCompilerContext, | ||
LegacyOperation, | ||
LegacyFragment, | ||
LegacyField, | ||
LegacyInlineFragment | ||
} from "apollo-codegen-core/lib/compiler/legacyIR"; | ||
import { GraphQLType } from "graphql"; | ||
import { Property } from "./language"; | ||
import { GraphQLCompositeType } from "graphql"; | ||
import CodeGenerator from 'apollo-codegen-core/lib/utilities/CodeGenerator'; | ||
import { LegacyCompilerContext, LegacyOperation, LegacyFragment, LegacyField, LegacyInlineFragment } from 'apollo-codegen-core/lib/compiler/legacyIR'; | ||
import { GraphQLType } from 'graphql'; | ||
import { Property } from './language'; | ||
import { GraphQLCompositeType } from 'graphql'; | ||
export function generateSource(context: LegacyCompilerContext) { | ||
const generator = new CodeGenerator(context); | ||
generator.printOnNewline('// This file was automatically generated and should not be edited.'); | ||
generator.printOnNewline( | ||
"// This file was automatically generated and should not be edited." | ||
); | ||
generator.printNewline(); | ||
@@ -96,9 +97,9 @@ | ||
switch (operationType) { | ||
case 'query': | ||
case "query": | ||
objectName = `${operationClassName(operationName)}Query`; | ||
protocol = 'com.apollographql.scalajs.GraphQLQuery'; | ||
protocol = "com.apollographql.scalajs.GraphQLQuery"; | ||
break; | ||
case 'mutation': | ||
case "mutation": | ||
objectName = `${operationClassName(operationName)}Mutation`; | ||
protocol = 'com.apollographql.scalajs.GraphQLMutation'; | ||
protocol = "com.apollographql.scalajs.GraphQLMutation"; | ||
break; | ||
@@ -109,53 +110,72 @@ default: | ||
objectDeclaration(generator, { | ||
objectName, | ||
superclass: protocol, | ||
}, () => { | ||
if (source) { | ||
generator.printOnNewline('val operationString ='); | ||
generator.withIndent(() => { | ||
multilineString(generator, source); | ||
}); | ||
} | ||
objectDeclaration( | ||
generator, | ||
{ | ||
objectName, | ||
superclass: protocol | ||
}, | ||
() => { | ||
if (source) { | ||
generator.printOnNewline("val operationString ="); | ||
generator.withIndent(() => { | ||
multilineString(generator, source); | ||
}); | ||
} | ||
if (operationId) { | ||
operationIdentifier(generator, operationId); | ||
} | ||
if (operationId) { | ||
operationIdentifier(generator, operationId); | ||
} | ||
if (fragmentsReferenced && fragmentsReferenced.length > 0) { | ||
generator.printNewlineIfNeeded(); | ||
generator.printOnNewline('val requestString: String = { operationString'); | ||
fragmentsReferenced.forEach(fragment => { | ||
generator.print(` + ${caseClassNameForFragmentName(fragment)}.fragmentString`) | ||
}); | ||
generator.print(' }'); | ||
if (fragmentsReferenced && fragmentsReferenced.length > 0) { | ||
generator.printNewlineIfNeeded(); | ||
generator.printOnNewline( | ||
"val requestString: String = { operationString" | ||
); | ||
fragmentsReferenced.forEach(fragment => { | ||
generator.print( | ||
` + ${caseClassNameForFragmentName(fragment)}.fragmentString` | ||
); | ||
}); | ||
generator.print(" }"); | ||
generator.printOnNewline('val operation = com.apollographql.scalajs.gql(requestString)'); | ||
} else { | ||
generator.printOnNewline('val operation = com.apollographql.scalajs.gql(operationString)'); | ||
} | ||
generator.printOnNewline( | ||
"val operation = com.apollographql.scalajs.gql(requestString)" | ||
); | ||
} else { | ||
generator.printOnNewline( | ||
"val operation = com.apollographql.scalajs.gql(operationString)" | ||
); | ||
} | ||
generator.printNewlineIfNeeded(); | ||
generator.printNewlineIfNeeded(); | ||
if (variables && variables.length > 0) { | ||
const properties = variables.map(({ name, type }) => { | ||
const propertyName = escapeIdentifierIfNeeded(name); | ||
const typeName = typeNameFromGraphQLType(generator.context, type); | ||
const isOptional = !(type instanceof GraphQLNonNull || type instanceof GraphQLNonNull); | ||
return { name, propertyName, type, typeName, isOptional }; | ||
}); | ||
if (variables && variables.length > 0) { | ||
const properties = variables.map(({ name, type }) => { | ||
const propertyName = escapeIdentifierIfNeeded(name); | ||
const typeName = typeNameFromGraphQLType(generator.context, type); | ||
const isOptional = !( | ||
type instanceof GraphQLNonNull || type instanceof GraphQLNonNull | ||
); | ||
return { name, propertyName, type, typeName, isOptional }; | ||
}); | ||
caseClassDeclaration(generator, { caseClassName: 'Variables', description: '', params: properties.map(p => { | ||
return { | ||
name: p.propertyName, | ||
type: p.typeName | ||
}; | ||
})}, () => {}); | ||
} else { | ||
generator.printOnNewline('type Variables = Unit'); | ||
} | ||
caseClassDeclaration( | ||
generator, | ||
{ | ||
caseClassName: "Variables", | ||
description: "", | ||
params: properties.map(p => { | ||
return { | ||
name: p.propertyName, | ||
type: p.typeName | ||
}; | ||
}) | ||
}, | ||
() => {} | ||
); | ||
} else { | ||
generator.printOnNewline("type Variables = Unit"); | ||
} | ||
caseClassDeclarationForSelectionSet( | ||
generator, | ||
{ | ||
caseClassDeclarationForSelectionSet(generator, { | ||
caseClassName: "Data", | ||
@@ -166,5 +186,5 @@ parentType: rootType, | ||
fragmentSpreads | ||
} | ||
); | ||
}); | ||
}); | ||
} | ||
); | ||
} | ||
@@ -185,16 +205,20 @@ | ||
caseClassDeclarationForSelectionSet(generator, { | ||
caseClassName, | ||
parentType: typeCondition, | ||
fields, | ||
inlineFragments, | ||
fragmentSpreads | ||
}, () => { | ||
if (source) { | ||
generator.printOnNewline('val fragmentString ='); | ||
generator.withIndent(() => { | ||
multilineString(generator, source); | ||
}); | ||
caseClassDeclarationForSelectionSet( | ||
generator, | ||
{ | ||
caseClassName, | ||
parentType: typeCondition, | ||
fields, | ||
inlineFragments, | ||
fragmentSpreads | ||
}, | ||
() => { | ||
if (source) { | ||
generator.printOnNewline("val fragmentString ="); | ||
generator.withIndent(() => { | ||
multilineString(generator, source); | ||
}); | ||
} | ||
} | ||
}); | ||
); | ||
} | ||
@@ -212,82 +236,108 @@ | ||
}: { | ||
caseClassName: string, | ||
parentType: GraphQLCompositeType, | ||
fields: LegacyField[], | ||
inlineFragments?: LegacyInlineFragment[], | ||
fragmentSpreads?: string[], | ||
caseClassName: string; | ||
parentType: GraphQLCompositeType; | ||
fields: LegacyField[]; | ||
inlineFragments?: LegacyInlineFragment[]; | ||
fragmentSpreads?: string[]; | ||
viewableAs?: { | ||
caseClassName: string, | ||
properties: (LegacyField & Property)[] | ||
} | ||
caseClassName: string; | ||
properties: (LegacyField & Property)[]; | ||
}; | ||
}, | ||
objectClosure?: () => void, | ||
objectClosure?: () => void | ||
) { | ||
const possibleTypes = parentType ? possibleTypesForType(generator.context, parentType) : null; | ||
const possibleTypes = parentType | ||
? possibleTypesForType(generator.context, parentType) | ||
: null; | ||
if (!possibleTypes || possibleTypes.length == 1) { | ||
const properties = fields | ||
.map(field => propertyFromLegacyField(generator.context, field, caseClassName)) | ||
.map(field => | ||
propertyFromLegacyField(generator.context, field, caseClassName) | ||
) | ||
.filter(field => field.propertyName != "__typename"); | ||
caseClassDeclaration(generator, { caseClassName, params: properties.map(p => { | ||
return { | ||
name: p.responseName, | ||
type: p.typeName, | ||
}; | ||
}) }, () => {}); | ||
caseClassDeclaration( | ||
generator, | ||
{ | ||
caseClassName, | ||
params: properties.map(p => { | ||
return { | ||
name: p.responseName, | ||
type: p.typeName | ||
}; | ||
}) | ||
}, | ||
() => {} | ||
); | ||
} else { | ||
generator.printNewlineIfNeeded(); | ||
const properties = fields | ||
.map(field => propertyFromLegacyField(generator.context, field, caseClassName)) | ||
.map(field => | ||
propertyFromLegacyField(generator.context, field, caseClassName) | ||
) | ||
.filter(field => field.propertyName != "__typename"); | ||
caseClassDeclaration(generator, { caseClassName, params: properties.map(p => { | ||
return { | ||
name: p.responseName, | ||
type: p.typeName, | ||
}; | ||
}), superclass: 'slinky.readwrite.WithRaw'}, () => { | ||
if (inlineFragments && inlineFragments.length > 0) { | ||
inlineFragments.forEach((inlineFragment) => { | ||
const fragClass = caseClassNameForInlineFragment(inlineFragment); | ||
generator.printOnNewline(`def as${inlineFragment.typeCondition}`); | ||
generator.print(`: Option[${fragClass}] =`); | ||
generator.withinBlock(() => { | ||
generator.printOnNewline(`if (${fragClass}.possibleTypes.contains(this.raw.__typename.asInstanceOf[String])) Some(implicitly[slinky.readwrite.Reader[${fragClass}]].read(this.raw)) else None`); | ||
caseClassDeclaration( | ||
generator, | ||
{ | ||
caseClassName, | ||
params: properties.map(p => { | ||
return { | ||
name: p.responseName, | ||
type: p.typeName | ||
}; | ||
}), | ||
superclass: "slinky.readwrite.WithRaw" | ||
}, | ||
() => { | ||
if (inlineFragments && inlineFragments.length > 0) { | ||
inlineFragments.forEach(inlineFragment => { | ||
const fragClass = caseClassNameForInlineFragment(inlineFragment); | ||
generator.printOnNewline(`def as${inlineFragment.typeCondition}`); | ||
generator.print(`: Option[${fragClass}] =`); | ||
generator.withinBlock(() => { | ||
generator.printOnNewline( | ||
`if (${fragClass}.possibleTypes.contains(this.raw.__typename.asInstanceOf[String])) Some(implicitly[slinky.readwrite.Reader[${fragClass}]].read(this.raw)) else None` | ||
); | ||
}); | ||
}); | ||
}); | ||
} | ||
} | ||
if (fragmentSpreads) { | ||
fragmentSpreads.forEach(s => { | ||
const fragment = generator.context.fragments[s]; | ||
const alwaysDefined = isTypeProperSuperTypeOf(generator.context.schema, fragment.typeCondition, parentType); | ||
if (!alwaysDefined) { | ||
generator.printOnNewline(`def as${s}`); | ||
generator.print(`: Option[${s}] =`); | ||
generator.withinBlock(() => { | ||
generator.printOnNewline(`if (${s}.possibleTypes.contains(this.raw.__typename.asInstanceOf[String])) Some(implicitly[slinky.readwrite.Reader[${s}]].read(this.raw)) else None`); | ||
}); | ||
} | ||
}) | ||
if (fragmentSpreads) { | ||
fragmentSpreads.forEach(s => { | ||
const fragment = generator.context.fragments[s]; | ||
const alwaysDefined = isTypeProperSuperTypeOf( | ||
generator.context.schema, | ||
fragment.typeCondition, | ||
parentType | ||
); | ||
if (!alwaysDefined) { | ||
generator.printOnNewline(`def as${s}`); | ||
generator.print(`: Option[${s}] =`); | ||
generator.withinBlock(() => { | ||
generator.printOnNewline( | ||
`if (${s}.possibleTypes.contains(this.raw.__typename.asInstanceOf[String])) Some(implicitly[slinky.readwrite.Reader[${s}]].read(this.raw)) else None` | ||
); | ||
}); | ||
} | ||
}); | ||
} | ||
} | ||
}); | ||
); | ||
// add types and implicit conversions | ||
if (inlineFragments && inlineFragments.length > 0) { | ||
inlineFragments.forEach((inlineFragment) => { | ||
caseClassDeclarationForSelectionSet( | ||
generator, | ||
{ | ||
caseClassName: caseClassNameForInlineFragment(inlineFragment), | ||
parentType: inlineFragment.typeCondition, | ||
fields: inlineFragment.fields, | ||
// inlineFragments: inlineFragment.inlineFragments, | ||
fragmentSpreads: inlineFragment.fragmentSpreads, | ||
viewableAs: { | ||
caseClassName, | ||
properties, | ||
}, | ||
inlineFragments.forEach(inlineFragment => { | ||
caseClassDeclarationForSelectionSet(generator, { | ||
caseClassName: caseClassNameForInlineFragment(inlineFragment), | ||
parentType: inlineFragment.typeCondition, | ||
fields: inlineFragment.fields, | ||
// inlineFragments: inlineFragment.inlineFragments, | ||
fragmentSpreads: inlineFragment.fragmentSpreads, | ||
viewableAs: { | ||
caseClassName, | ||
properties | ||
} | ||
); | ||
}); | ||
}); | ||
@@ -300,9 +350,17 @@ } | ||
generator.printNewlineIfNeeded(); | ||
generator.printOnNewline('val possibleTypes = scala.collection.Set('); | ||
generator.print(join(Array.from(possibleTypes).map(type => `"${String(type)}"`), ', ')); | ||
generator.print(')'); | ||
generator.printOnNewline("val possibleTypes = scala.collection.Set("); | ||
generator.print( | ||
join(Array.from(possibleTypes).map(type => `"${String(type)}"`), ", ") | ||
); | ||
generator.print(")"); | ||
} | ||
if (viewableAs) { | ||
generator.printOnNewline(`implicit def to${viewableAs.caseClassName}(a: ${caseClassName}): ${viewableAs.caseClassName} = ${viewableAs.caseClassName}(${viewableAs.properties.map(p => "a." + p.responseName).join(', ')})`); | ||
generator.printOnNewline( | ||
`implicit def to${viewableAs.caseClassName}(a: ${caseClassName}): ${ | ||
viewableAs.caseClassName | ||
} = ${viewableAs.caseClassName}(${viewableAs.properties | ||
.map(p => "a." + p.responseName) | ||
.join(", ")})` | ||
); | ||
} | ||
@@ -313,13 +371,23 @@ | ||
const fragment = generator.context.fragments[s]; | ||
const alwaysDefined = isTypeProperSuperTypeOf(generator.context.schema, fragment.typeCondition, parentType); | ||
const alwaysDefined = isTypeProperSuperTypeOf( | ||
generator.context.schema, | ||
fragment.typeCondition, | ||
parentType | ||
); | ||
if (alwaysDefined) { | ||
generator.printOnNewline(`implicit def to${s}(a: ${caseClassName}): ${s} = ${s}(${(fragment.fields || []).map(p => "a." + p.responseName).join(', ')})`); | ||
generator.printOnNewline( | ||
`implicit def to${s}(a: ${caseClassName}): ${s} = ${s}(${( | ||
fragment.fields || [] | ||
) | ||
.map(p => "a." + p.responseName) | ||
.join(", ")})` | ||
); | ||
} | ||
}) | ||
}); | ||
} | ||
fields.filter(field => isCompositeType(getNamedType(field.type))).forEach(field => { | ||
caseClassDeclarationForSelectionSet( | ||
generator, | ||
{ | ||
fields | ||
.filter(field => isCompositeType(getNamedType(field.type))) | ||
.forEach(field => { | ||
caseClassDeclarationForSelectionSet(generator, { | ||
caseClassName: caseClassNameForPropertyName(field.responseName), | ||
@@ -330,5 +398,4 @@ parentType: getNamedType(field.type) as GraphQLCompositeType, | ||
fragmentSpreads: field.fragmentSpreads | ||
} | ||
); | ||
}); | ||
}); | ||
}); | ||
@@ -341,12 +408,20 @@ if (objectClosure) { | ||
function operationIdentifier(generator: CodeGenerator<LegacyCompilerContext, any>, operationId: string) { | ||
function operationIdentifier( | ||
generator: CodeGenerator<LegacyCompilerContext, any>, | ||
operationId: string | ||
) { | ||
if (!generator.context.options.generateOperationIds) { | ||
return | ||
return; | ||
} | ||
generator.printNewlineIfNeeded(); | ||
generator.printOnNewline(`val operationIdentifier: String = "${operationId}"`); | ||
generator.printOnNewline( | ||
`val operationIdentifier: String = "${operationId}"` | ||
); | ||
} | ||
export function typeDeclarationForGraphQLType(generator: CodeGenerator<LegacyCompilerContext, any>, type: GraphQLType) { | ||
export function typeDeclarationForGraphQLType( | ||
generator: CodeGenerator<LegacyCompilerContext, any>, | ||
type: GraphQLType | ||
) { | ||
if (type instanceof GraphQLEnumType) { | ||
@@ -359,3 +434,6 @@ enumerationDeclaration(generator, type); | ||
function enumerationDeclaration(generator: CodeGenerator<LegacyCompilerContext, any>, type: GraphQLEnumType) { | ||
function enumerationDeclaration( | ||
generator: CodeGenerator<LegacyCompilerContext, any>, | ||
type: GraphQLEnumType | ||
) { | ||
const { name, description } = type; | ||
@@ -370,3 +448,7 @@ const values = type.getValues(); | ||
comment(generator, value.description || ""); | ||
generator.printOnNewline(`val ${escapeIdentifierIfNeeded(enumCaseName(value.name))} = "${value.value}"`); | ||
generator.printOnNewline( | ||
`val ${escapeIdentifierIfNeeded(enumCaseName(value.name))} = "${ | ||
value.value | ||
}"` | ||
); | ||
}); | ||
@@ -377,14 +459,31 @@ }); | ||
function caseClassDeclarationForInputObjectType(generator: CodeGenerator<LegacyCompilerContext, any>, type: GraphQLInputObjectType) { | ||
function caseClassDeclarationForInputObjectType( | ||
generator: CodeGenerator<LegacyCompilerContext, any>, | ||
type: GraphQLInputObjectType | ||
) { | ||
const { name: caseClassName, description } = type; | ||
const fields = Object.values(type.getFields()); | ||
const properties = fields.map(field => propertyFromInputField(generator.context, field, generator.context.options.namespace)); | ||
const properties = fields.map(field => | ||
propertyFromInputField( | ||
generator.context, | ||
field, | ||
generator.context.options.namespace | ||
) | ||
); | ||
caseClassDeclaration(generator, { caseClassName, description: description || undefined, params: properties.map(p => { | ||
return { | ||
name: p.propertyName, | ||
type: p.typeName, | ||
defaultValue: p.isOptional ? "scala.scalajs.js.undefined" : "" | ||
}; | ||
})}, () => {}); | ||
caseClassDeclaration( | ||
generator, | ||
{ | ||
caseClassName, | ||
description: description || undefined, | ||
params: properties.map(p => { | ||
return { | ||
name: p.propertyName, | ||
type: p.typeName, | ||
defaultValue: p.isOptional ? "scala.scalajs.js.undefined" : "" | ||
}; | ||
}) | ||
}, | ||
() => {} | ||
); | ||
} |
@@ -1,1 +0,1 @@ | ||
export { generateSource } from './codeGeneration'; | ||
export { generateSource } from "./codeGeneration"; |
@@ -13,6 +13,9 @@ import CodeGenerator from "apollo-codegen-core/lib/utilities/CodeGenerator"; | ||
export function comment(generator: CodeGenerator<LegacyCompilerContext, any>, comment: string) { | ||
const split = comment ? comment.split('\n') : []; | ||
export function comment( | ||
generator: CodeGenerator<LegacyCompilerContext, any>, | ||
comment: string | ||
) { | ||
const split = comment ? comment.split("\n") : []; | ||
if (split.length > 0) { | ||
generator.printOnNewline('/**') | ||
generator.printOnNewline("/**"); | ||
split.forEach(line => { | ||
@@ -22,7 +25,10 @@ generator.printOnNewline(` * ${line.trim()}`); | ||
generator.printOnNewline(' */'); | ||
generator.printOnNewline(" */"); | ||
} | ||
} | ||
export function packageDeclaration(generator: CodeGenerator<LegacyCompilerContext, any>, pkg: string) { | ||
export function packageDeclaration( | ||
generator: CodeGenerator<LegacyCompilerContext, any>, | ||
pkg: string | ||
) { | ||
generator.printNewlineIfNeeded(); | ||
@@ -35,5 +41,8 @@ generator.printOnNewline(`package ${pkg}`); | ||
generator: CodeGenerator<LegacyCompilerContext, any>, | ||
{ objectName, superclass }: { | ||
objectName: string, | ||
superclass?: string | ||
{ | ||
objectName, | ||
superclass | ||
}: { | ||
objectName: string; | ||
superclass?: string; | ||
}, | ||
@@ -43,3 +52,5 @@ closure?: () => void | ||
generator.printNewlineIfNeeded(); | ||
generator.printOnNewline(`object ${objectName}` + (superclass ? ` extends ${superclass}` : '')); | ||
generator.printOnNewline( | ||
`object ${objectName}` + (superclass ? ` extends ${superclass}` : "") | ||
); | ||
generator.pushScope({ typeName: objectName }); | ||
@@ -54,11 +65,16 @@ if (closure) { | ||
generator: CodeGenerator<LegacyCompilerContext, any>, | ||
{ caseClassName, description, superclass, params }: { | ||
caseClassName: string, | ||
description?: string, | ||
superclass?: string, | ||
{ | ||
caseClassName, | ||
description, | ||
superclass, | ||
params | ||
}: { | ||
caseClassName: string; | ||
description?: string; | ||
superclass?: string; | ||
params?: { | ||
name: string, | ||
type: string, | ||
defaultValue?: string | ||
}[], | ||
name: string; | ||
type: string; | ||
defaultValue?: string; | ||
}[]; | ||
}, | ||
@@ -73,7 +89,14 @@ closure?: () => void | ||
const paramsSection = (params || []).map(v => { | ||
return v.name + ": " + v.type + (v.defaultValue ? ` = ${v.defaultValue}` : ""); | ||
}).join(', '); | ||
const paramsSection = (params || []) | ||
.map(v => { | ||
return ( | ||
v.name + ": " + v.type + (v.defaultValue ? ` = ${v.defaultValue}` : "") | ||
); | ||
}) | ||
.join(", "); | ||
generator.printOnNewline(`case class ${caseClassName}(${paramsSection})` + (superclass ? ` extends ${superclass}` : '')); | ||
generator.printOnNewline( | ||
`case class ${caseClassName}(${paramsSection})` + | ||
(superclass ? ` extends ${superclass}` : "") | ||
); | ||
generator.pushScope({ typeName: caseClassName }); | ||
@@ -88,6 +111,10 @@ if (closure) { | ||
generator: CodeGenerator<LegacyCompilerContext, any>, | ||
{ propertyName, typeName, description}: { | ||
propertyName: string, | ||
typeName: string, | ||
description: string | ||
{ | ||
propertyName, | ||
typeName, | ||
description | ||
}: { | ||
propertyName: string; | ||
typeName: string; | ||
description: string; | ||
}, | ||
@@ -107,5 +134,5 @@ closure?: () => void | ||
declarations: { | ||
propertyName: string, | ||
typeName: string, | ||
description: string | ||
propertyName: string; | ||
typeName: string; | ||
description: string; | ||
}[] | ||
@@ -119,6 +146,25 @@ ) { | ||
const reservedKeywords = new Set([ | ||
'case', 'catch', 'class', 'def', 'do', 'else', | ||
'extends', 'false', 'final', 'for', 'if', 'match', | ||
'new', 'null', 'throw', 'trait', 'true', 'try', 'until', | ||
'val', 'var', 'while', 'with' | ||
"case", | ||
"catch", | ||
"class", | ||
"def", | ||
"do", | ||
"else", | ||
"extends", | ||
"false", | ||
"final", | ||
"for", | ||
"if", | ||
"match", | ||
"new", | ||
"null", | ||
"throw", | ||
"trait", | ||
"true", | ||
"try", | ||
"until", | ||
"val", | ||
"var", | ||
"while", | ||
"with" | ||
]); | ||
@@ -128,3 +174,3 @@ | ||
if (reservedKeywords.has(identifier)) { | ||
return '`' + identifier + '`'; | ||
return "`" + identifier + "`"; | ||
} else { | ||
@@ -131,0 +177,0 @@ return identifier; |
@@ -1,15 +0,9 @@ | ||
import { camelCase, pascalCase } from 'change-case'; | ||
import * as Inflector from 'inflected'; | ||
import { camelCase, pascalCase } from "change-case"; | ||
import * as Inflector from "inflected"; | ||
import { | ||
join | ||
} from 'apollo-codegen-core/lib/utilities/printing'; | ||
import { join } from "apollo-codegen-core/lib/utilities/printing"; | ||
import { | ||
escapeIdentifierIfNeeded, Property | ||
} from './language'; | ||
import { escapeIdentifierIfNeeded, Property } from "./language"; | ||
import { | ||
typeNameFromGraphQLType | ||
} from './types'; | ||
import { typeNameFromGraphQLType } from "./types"; | ||
@@ -20,6 +14,10 @@ import { | ||
getNamedType, | ||
isCompositeType, | ||
} from 'graphql'; | ||
import { LegacyCompilerContext, LegacyField, LegacyInlineFragment } from 'apollo-codegen-core/lib/compiler/legacyIR'; | ||
import { GraphQLInputField } from 'graphql'; | ||
isCompositeType | ||
} from "graphql"; | ||
import { | ||
LegacyCompilerContext, | ||
LegacyField, | ||
LegacyInlineFragment | ||
} from "apollo-codegen-core/lib/compiler/legacyIR"; | ||
import { GraphQLInputField } from "graphql"; | ||
@@ -42,13 +40,20 @@ export function enumCaseName(name: string) { | ||
export function caseClassNameForInlineFragment(inlineFragment: LegacyInlineFragment) { | ||
return 'As' + pascalCase(String(inlineFragment.typeCondition)); | ||
export function caseClassNameForInlineFragment( | ||
inlineFragment: LegacyInlineFragment | ||
) { | ||
return "As" + pascalCase(String(inlineFragment.typeCondition)); | ||
} | ||
export function propertyFromInputField(context: LegacyCompilerContext, field: GraphQLInputField, namespace?: string, parentCaseClassName?: string): GraphQLInputField & Property { | ||
export function propertyFromInputField( | ||
context: LegacyCompilerContext, | ||
field: GraphQLInputField, | ||
namespace?: string, | ||
parentCaseClassName?: string | ||
): GraphQLInputField & Property { | ||
const name = field.name; | ||
const unescapedPropertyName = isMetaFieldName(name) ? name : camelCase(name) | ||
const unescapedPropertyName = isMetaFieldName(name) ? name : camelCase(name); | ||
const propertyName = escapeIdentifierIfNeeded(unescapedPropertyName); | ||
const type = field.type; | ||
const isList = type instanceof GraphQLList || type instanceof GraphQLList | ||
const isList = type instanceof GraphQLList || type instanceof GraphQLList; | ||
const isOptional = !(type instanceof GraphQLNonNull); | ||
@@ -58,22 +63,56 @@ const bareType = getNamedType(type); | ||
if (isCompositeType(bareType)) { | ||
const bareTypeName = join([ | ||
namespace, | ||
parentCaseClassName, | ||
escapeIdentifierIfNeeded(pascalCase(Inflector.singularize(name))) | ||
], '.'); | ||
const typeName = typeNameFromGraphQLType(context, type, bareTypeName, isOptional, true); | ||
return { ...field, propertyName, typeName, isOptional, isList, description: field.description || undefined }; | ||
const bareTypeName = join( | ||
[ | ||
namespace, | ||
parentCaseClassName, | ||
escapeIdentifierIfNeeded(pascalCase(Inflector.singularize(name))) | ||
], | ||
"." | ||
); | ||
const typeName = typeNameFromGraphQLType( | ||
context, | ||
type, | ||
bareTypeName, | ||
isOptional, | ||
true | ||
); | ||
return { | ||
...field, | ||
propertyName, | ||
typeName, | ||
isOptional, | ||
isList, | ||
description: field.description || undefined | ||
}; | ||
} else { | ||
const typeName = typeNameFromGraphQLType(context, type, undefined, isOptional, true); | ||
return { ...field, propertyName, typeName, isOptional, isList, description: field.description || undefined }; | ||
const typeName = typeNameFromGraphQLType( | ||
context, | ||
type, | ||
undefined, | ||
isOptional, | ||
true | ||
); | ||
return { | ||
...field, | ||
propertyName, | ||
typeName, | ||
isOptional, | ||
isList, | ||
description: field.description || undefined | ||
}; | ||
} | ||
} | ||
export function propertyFromLegacyField(context: LegacyCompilerContext, field: LegacyField, namespace?: string, parentCaseClassName?: string): LegacyField & Property { | ||
export function propertyFromLegacyField( | ||
context: LegacyCompilerContext, | ||
field: LegacyField, | ||
namespace?: string, | ||
parentCaseClassName?: string | ||
): LegacyField & Property { | ||
const name = field.responseName; | ||
const unescapedPropertyName = isMetaFieldName(name) ? name : camelCase(name) | ||
const unescapedPropertyName = isMetaFieldName(name) ? name : camelCase(name); | ||
const propertyName = escapeIdentifierIfNeeded(unescapedPropertyName); | ||
const type = field.type; | ||
const isList = type instanceof GraphQLList || type instanceof GraphQLList | ||
const isList = type instanceof GraphQLList || type instanceof GraphQLList; | ||
const isOptional = field.isConditional || !(type instanceof GraphQLNonNull); | ||
@@ -83,11 +122,24 @@ const bareType = getNamedType(type); | ||
if (isCompositeType(bareType)) { | ||
const bareTypeName = join([ | ||
namespace, | ||
parentCaseClassName, | ||
escapeIdentifierIfNeeded(pascalCase(Inflector.singularize(name))) | ||
], '.'); | ||
const typeName = typeNameFromGraphQLType(context, type, bareTypeName, isOptional); | ||
const bareTypeName = join( | ||
[ | ||
namespace, | ||
parentCaseClassName, | ||
escapeIdentifierIfNeeded(pascalCase(Inflector.singularize(name))) | ||
], | ||
"." | ||
); | ||
const typeName = typeNameFromGraphQLType( | ||
context, | ||
type, | ||
bareTypeName, | ||
isOptional | ||
); | ||
return { ...field, propertyName, typeName, isOptional, isList }; | ||
} else { | ||
const typeName = typeNameFromGraphQLType(context, type, undefined, isOptional); | ||
const typeName = typeNameFromGraphQLType( | ||
context, | ||
type, | ||
undefined, | ||
isOptional | ||
); | ||
return { ...field, propertyName, typeName, isOptional, isList }; | ||
@@ -94,0 +146,0 @@ } |
@@ -12,15 +12,18 @@ import { | ||
isAbstractType | ||
} from 'graphql'; | ||
import { LegacyCompilerContext } from 'apollo-codegen-core/lib/compiler/legacyIR'; | ||
import { GraphQLType } from 'graphql'; | ||
} from "graphql"; | ||
import { LegacyCompilerContext } from "apollo-codegen-core/lib/compiler/legacyIR"; | ||
import { GraphQLType } from "graphql"; | ||
const builtInScalarMap = { | ||
[GraphQLString.name]: 'String', | ||
[GraphQLInt.name]: 'Int', | ||
[GraphQLFloat.name]: 'Double', | ||
[GraphQLBoolean.name]: 'Boolean', | ||
[GraphQLID.name]: 'String', | ||
} | ||
[GraphQLString.name]: "String", | ||
[GraphQLInt.name]: "Int", | ||
[GraphQLFloat.name]: "Double", | ||
[GraphQLBoolean.name]: "Boolean", | ||
[GraphQLID.name]: "String" | ||
}; | ||
export function possibleTypesForType(context: LegacyCompilerContext, type: GraphQLType) { | ||
export function possibleTypesForType( | ||
context: LegacyCompilerContext, | ||
type: GraphQLType | ||
) { | ||
if (isAbstractType(type)) { | ||
@@ -33,5 +36,16 @@ return context.schema.getPossibleTypes(type); | ||
export function typeNameFromGraphQLType(context: LegacyCompilerContext, type: GraphQLType, bareTypeName?: string, isOptional?: boolean, isInputObject?: boolean): string { | ||
export function typeNameFromGraphQLType( | ||
context: LegacyCompilerContext, | ||
type: GraphQLType, | ||
bareTypeName?: string, | ||
isOptional?: boolean, | ||
isInputObject?: boolean | ||
): string { | ||
if (type instanceof GraphQLNonNull) { | ||
return typeNameFromGraphQLType(context, type.ofType, bareTypeName, isOptional || false) | ||
return typeNameFromGraphQLType( | ||
context, | ||
type.ofType, | ||
bareTypeName, | ||
isOptional || false | ||
); | ||
} else if (isOptional === undefined) { | ||
@@ -43,3 +57,6 @@ isOptional = true; | ||
if (type instanceof GraphQLList) { | ||
typeName = 'Seq[' + typeNameFromGraphQLType(context, type.ofType, bareTypeName) + ']'; | ||
typeName = | ||
"Seq[" + | ||
typeNameFromGraphQLType(context, type.ofType, bareTypeName) + | ||
"]"; | ||
} else if (type instanceof GraphQLScalarType) { | ||
@@ -53,7 +70,19 @@ typeName = typeNameForScalarType(context, type); | ||
return isOptional ? (isInputObject ? `scala.scalajs.js.UndefOr[${typeName}]` : `Option[${typeName}]`) : typeName; | ||
return isOptional | ||
? isInputObject | ||
? `scala.scalajs.js.UndefOr[${typeName}]` | ||
: `Option[${typeName}]` | ||
: typeName; | ||
} | ||
function typeNameForScalarType(context: LegacyCompilerContext, type: GraphQLScalarType): string { | ||
return builtInScalarMap[type.name] || (context.options.passthroughCustomScalars ? context.options.customScalarsPrefix + type.name : GraphQLString.name) | ||
function typeNameForScalarType( | ||
context: LegacyCompilerContext, | ||
type: GraphQLScalarType | ||
): string { | ||
return ( | ||
builtInScalarMap[type.name] || | ||
(context.options.passthroughCustomScalars | ||
? context.options.customScalarsPrefix + type.name | ||
: GraphQLString.name) | ||
); | ||
} |
@@ -1,3 +0,3 @@ | ||
import { LegacyCompilerContext } from 'apollo-codegen-core/lib/compiler/legacyIR'; | ||
import CodeGenerator from 'apollo-codegen-core/lib/utilities/CodeGenerator'; | ||
import { LegacyCompilerContext } from "apollo-codegen-core/lib/compiler/legacyIR"; | ||
import CodeGenerator from "apollo-codegen-core/lib/utilities/CodeGenerator"; | ||
@@ -8,8 +8,13 @@ export function escapedString(string: string) { | ||
export function multilineString(generator: CodeGenerator<LegacyCompilerContext, any>, string: string) { | ||
const lines = string.split('\n'); | ||
export function multilineString( | ||
generator: CodeGenerator<LegacyCompilerContext, any>, | ||
string: string | ||
) { | ||
const lines = string.split("\n"); | ||
lines.forEach((line, index) => { | ||
const isLastLine = index != lines.length - 1; | ||
generator.printOnNewline(`"${escapedString(line)}"` + (isLastLine ? ' +' : '')); | ||
generator.printOnNewline( | ||
`"${escapedString(line)}"` + (isLastLine ? " +" : "") | ||
); | ||
}); | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No bug tracker
MaintenancePackage does not have a linked bug tracker in package.json.
Found 1 instance in 1 package
No website
QualityPackage does not have a website.
Found 1 instance in 1 package
110626
0
33
2202
1
1
Updatedapollo-codegen-core@0.27.3