graphql#GraphQLList TypeScript Examples
The following examples show how to use
graphql#GraphQLList.
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: utils.ts From tql with MIT License | 7 votes |
export function listType(type: GraphQLOutputType | GraphQLInputType): boolean {
if (type instanceof GraphQLNonNull) {
return listType(type.ofType);
} else if (type instanceof GraphQLList) {
return true;
} else {
return false;
}
}
Example #2
Source File: utils.ts From tql with MIT License | 7 votes |
export function outputType(type: GraphQLOutputType): GraphQLOutputType {
if (type instanceof GraphQLNonNull) {
return outputType(type.ofType);
} else if (type instanceof GraphQLList) {
return outputType(type.ofType);
} else {
return type;
}
}
Example #3
Source File: utils.ts From tql with MIT License | 7 votes |
export function inputType(type: GraphQLInputType): GraphQLInputType {
if (type instanceof GraphQLNonNull) {
return inputType(type.ofType);
} else if (type instanceof GraphQLList) {
return inputType(type.ofType);
} else {
return type;
}
}
Example #4
Source File: visitor.ts From proto2graphql with MIT License | 6 votes |
function visitDataType(
type: string,
repeated: Boolean,
resolver: () => protobuf.ReflectionObject | null,
context: Context
) {
const baseType = isScalar(type)
? convertScalar(type)
: getType(fullTypeName(resolver()), context);
return repeated ? new GraphQLList(baseType) : baseType;
}
Example #5
Source File: schema.ts From squid with GNU General Public License v3.0 | 6 votes |
function unwrapList(type: GraphQLOutputType): DeepList {
let nulls: boolean[] = []
while (type instanceof GraphQLList) {
type = type.ofType
if (type instanceof GraphQLNonNull) {
nulls.push(false)
type = type.ofType
} else {
nulls.push(true)
}
}
return {item: type, nulls}
}
Example #6
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 #7
Source File: buildPaginatedListType.ts From payload with MIT License | 6 votes |
buildPaginatedListType = (name, docType) => new GraphQLObjectType({
name,
fields: {
docs: {
type: new GraphQLList(docType),
},
totalDocs: { type: GraphQLInt },
offset: { type: GraphQLInt },
limit: { type: GraphQLInt },
totalPages: { type: GraphQLInt },
page: { type: GraphQLInt },
pagingCounter: { type: GraphQLInt },
hasPrevPage: { type: GraphQLBoolean },
hasNextPage: { type: GraphQLBoolean },
prevPage: { type: GraphQLBoolean },
nextPage: { type: GraphQLBoolean },
},
})
Example #8
Source File: instructor.ts From peterportal-public-api with MIT License | 6 votes |
instructorType: GraphQLObjectType = new GraphQLObjectType({
name: 'Instructor',
fields: () => ({
name: { type: GraphQLString },
shortened_name: {
type: GraphQLString,
description: "Name as it appears on webreg. Follows the format: `DOE, J.`",
resolve: (instructor) => {
if (instructor.shortened_name) {
return instructor.shortened_name
} else {
// If the shortened_name wasn't provided,
// we can construct it from the name.
const name_parts = instructor.name.split(' ');
return `${name_parts[name_parts.length-1]}, ${name_parts[0][0]}.`.toUpperCase()
}
}
},
ucinetid: { type: GraphQLString },
email: {type: GraphQLString },
title: { type: GraphQLString },
department: { type: GraphQLString },
schools: { type: new GraphQLList(GraphQLString) },
related_departments: { type: new GraphQLList(GraphQLString) },
course_history: {
type: new GraphQLList(courseType),
resolve: (instructor) => {
return getInstructor(instructor.ucinetid)["course_history"].map(course_id => getCourse(course_id.replace(/ /g, "")));
}
}
})
})
Example #9
Source File: grades.ts From peterportal-public-api with MIT License | 6 votes |
gradeDistributionCollectionType: GraphQLObjectType = new GraphQLObjectType({
name: 'GradeDistributionCollection',
fields: () => ({
aggregate: { type: gradeDistributionCollectionAggregateType },
grade_distributions: {type: new GraphQLList(gradeDistributionType)},
instructors: {
type: new GraphQLList(GraphQLString),
description: "List of instructors present in the Grade Distribution Collection"
}
})
})
Example #10
Source File: createControllerSchemas.ts From davinci with MIT License | 6 votes |
/**
* Returns a flatten list of fields
* @param fieldASTs
* @param returnType
* @param basePath
*/
export function getFieldsSelection(fieldASTs, returnType, basePath?: string) {
const { selections } = fieldASTs.selectionSet;
return selections.reduce((projs, selection) => {
const fieldName = selection.name.value;
const isParentList = returnType instanceof GraphQLList;
const fieldReturnType = (returnType.ofType || returnType).getFields()[fieldName].type;
const pathSuffix = isParentList ? '[]' : '';
const fieldPath = _.compact([`${basePath || ''}${pathSuffix}`, fieldName]).join('.');
if (selection.selectionSet) {
return [...projs, ...getFieldsSelection(selection, fieldReturnType, fieldPath)];
}
return [...projs, fieldPath];
}, []);
}
Example #11
Source File: visitor.ts From proto2graphql with MIT License | 6 votes |
function visitFieldType(field: protobuf.Field, context: Context) {
if (field instanceof protobuf.MapField) {
return new GraphQLList(getType(fullTypeName(field), context));
}
return visitDataType(
field.type,
field.repeated,
() => field.resolve().resolvedType,
context
);
}
Example #12
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 #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: 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 #15
Source File: schema-resolver.ts From graphql-mesh with MIT License | 6 votes |
resolve(input: { type: SoapType; isList: boolean }): GraphQLOutputType {
try {
const type: GraphQLOutputType = this.resolveOutputType(input.type);
return input.isList ? new GraphQLList(type) : type;
} catch (err) {
const errStacked = new Error(`could not resolve output type for ${util.inspect(input)}`);
errStacked.stack += '\nCaused by: ' + err.stack;
throw errStacked;
}
}
Example #16
Source File: getType.test.ts From amplify-codegen with Apache License 2.0 | 6 votes |
describe('getType', () => {
const testObj = new GraphQLObjectType({
name: 'Address',
fields: {
street: { type: GraphQLString },
number: { type: GraphQLInt },
requiredInt: { type: new GraphQLNonNull(GraphQLInt) },
listOfInt: { type: new GraphQLList(GraphQLInt) },
listOfNonNullInt: { type: new GraphQLNonNull(new GraphQLList(GraphQLInt)) },
},
});
it('should return string type for street', () => {
expect(getType(testObj.getFields().street.type)).toEqual(GraphQLString);
});
it('should return integer type for number', () => {
expect(getType(testObj.getFields().number.type)).toEqual(GraphQLInt);
});
it('should return integer type for a Non-Null integer', () => {
expect(getType(testObj.getFields().requiredInt.type)).toEqual(GraphQLInt);
});
it('should return integer type for list of integer type', () => {
expect(getType(testObj.getFields().listOfInt.type)).toEqual(GraphQLInt);
});
it('should return integer type for a list of non null integer type', () => {
expect(getType(testObj.getFields().listOfNonNullInt.type)).toEqual(GraphQLInt);
});
});
Example #17
Source File: schema-resolver.ts From graphql-mesh with MIT License | 6 votes |
resolve(input: { type: SoapType; isList: boolean }): GraphQLInputType {
try {
const type: GraphQLInputType = this.resolveInputType(input.type);
return input.isList ? new GraphQLList(type) : type;
} catch (err) {
const errStacked = new Error(`could not resolve output type for ${util.inspect(input)}`);
errStacked.stack += '\nCaused by: ' + err.stack;
throw errStacked;
}
}
Example #18
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 #19
Source File: schema.ts From Deep-Lynx with MIT License | 5 votes |
// each key in the relationship should be included on the input object as a field to be filtered on
inputFieldsForRelationship(relationship: MetatypeRelationship): {[key: string]: any} {
const fields: {[key: string]: any} = {};
relationship.keys?.forEach((relationshipKey) => {
const propertyName = stringToValidPropertyName(relationshipKey.property_name);
switch (relationshipKey.data_type) {
// because we have no specification on our internal number type, we
// must set this as a float for now
case 'number': {
fields[propertyName] = {
type: GraphQLFloat,
};
break;
}
case 'boolean': {
fields[propertyName] = {
type: GraphQLBoolean,
};
break;
}
case 'string' || 'date' || 'file': {
fields[propertyName] = {
type: GraphQLString,
};
break;
}
case 'list': {
fields[propertyName] = {
type: new GraphQLList(GraphQLJSON),
};
break;
}
case 'enumeration': {
const enumMap: {[key: string]: GraphQLEnumValueConfig} = {};
if (relationshipKey.options) {
relationshipKey.options.forEach((option) => {
enumMap[option] = {
value: option,
};
});
}
fields[propertyName] = {
type: new GraphQLEnumType({
name: stringToValidPropertyName(`${relationship.name}_${relationshipKey.name}_Enum_TypeB`),
values: enumMap,
}),
};
break;
}
default: {
fields[propertyName] = {
type: GraphQLString,
};
}
}
});
return fields;
}
Example #20
Source File: schema.ts From Deep-Lynx with MIT License | 5 votes |
// each key in the metatype should be included on the input object as a field to be filtered on
inputFieldsForMetatype(metatype: Metatype): {[key: string]: any} {
const fields: {[key: string]: any} = {};
metatype.keys?.forEach((metatypeKey) => {
const propertyName = stringToValidPropertyName(metatypeKey.property_name);
switch (metatypeKey.data_type) {
// because we have no specification on our internal number type, we
// must set this as a float for now
case 'number': {
fields[propertyName] = {
type: GraphQLFloat,
};
break;
}
case 'boolean': {
fields[propertyName] = {
type: GraphQLBoolean,
};
break;
}
case 'string' || 'date' || 'file': {
fields[propertyName] = {
type: GraphQLString,
};
break;
}
case 'list': {
fields[propertyName] = {
type: new GraphQLList(GraphQLJSON),
};
break;
}
case 'enumeration': {
const enumMap: {[key: string]: GraphQLEnumValueConfig} = {};
if (metatypeKey.options) {
metatypeKey.options.forEach((option) => {
enumMap[option] = {
value: option,
};
});
}
// we have to include a UUID here so that we can insure a uniquely named type
fields[propertyName] = {
type: new GraphQLEnumType({
name: stringToValidPropertyName(`${metatype.name}_${metatypeKey.name}_Enum_Type_B`),
values: enumMap,
}),
};
break;
}
default: {
fields[propertyName] = {
type: GraphQLString,
};
}
}
});
return fields;
}
Example #21
Source File: buildWhereInputType.ts From payload with MIT License | 5 votes |
buildWhereInputType = (name: string, fields: Field[], parentName: string): GraphQLInputObjectType => {
// This is the function that builds nested paths for all
// field types with nested paths.
const fieldTypes = fields.reduce((schema, field) => {
if (!fieldIsPresentationalOnly(field) && !field.hidden) {
const getFieldSchema = fieldToSchemaMap(parentName)[field.type];
if (getFieldSchema) {
const fieldSchema = getFieldSchema(field);
if (fieldHasSubFields(field)) {
return {
...schema,
...(fieldSchema.reduce((subFields, subField) => ({
...subFields,
[formatName(subField.key)]: subField.type,
}), {})),
};
}
return {
...schema,
[formatName(field.name)]: fieldSchema,
};
}
}
return schema;
}, {});
fieldTypes.id = {
type: withOperators(
{ name: 'id' } as FieldAffectingData,
GraphQLJSON,
parentName,
[...operators.equality, ...operators.contains],
),
};
const fieldName = formatName(name);
return new GraphQLInputObjectType({
name: `${fieldName}_where`,
fields: {
...fieldTypes,
OR: {
type: new GraphQLList(new GraphQLInputObjectType({
name: `${fieldName}_where_or`,
fields: fieldTypes,
})),
},
AND: {
type: new GraphQLList(new GraphQLInputObjectType({
name: `${fieldName}_where_and`,
fields: fieldTypes,
})),
},
},
});
}
Example #22
Source File: custom-type-resolver.ts From graphql-mesh with MIT License | 5 votes |
ENTITIES = new GraphQLList(GraphQLID);
Example #23
Source File: schedule.ts From peterportal-public-api with MIT License | 5 votes |
courseOfferingType: GraphQLObjectType = new GraphQLObjectType({
name: "CourseOffering",
fields: () => ({
year: { type: GraphQLString },
quarter: { type: GraphQLString },
instructors: {
type: new GraphQLList(instructorType),
resolve: (offering) => {
return offering.instructors.map((name: string) => {
//Fetch all possible ucinetids from the instructor.
let ucinetids : string[] = getUCINetIDFromName(name);
//If only one ucinetid exists and it's in the instructor cache,
//then we can return the instructor for it.
if (ucinetids && ucinetids.length == 1) {
const instructor = getInstructor(ucinetids[0]);
if (instructor) { return instructor; }
}
//If there is more than one and the course exists,
//use the course to figure it out.
else if (ucinetids && ucinetids.length > 1 && offering.course) {
//Filter our instructors by those with related departments.
let course_dept = offering.course.department;
let instructors = ucinetids.map(id => getInstructor(id)).filter( temp => temp.related_departments.includes(course_dept));
//If only one is left and it's in the instructor cache, we can return it.
if (instructors.length == 1) {
return instructors[0];
} else {
//Filter instructors by those that taught the course before.
instructors = instructors.filter( inst => {
return inst.course_history.map((course) => course.replace(/ /g, "")).includes(offering.course.id);
});
//If only one is left and it's in the instructor cache, we can return it.
if (instructors.length == 1) {
return instructors[0];
}
}
}
//If we haven't found any instructors, then just return the shortened name.
return {shortened_name: name};
})
}
},
final_exam: { type: GraphQLString },
max_capacity: { type: GraphQLFloat },
meetings: { type: new GraphQLList(meetingType) },
num_section_enrolled: { type: GraphQLFloat },
num_total_enrolled: { type: GraphQLFloat },
num_new_only_reserved: { type: GraphQLFloat },
num_on_waitlist: {
type: GraphQLFloat,
resolve: (offering) => {
return offering.num_on_waitlist === 'n/a' ? null : offering.num_on_waitlist;
}
},
num_requested: { type: GraphQLFloat },
restrictions: { type: GraphQLString },
section: { type: sectionInfoType },
status: { type: GraphQLString },
units: { type: GraphQLString },
course: {
type: courseType,
resolve: (offering) => {
// Get the course from the cache.
const course = getCourse(offering.course.id);
// If it's not in our cache, return whatever information was provided.
// Usually, it will at least have id, department, and number
return course ? course : offering.course;
}
}
})
})
Example #24
Source File: custom-type-resolver.ts From graphql-mesh with MIT License | 5 votes |
IDREFS = new GraphQLList(GraphQLID);
Example #25
Source File: schema_builder.ts From graphql-mesh with MIT License | 5 votes |
/**
* Creates a list type or returns an existing one, and stores it in data
*/
function createOrReuseList<TSource, TContext, TArgs>({
def,
operation,
iteration,
isInputObjectType,
data,
includeHttpDetails,
logger,
}: CreateOrReuseComplexTypeParams<TSource, TContext, TArgs>): GraphQLList<any> {
const translationLogger = logger.child('translation');
const name = isInputObjectType ? def.graphQLInputObjectTypeName : def.graphQLTypeName;
// Try to reuse existing Object Type
if (!isInputObjectType && def.graphQLType && typeof def.graphQLType !== 'undefined') {
translationLogger.debug(`Reuse GraphQLList '${def.graphQLTypeName}'`);
return def.graphQLType as GraphQLList<any>;
} else if (isInputObjectType && def.graphQLInputObjectType && typeof def.graphQLInputObjectType !== 'undefined') {
translationLogger.debug(`Reuse GraphQLList '${def.graphQLInputObjectTypeName}'`);
return def.graphQLInputObjectType as GraphQLList<any>;
}
// Create new List Object Type
translationLogger.debug(`Create GraphQLList '${def.graphQLTypeName}'`);
// Get definition of the list item, which should be in the sub definitions
const itemDef = def.subDefinitions as DataDefinition;
// Equivalent to schema.items
const itemsSchema = itemDef.schema;
// Equivalent to `{name}ListItem`
const itemsName = itemDef.graphQLTypeName;
const itemsType = getGraphQLType({
def: itemDef,
data,
operation,
iteration: iteration + 1,
isInputObjectType,
includeHttpDetails,
logger,
});
if (itemsType !== null) {
const listObjectType = new GraphQLList(itemsType);
// Store newly created list type
if (!isInputObjectType) {
def.graphQLType = listObjectType;
} else {
def.graphQLInputObjectType = listObjectType;
}
return listObjectType;
} else {
throw new Error(`Cannot create list item object type '${itemsName}' in list
'${name}' with schema '${JSON.stringify(itemsSchema)}'`);
}
}
Example #26
Source File: getType.ts From amplify-codegen with Apache License 2.0 | 5 votes |
export default function getType(typeObj: GraphQLType): GQLConcreteType {
if (typeObj instanceof GraphQLList || typeObj instanceof GraphQLNonNull) {
return getType(typeObj.ofType);
}
return typeObj;
}
Example #27
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>");
}
}
}
Example #28
Source File: typeNameFromGraphQLType.ts From amplify-codegen with Apache License 2.0 | 5 votes |
describe('Swift code generation: Types', () => {
let helpers: Helpers;
beforeEach(() => {
helpers = new Helpers({});
});
describe('#typeNameFromGraphQLType()', () => {
it('should return String? for GraphQLString', () => {
expect(helpers.typeNameFromGraphQLType(GraphQLString)).toBe('String?');
});
it('should return String for GraphQLNonNull(GraphQLString)', () => {
expect(helpers.typeNameFromGraphQLType(new GraphQLNonNull(GraphQLString))).toBe('String');
});
it('should return [String?]? for GraphQLList(GraphQLString)', () => {
expect(helpers.typeNameFromGraphQLType(new GraphQLList(GraphQLString))).toBe('[String?]?');
});
it('should return [String?] for GraphQLNonNull(GraphQLList(GraphQLString))', () => {
expect(helpers.typeNameFromGraphQLType(new GraphQLNonNull(new GraphQLList(GraphQLString)))).toBe('[String?]');
});
it('should return [String]? for GraphQLList(GraphQLNonNull(GraphQLString))', () => {
expect(helpers.typeNameFromGraphQLType(new GraphQLList(new GraphQLNonNull(GraphQLString)))).toBe('[String]?');
});
it('should return [String] for GraphQLNonNull(GraphQLList(GraphQLNonNull(GraphQLString)))', () => {
expect(helpers.typeNameFromGraphQLType(new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLString))))).toBe('[String]');
});
it('should return [[String?]?]? for GraphQLList(GraphQLList(GraphQLString))', () => {
expect(helpers.typeNameFromGraphQLType(new GraphQLList(new GraphQLList(GraphQLString)))).toBe('[[String?]?]?');
});
it('should return [[String?]]? for GraphQLList(GraphQLNonNull(GraphQLList(GraphQLString)))', () => {
expect(helpers.typeNameFromGraphQLType(new GraphQLList(new GraphQLNonNull(new GraphQLList(GraphQLString))))).toBe('[[String?]]?');
});
it('should return Int? for GraphQLInt', () => {
expect(helpers.typeNameFromGraphQLType(GraphQLInt)).toBe('Int?');
});
it('should return Double? for GraphQLFloat', () => {
expect(helpers.typeNameFromGraphQLType(GraphQLFloat)).toBe('Double?');
});
it('should return Bool? for GraphQLBoolean', () => {
expect(helpers.typeNameFromGraphQLType(GraphQLBoolean)).toBe('Bool?');
});
it('should return GraphQLID? for GraphQLID', () => {
expect(helpers.typeNameFromGraphQLType(GraphQLID)).toBe('GraphQLID?');
});
it('should return String? for a custom scalar type', () => {
expect(helpers.typeNameFromGraphQLType(new GraphQLScalarType({ name: 'CustomScalarType', serialize: String }))).toBe('String?');
});
it('should return a passed through custom scalar type with the passthroughCustomScalars option', () => {
helpers.options.passthroughCustomScalars = true;
helpers.options.customScalarsPrefix = '';
expect(helpers.typeNameFromGraphQLType(new GraphQLScalarType({ name: 'CustomScalarType', serialize: String }))).toBe(
'CustomScalarType?'
);
});
it('should return a passed through custom scalar type with a prefix with the customScalarsPrefix option', () => {
helpers.options.passthroughCustomScalars = true;
helpers.options.customScalarsPrefix = 'My';
expect(helpers.typeNameFromGraphQLType(new GraphQLScalarType({ name: 'CustomScalarType', serialize: String }))).toBe(
'MyCustomScalarType?'
);
});
});
});
Example #29
Source File: generateSchema.test.ts From davinci with MIT License | 4 votes |
describe('schema generation', () => {
describe('#generateGQLSchema', () => {
it('supports primitive types', () => {
class Customer {
@field()
firstname: string;
@field()
age: number;
@field()
isActive: boolean;
@field()
date: Date
@field()
blob: Object
@field({ type: String })
something() {}
}
const { schema } = generateGQLSchema({ type: Customer });
should(schema)
.have.property('name')
.equal('Customer');
const fields = schema.getFields();
should(Object.keys(fields)).be.deepEqual(['firstname', 'age', 'isActive', 'date', 'blob', 'something']);
should(fields.firstname.type).be.equal(GraphQLString);
should(fields.age.type).be.equal(GraphQLFloat);
should(fields.isActive.type).be.equal(GraphQLBoolean);
should(fields.date.type).be.equal(GraphQLDateTime);
should(fields.blob.type).be.equal(GraphQLJSON);
should(fields.something.type).be.equal(GraphQLString);
});
it('supports nested classes', () => {
class CustomerBirth {
@field()
place: string;
}
class Customer {
@field()
birth: CustomerBirth;
}
const { schemas } = generateGQLSchema({ type: Customer });
should(schemas)
.have.property('Customer')
.instanceOf(GraphQLObjectType);
// @ts-ignore
const { birth } = schemas.Customer.getFields();
should(birth.type).be.instanceOf(GraphQLObjectType);
// @ts-ignore
const { place } = schemas.CustomerBirth.getFields();
should(place.type).be.equal(GraphQLString);
});
it('should pass fields defined as function as resolve', () => {
class Customer {
@field({ type: String })
something(parent, args, context, info) {
return { parent, args, context, info };
}
@field({ type: [Number] })
somethingArray(parent, args, context, info) {
return { parent, args, context, info };
}
}
const { schema } = generateGQLSchema({ type: Customer });
should(schema).be.instanceOf(GraphQLObjectType);
// @ts-ignore
const { something, somethingArray } = schema.getFields();
should(something.type).be.equal(GraphQLString);
should(something.resolve).be.equal(Customer.prototype.something);
should(somethingArray.type).be.instanceOf(GraphQLList);
should(somethingArray.type.ofType).be.equal(GraphQLFloat);
should(somethingArray.resolve).be.equal(Customer.prototype.somethingArray);
});
it('should create an external resolver', () => {
class Book {}
class Author {
@field()
title: string;
}
// @ts-ignore
class AuthorController {
@fieldResolver(Book, 'authors', [Author])
getBookAuthors() {}
}
const { schema } = generateGQLSchema({ type: Book });
should(schema).be.instanceOf(GraphQLObjectType);
// @ts-ignore
const { authors } = schema.getFields();
should(authors.type).be.instanceOf(GraphQLList);
should(authors.type.ofType).be.instanceOf(GraphQLObjectType);
should(authors.resolve).be.type('function');
});
it('supports arrays', () => {
class CustomerPhone {
@field()
number: string;
}
class Customer {
@field({ type: [CustomerPhone] })
phones: CustomerPhone[];
@field({ type: [String] })
tags: string[];
}
const schemas: any = generateGQLSchema({ type: Customer }).schemas;
should(Object.keys(schemas.Customer.getFields())).be.deepEqual(['phones', 'tags']);
should(Object.keys(schemas.CustomerPhone.getFields())).be.deepEqual(['number']);
const { tags, phones } = schemas.Customer.getFields();
should(tags.type)
.be.instanceOf(GraphQLList)
.have.property('ofType')
.equal(GraphQLString);
should(phones.type)
.be.instanceOf(GraphQLList)
.have.property('ofType')
.equal(schemas.CustomerPhone);
});
it('supports union types', () => {
class Cat {
@field()
breed: string;
}
class Human {
@field()
phone: string;
}
const resolveType = () => 'Human';
const Animal = new UnionType('Animal', [Cat, Human], resolveType);
const schemas: any = generateGQLSchema({ type: Animal }).schemas;
should(Object.keys(schemas)).be.deepEqual(['Cat', 'Human', 'Animal']);
const types = schemas.Animal.getTypes();
should(types[0].name).be.equal('Cat')
should(types[1].name).be.equal('Human')
should(types).have.length(2);
should(schemas.Animal).be.instanceOf(GraphQLUnionType);
});
it('if transformMetadata is supplied, it should transform the metadata', () => {
class Customer {
@field()
firstname: string;
}
const transformMetadata = (metadata, { type: t, parentType }) => {
const type = _fp.get('opts.type', metadata) || t;
if (type === String && parentType.name !== 'Query') {
class Query {
@field()
EQ: string;
}
return _fp.set('opts.type', Query, metadata);
}
return metadata;
};
const schemas: any = generateGQLSchema({ type: Customer, transformMetadata }).schemas;
const fields = schemas.Customer.getFields();
should(fields.firstname.type).be.instanceOf(GraphQLObjectType);
should(fields.firstname.type.getFields()).have.property('EQ');
});
});
});