graphql#GraphQLType TypeScript Examples
The following examples show how to use
graphql#GraphQLType.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: withOperators.ts From payload with MIT License | 6 votes |
withOperators = (field: FieldAffectingData, type: GraphQLType, parentName: string, operators: string[]): GraphQLInputObjectType => {
const name = `${combineParentName(parentName, field.name)}_operator`;
const listOperators = ['in', 'not_in', 'all'];
if (!field.required) operators.push('exists');
return new GraphQLInputObjectType({
name,
fields: operators.reduce((fields, operator) => {
let gqlType: GraphQLType;
if (listOperators.indexOf(operator) > -1) {
gqlType = new GraphQLList(type);
} else if (operator === 'exists') {
gqlType = GraphQLBoolean;
} else {
gqlType = type;
}
return {
...fields,
[operator]: {
type: gqlType,
},
};
}, {}),
});
}
Example #2
Source File: complextypes.ts From amplify-codegen with Apache License 2.0 | 6 votes |
export function isS3Field(field: GraphQLType): boolean {
if (isObjectType(field) || isInputObjectType(field)) {
const fields = field.getFields();
const stringFields = Object.keys(fields).filter(f => {
const fieldType = fields[f].type;
const typeName = getNamedType(fieldType);
return (typeName.name === 'String' && isNonNullType(fieldType));
});
const isS3FileField = S3_FIELD_NAMES.every(fieldName => stringFields.includes(fieldName));
if (isS3FileField) {
return true;
}
}
return false;
}
Example #3
Source File: complextypes.ts From amplify-codegen with Apache License 2.0 | 6 votes |
export function hasS3Fields(input: GraphQLType): boolean {
if (isObjectType(input) || isInputObjectType(input)) {
if (isS3Field(input)) {
return true;
}
const fields = input.getFields();
return Object.keys(fields).some(f => hasS3Fields((<any>fields[f]) as GraphQLType));
}
return false;
}
Example #4
Source File: types.ts From amplify-codegen with Apache License 2.0 | 6 votes |
export function typeNameFromGraphQLType(
context: LegacyCompilerContext,
type: GraphQLType,
bareTypeName?: string | null,
nullable = true
): string {
if (isNonNullType(type)) {
return typeNameFromGraphQLType(context, type.ofType, bareTypeName, false);
}
let typeName;
if (isListType(type)) {
typeName = `Array< ${typeNameFromGraphQLType(context, type.ofType, bareTypeName, true)} >`;
} else if (type instanceof GraphQLScalarType) {
typeName =
builtInScalarMap[type.name] ||
appSyncScalars[type.name] ||
(context.options.passthroughCustomScalars ? context.options.customScalarsPrefix + type.name : builtInScalarMap[GraphQLString.name]);
} else {
typeName = bareTypeName || type.name;
}
return nullable ? typeName + ' | null' : typeName;
}
Example #5
Source File: resolve-additional-resolvers.ts From graphql-mesh with MIT License | 6 votes |
function getTypeByPath(type: GraphQLType, path: string[]): GraphQLNamedType {
if ('ofType' in type) {
return getTypeByPath(getNamedType(type), path);
}
if (path.length === 0) {
return getNamedType(type);
}
if (!('getFields' in type)) {
throw new Error(`${type} cannot have a path ${path.join('.')}`);
}
const fieldMap = type.getFields();
const currentFieldName = path[0];
// Might be an index of an array
if (!Number.isNaN(parseInt(currentFieldName))) {
return getTypeByPath(type, path.slice(1));
}
const field = fieldMap[currentFieldName];
if (!field?.type) {
throw new Error(`${type}.${currentFieldName} is not a valid field.`);
}
return getTypeByPath(field.type, path.slice(1));
}
Example #6
Source File: codeGeneration.ts From amplify-codegen with Apache License 2.0 | 6 votes |
export function propertiesFromFields(
context: LegacyCompilerContext,
fields: {
name?: string;
type: GraphQLType;
responseName?: string;
description?: Maybe<string>;
fragmentSpreads?: any;
inlineFragments?: LegacyInlineFragment[];
fieldName?: string;
}[],
) {
return fields.map(field => propertyFromField(context, field));
}
Example #7
Source File: codeGeneration.ts From amplify-codegen with Apache License 2.0 | 6 votes |
function getObjectTypeName(type: GraphQLType): string {
if (isListType(type)) {
return getObjectTypeName(type.ofType);
}
if (isNonNullType(type)) {
return getObjectTypeName(type.ofType);
}
if (isObjectType(type)) {
return `"${type.name}"`;
}
if (isUnionType(type)) {
return type
.getTypes()
.map(type => getObjectTypeName(type))
.join(' | ');
}
return `"${type.name}"`;
}
Example #8
Source File: codeGeneration.ts From amplify-codegen with Apache License 2.0 | 6 votes |
export function typeDeclarationForGraphQLType(generator: CodeGenerator, type: GraphQLType) {
if (isEnumType(type)) {
enumerationDeclaration(generator, type);
} else if (isUnionType(type)) {
unionDeclaration(generator, type);
} else if (isInputObjectType(type)) {
structDeclarationForInputObjectType(generator, type);
} else if (isObjectType(type)) {
structDeclarationForObjectType(generator, type);
} else if (isInterfaceType(type)) {
structDeclarationForInterfaceType(generator, type);
}
}
Example #9
Source File: helpers.ts From amplify-codegen with Apache License 2.0 | 6 votes |
mapExpressionForType(type: GraphQLType, expression: (identifier: string) => string, identifier = ''): string {
let isOptional;
if (isNonNullType(type)) {
isOptional = false;
type = type.ofType;
} else {
isOptional = true;
}
if (isListType(type)) {
if (isOptional) {
return `${identifier}.flatMap { $0.map { ${this.mapExpressionForType(type.ofType, expression, '$0')} } }`;
} else {
return `${identifier}.map { ${this.mapExpressionForType(type.ofType, expression, '$0')} }`;
}
} else if (isOptional) {
return `${identifier}.flatMap { ${expression('$0')} }`;
} else {
return expression(identifier);
}
}
Example #10
Source File: helpers.ts From amplify-codegen with Apache License 2.0 | 6 votes |
fieldTypeEnum(type: GraphQLType, structName: string): string {
if (isNonNullType(type)) {
return `.nonNull(${this.fieldTypeEnum(type.ofType, structName)})`;
} else if (isListType(type)) {
return `.list(${this.fieldTypeEnum(type.ofType, structName)})`;
} else if (type instanceof GraphQLScalarType) {
return `.scalar(${this.typeNameForScalarType(type)}.self)`;
} else if (type instanceof GraphQLEnumType) {
return `.scalar(${type.name}.self)`;
} else if (isCompositeType(type)) {
return `.object(${structName}.selections)`;
} else {
throw new Error(`Unknown field type: ${type}`);
}
}
Example #11
Source File: helpers.ts From amplify-codegen with Apache License 2.0 | 6 votes |
// Types
typeNameFromGraphQLType(type: GraphQLType, unmodifiedTypeName?: string, isOptional?: boolean): string {
if (isNonNullType(type)) {
return this.typeNameFromGraphQLType(type.ofType, unmodifiedTypeName, false);
} else if (isOptional === undefined) {
isOptional = true;
}
let typeName;
if (isListType(type)) {
typeName = '[' + this.typeNameFromGraphQLType(type.ofType, unmodifiedTypeName) + ']';
} else if (type instanceof GraphQLScalarType) {
typeName = this.typeNameForScalarType(type);
} else {
typeName = unmodifiedTypeName || type.name;
}
return isOptional ? typeName + '?' : typeName;
}
Example #12
Source File: Utils.ts From graphql-ts-client with MIT License | 6 votes |
export function targetTypeOf(type: GraphQLType): GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | undefined {
if (type instanceof GraphQLNonNull) {
return targetTypeOf(type.ofType);
}
if (type instanceof GraphQLList) {
return targetTypeOf(type.ofType);
}
if (type instanceof GraphQLObjectType || type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType) {
return type;
}
return undefined;
}
Example #13
Source File: Writer.ts From graphql-ts-client with MIT License | 6 votes |
protected importType(type: GraphQLType) {
if (this.imported) {
throw new Error("Writer's importing has been terminated");
}
if (type instanceof GraphQLNonNull) {
this.importType(type.ofType);
} else if (type instanceof GraphQLList) {
this.importType(type.ofType);
} else if (type instanceof GraphQLInputObjectType) {
this.importedTypes.add(type);
} else if (type instanceof GraphQLEnumType) {
this.importedTypes.add(type);
} else if (type instanceof GraphQLScalarType && this.config.scalarTypeMap !== undefined) {
const mappedType = this.config.scalarTypeMap[type.name];
if (typeof mappedType == 'object') {
const importSource = mappedType.importSource;
let set = this.importedScalarTypes.get(importSource);
if (set === undefined) {
set = new Set<string>();
this.importedScalarTypes.set(importSource, set);
}
set.add(mappedType.typeName);
};
}
}
Example #14
Source File: serializeToJSON.ts From amplify-codegen with Apache License 2.0 | 6 votes |
function serializeType(type: GraphQLType) {
if (isEnumType(type)) {
return serializeEnumType(type);
} else if (isUnionType(type)) {
return serializeUnionType(type);
} else if (isInputObjectType(type)) {
return serializeInputObjectType(type);
} else if (isObjectType(type)) {
return serializeObjectType(type);
} else if (isInterfaceType(type)) {
return serializeInterfaceType(type);
} else if (isScalarType(type)) {
return serializeScalarType(type);
} else {
throw new Error(`Unexpected GraphQL type: ${type}`);
}
}
Example #15
Source File: index.ts From amplify-codegen with Apache License 2.0 | 6 votes |
compileOperation(operationDefinition: OperationDefinitionNode): Operation {
if (!operationDefinition.name) {
throw new Error('Operations should be named');
}
const filePath = filePathForNode(operationDefinition);
const operationName = operationDefinition.name.value;
const operationType = operationDefinition.operation;
const variables = (operationDefinition.variableDefinitions || []).map(node => {
const name = node.variable.name.value;
const type = typeFromAST(this.schema, node.type as NonNullTypeNode);
this.addTypeUsed(getNamedType(type as GraphQLType));
return { name, type: type as GraphQLNonNull<any> };
});
const source = print(operationDefinition);
const rootType = getOperationRootType(this.schema, operationDefinition) as GraphQLObjectType;
const selectionSet = this.compileSelectionSet(operationDefinition.selectionSet, rootType);
this.addTypeUsed(getNamedType((selectionSet.selections[0] as Field).type)); // store result type
return {
filePath,
operationName,
operationType,
variables,
source,
rootType,
selectionSet,
};
}
Example #16
Source File: index.ts From amplify-codegen with Apache License 2.0 | 6 votes |
addTypeUsed(type: GraphQLType) {
if (this.typesUsedSet.has(type)) return;
if (
isEnumType(type) ||
isUnionType(type) ||
isInputObjectType(type) ||
isInterfaceType(type) ||
isObjectType(type) ||
(isScalarType(type) && !isSpecifiedScalarType(type))
) {
this.typesUsedSet.add(type);
}
if (isInterfaceType(type) || isUnionType(type)) {
for (const concreteType of this.schema.getPossibleTypes(type)) {
this.addTypeUsed(getNamedType(concreteType));
}
}
if (isInputObjectType(type)) {
for (const field of Object.values(type.getFields())) {
this.addTypeUsed(getNamedType(field.type));
}
}
if (isObjectType(type)) {
for (const fieldType of type.getInterfaces()) {
this.addTypeUsed(getNamedType(fieldType));
}
for (const field of Object.values(type.getFields())) {
this.addTypeUsed(getNamedType(field.type));
}
}
}
Example #17
Source File: index.ts From amplify-codegen with Apache License 2.0 | 6 votes |
export function propertyFromVar(
context: LegacyCompilerContext,
field: {
name?: string;
type: GraphQLType;
fields?: any[];
responseName?: string;
description?: string;
fragmentSpreads?: any;
inlineFragments?: LegacyInlineFragment[];
fieldName?: string;
},
): Property {
let { name: fieldName, type: fieldType } = field;
fieldName = fieldName || field.responseName;
const propertyName = fieldName;
let property = { fieldName, fieldType, propertyName };
let isNullable = true;
if (fieldType instanceof GraphQLNonNull) {
isNullable = false;
}
const typeName = typeNameFromGraphQLType(context, fieldType, null, false);
return { ...property, typeName, isComposite: false, fieldType, isNullable };
}
Example #18
Source File: index.ts From amplify-codegen with Apache License 2.0 | 6 votes |
export function variablesFromField(
context: LegacyCompilerContext,
fields: {
name?: string;
type: GraphQLType;
responseName?: string;
description?: string;
fragmentSpreads?: any;
inlineFragments?: LegacyInlineFragment[];
fieldName?: string;
}[],
) {
return fields.map(field => propertyFromVar(context, field));
}
Example #19
Source File: isS3Object.ts From amplify-codegen with Apache License 2.0 | 6 votes |
export default function isS3Object(typeObj: GraphQLType): boolean {
if (isObjectType(typeObj)) {
const fields = typeObj.getFields();
const fieldName = typeObj.name;
const hasS3Fields = S3_FIELD_NAMES.every(s3Field => {
const field = fields[s3Field];
try {
const type = getType(field.type);
return field && isScalarType(type) && type.name === 'String';
} catch (e) {
return false;
}
});
return hasS3Fields && fieldName === 'S3Object';
}
return false;
}
Example #20
Source File: Writer.ts From graphql-ts-client with MIT License | 6 votes |
protected gqlTypeRef(type: GraphQLType) {
if (type instanceof GraphQLNonNull) {
this.gqlTypeRef(type.ofType);
this.text("!");
} else if (type instanceof GraphQLList) {
this.text("[");
this.gqlTypeRef(type.ofType);
this.text("]");
} else if (type instanceof GraphQLUnionType) {
this.enter("BLANK");
for (const itemType of type.getTypes()) {
this.separator(" | ");
this.text(itemType.name);
}
this.leave();
} else {
this.text(type.name);
}
}
Example #21
Source File: isRequired.ts From amplify-codegen with Apache License 2.0 | 6 votes |
export default function isRequired(typeObj: GraphQLType): boolean {
if (isNonNullType(typeObj) && isListType(typeObj.ofType)) {
// See if it's a Non-null List of Non-null Types
return isRequired(typeObj.ofType.ofType);
}
if (isListType(typeObj)) {
// See if it's a Nullable List of Non-null Types
return isNonNullType(typeObj.ofType);
}
return isNonNullType(typeObj);
}
Example #22
Source File: withNullableType.ts From payload with MIT License | 6 votes |
withNullableType = (field: NonPresentationalField, type: GraphQLType, forceNullable = false): GraphQLType => {
const hasReadAccessControl = field.access && field.access.read;
const condition = field.admin && field.admin.condition;
if (!forceNullable && field.required && !field.localized && !condition && !hasReadAccessControl) {
return new GraphQLNonNull(type);
}
return type;
}
Example #23
Source File: Writer.d.ts From graphql-ts-client with MIT License | 5 votes |
protected varableDecl(name: string, type: GraphQLType, overrideObjectTypeName?: string): void;
Example #24
Source File: Writer.d.ts From graphql-ts-client with MIT License | 5 votes |
protected typeRef(type: GraphQLType, objectRender?: string | ((type: GraphQLObjectType | GraphQLInterfaceType, field: GraphQLField<any, any>) => boolean)): void;
Example #25
Source File: Writer.d.ts From graphql-ts-client with MIT License | 5 votes |
protected gqlTypeRef(type: GraphQLType): void;
Example #26
Source File: codeGeneration.ts From amplify-codegen with Apache License 2.0 | 5 votes |
// pickedPropertyDeclarations declares specific properties selected by execution schemas or fragment schemas.
export function pickedPropertyDeclarations(generator: CodeGenerator, properties: Property[], isOptional = false) {
if (!properties) return;
properties.forEach(property => {
if (isAbstractType(getNamedType(property.type || property.fieldType!))) {
const propertySets = getPossibleTypeNames(generator, property).map(type => {
const inlineFragment =
property.inlineFragments &&
property.inlineFragments.find(inlineFragment => {
return inlineFragment.typeCondition.toString() == type;
});
if (inlineFragment) {
const fields = inlineFragment.fields.map(field => {
if (field.fieldName === '__typename') {
return {
...field,
typeName: `"${inlineFragment.typeCondition}"`,
type: { name: `"${inlineFragment.typeCondition}"` } as GraphQLType,
};
} else {
return field;
}
});
return propertiesFromFields(generator.context, fields);
} else {
const fields = property.fields!.map(field => {
if (field.fieldName === '__typename') {
return {
...field,
typeName: `"${type}"`,
type: { name: `"${type}"` } as GraphQLType,
};
} else {
return field;
}
});
return propertiesFromFields(generator.context, fields);
}
});
pickedPropertySetsDeclaration(generator, property, propertySets);
} else {
if (
(property.fields && property.fields.length > 0) ||
(property.inlineFragments && property.inlineFragments.length > 0) ||
(property.fragmentSpreads && property.fragmentSpreads.length > 0)
) {
propertyDeclaration(generator, property, () => {
const properties = propertiesFromFields(generator.context, property.fields!);
pickedPropertyDeclarations(generator, properties, isOptional);
});
} else {
propertyDeclaration(generator, { ...property, isOptional });
}
}
});
}
Example #27
Source File: Generator.ts From graphql-ts-client with MIT License | 5 votes |
private async generateFetcherTypes(ctx: FetcherContext) {
const dir = join(this.config.targetDir, "fetchers");
const emptyFetcherNameMap = new Map<GraphQLType, string>();
const defaultFetcherNameMap = new Map<GraphQLType, string>();
const promises = ctx.fetcherTypes
.map(async type => {
const stream = createStreamAndLog(
join(dir, `${type.name}${this.config?.fetcherSuffix ?? "Fetcher"}.ts`)
);
const writer = this.createFetcheWriter(
type,
ctx,
stream,
this.config
);
emptyFetcherNameMap.set(type, writer.emptyFetcherName);
if (writer.defaultFetcherName !== undefined) {
defaultFetcherNameMap.set(type, writer.defaultFetcherName);
}
writer.write();
await closeStream(stream);
});
await Promise.all([
...promises,
(async() => {
const stream = createStreamAndLog(join(dir, "index.ts"));
for (const type of ctx.fetcherTypes) {
const fetcherTypeName = `${type.name}${this.config?.fetcherSuffix ?? "Fetcher"}`;
stream.write(
`export type {${
[
fetcherTypeName,
(type instanceof GraphQLObjectType || type instanceof GraphQLInterfaceType) &&
ctx.typesWithParameterizedField.has(type) ?
`${type.name}Args` :
undefined,
...this.additionalExportedTypeNamesForFetcher(type, ctx)
]
.filter(text => text !== undefined)
.join(", ")
}} from './${fetcherTypeName}';\n`
);
const defaultFetcherName = defaultFetcherNameMap.get(type);
stream.write(
`export {${
emptyFetcherNameMap.get(type)
}${
defaultFetcherName !== undefined ?
`, ${defaultFetcherName}` :
''
}} from './${fetcherTypeName}';\n`
);
}
await stream.end();
})()
]);
}
Example #28
Source File: Generator.ts From graphql-ts-client with MIT License | 5 votes |
function connectionTypeTuple(
type: GraphQLObjectType | GraphQLInterfaceType
): [
GraphQLObjectType | GraphQLInterfaceType,
GraphQLObjectType | GraphQLInterfaceType,
GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType
] | undefined {
const edges = type.getFields()["edges"];
if (edges !== undefined) {
const listType =
edges.type instanceof GraphQLNonNull ?
edges.type.ofType :
edges.type;
if (listType instanceof GraphQLList) {
const edgeType =
listType.ofType instanceof GraphQLNonNull ?
listType.ofType.ofType :
listType.ofType;
if (edgeType instanceof GraphQLObjectType) {
const node = edgeType.getFields()["node"];
if (node !== undefined) {
if (!(edges.type instanceof GraphQLNonNull)) {
waring(
`The type "${type.name}" is connection, its field "edges" must be not-null list`
);
}
if (!(listType.ofType instanceof GraphQLNonNull)) {
waring(
`The type "${type.name}" is connection, element of its field "edges" must be not-null`
);
}
let nodeType: GraphQLType;
if (node.type instanceof GraphQLNonNull) {
nodeType = node.type.ofType;
} else {
waring(
`The type "${edgeType}" is edge, its field "node" must be non-null`
);
nodeType = node.type;
}
if (!(nodeType instanceof GraphQLObjectType) && !(nodeType instanceof GraphQLInterfaceType) && !(nodeType instanceof GraphQLUnionType)) {
throw new Error(
`The type "${edgeType}" is edge, its field "node" must be object, interface, union or their non-null wrappers`
);
}
const cursor = edgeType.getFields()["cursor"];
if (cursor === undefined) {
waring(
`The type "${edgeType}" is edge, it must defined a field named "cursor"`
);
} else {
const cursorType =
cursor.type instanceof GraphQLNonNull ?
cursor.type.ofType :
cursor.type;
if (cursorType !== GraphQLString) {
throw new Error(
`The type "${edgeType}" is edge, its field "cursor" must be string`
);
}
}
return [type, edgeType, nodeType];
}
}
}
}
return undefined;
}
Example #29
Source File: Writer.ts From graphql-ts-client with MIT License | 5 votes |
protected typeRef(
type: GraphQLType,
objectRender?: string | ((type: GraphQLObjectType | GraphQLInterfaceType, field: GraphQLField<any, any>) => boolean)
) {
if (type instanceof GraphQLScalarType) {
const mappedType =
(this.config.scalarTypeMap ?? EMPTY_MAP)[type.name]
?? SCALAR_MAP[type.name];
if (mappedType === undefined) {
throw new Error(`Unknown scalar type ${type.name}`);
}
if (typeof mappedType === 'string') {
this.text(mappedType);
} else {
this.text(mappedType.typeName);
}
} else if (type instanceof GraphQLObjectType ||
type instanceof GraphQLInterfaceType ||
type instanceof GraphQLUnionType
) {
if (typeof objectRender === "string") {
this.text(objectRender);
} else if (type instanceof GraphQLUnionType) {
this.enter("BLANK");
for (const itemType of type.getTypes()) {
this.separator(" | ");
this.text(itemType.name);
}
this.leave();
} else if (typeof objectRender === 'function') {
this.scope({type: "BLOCK", multiLines: true}, () => {
const fieldMap = type.getFields();
for (const fieldName in fieldMap) {
const field = fieldMap[fieldName];
if (objectRender(type, field)) {
this.separator(", ");
this.text("readonly ");
this.text(fieldName);
this.text(": ");
this.typeRef(field.type, objectRender);
}
}
});
} else {
this.text(type.name);
}
} else if (type instanceof GraphQLEnumType || type instanceof GraphQLInputObjectType) {
this.text(type.name);
} else if (type instanceof GraphQLNonNull) {
this.typeRef(type.ofType, objectRender);
} else if (type instanceof GraphQLList) {
if (type.ofType instanceof GraphQLNonNull) {
if (!this.config.arrayEditable) {
this.text("readonly ");
}
this.typeRef(type.ofType, objectRender);
this.text("[]");
} else {
if (!this.config.arrayEditable) {
this.text("Readonly");
}
this.text("Array<");
this.typeRef(type.ofType, objectRender);
this.text(" | undefined>");
}
}
}