graphql#GraphQLObjectType TypeScript Examples
The following examples show how to use
graphql#GraphQLObjectType.
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: upper-case.directive.ts From nestjs-mercurius with MIT License | 6 votes |
visitFieldDefinition(
field: GraphQLField<any, any>,
_details: { objectType: GraphQLObjectType | GraphQLInterfaceType },
): GraphQLField<any, any> | void | null {
const { resolve = defaultFieldResolver } = field;
field.resolve = async function (...args) {
const result = await resolve.apply(this, args);
if (typeof result === 'string') {
return result.toUpperCase();
}
return result;
};
}
Example #2
Source File: generate-query.ts From graphql-query-generator with MIT License | 6 votes |
function fieldHasLeafs(
field: FieldDefinitionNode,
schema: GraphQLSchema
): boolean {
const ast = schema.getType(getTypeName(field.type)).astNode
if (
ast.kind === Kind.OBJECT_TYPE_DEFINITION ||
ast.kind === Kind.INTERFACE_TYPE_DEFINITION
) {
return ast.fields.some((child) => {
const childAst = schema.getType(getTypeName(child.type)).astNode
return (
typeof childAst === 'undefined' ||
childAst.kind === Kind.SCALAR_TYPE_DEFINITION
)
})
} else if (ast.kind === Kind.UNION_TYPE_DEFINITION) {
return ast.types.some((child) => {
let unionNamedTypes = (schema.getType(
child.name.value
) as GraphQLObjectType).astNode.fields
return unionNamedTypes.some((child) => {
const childAst = schema.getType(getTypeName(child.type)).astNode
return (
typeof childAst === 'undefined' ||
childAst.kind === Kind.SCALAR_TYPE_DEFINITION
)
})
})
}
return false
}
Example #3
Source File: schema.ts From apollo-server-vercel with MIT License | 6 votes |
TestSchema = new GraphQLSchema({
query: QueryRootType,
mutation: new GraphQLObjectType({
name: `MutationRoot`,
fields: {
writeTest: {
type: QueryRootType,
resolve: (): {} => ({})
}
}
})
})
Example #4
Source File: ts-artifacts.ts From graphql-mesh with MIT License | 6 votes |
function buildSignatureBasedOnRootFields(
codegenHelpers: CodegenHelpers,
type: Maybe<GraphQLObjectType>,
namespace: string
): Record<string, string> {
if (!type) {
return {};
}
const fields = type.getFields();
const operationMap: Record<string, string> = {};
for (const fieldName in fields) {
const field = fields[fieldName];
const argsExists = field.args && field.args.length > 0;
const argsName = argsExists ? `${namespace}.${type.name}${field.name}Args` : '{}';
const parentTypeNode: NamedTypeNode = {
kind: Kind.NAMED_TYPE,
name: {
kind: Kind.NAME,
value: type.name,
},
};
operationMap[fieldName] = ` /** ${field.description} **/\n ${
field.name
}: InContextSdkMethod<${namespace}.${codegenHelpers.getTypeToUse(
parentTypeNode
)}['${fieldName}'], ${argsName}, ${unifiedContextIdentifier}>`;
}
return operationMap;
}
Example #5
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 #6
Source File: FetcherWriter.ts From graphql-ts-client with MIT License | 6 votes |
protected importingBehavior(type: GraphQLNamedType): ImportingBehavior {
if (type === this.modelType) {
return "SELF";
}
if (type instanceof GraphQLObjectType || type instanceof GraphQLInterfaceType) {
return "SAME_DIR";
}
return "OTHER_DIR";
}
Example #7
Source File: visitor.ts From proto2graphql with MIT License | 6 votes |
function visitMessage(message: protobuf.Type, context: Context) {
const objectType = new GraphQLObjectType({
name: fullTypeName(message),
fields: () => visitFields(message.fieldsArray, context)
});
setType(objectType, context);
return [
objectType,
visitOneOfs(message, context),
visitMaps(message, context),
visitNested(message.nestedArray, context)
];
}
Example #8
Source File: index.test.ts From hono with MIT License | 6 votes |
QueryRootType = new GraphQLObjectType({
name: 'QueryRoot',
fields: {
test: {
type: GraphQLString,
args: {
who: { type: GraphQLString },
},
resolve: (_root, args: { who?: string }) => 'Hello ' + (args.who ?? 'World'),
},
thrower: {
type: GraphQLString,
resolve() {
throw new Error('Throws!')
},
},
},
})
Example #9
Source File: grades.ts From peterportal-public-api with MIT License | 6 votes |
gradeDistributionType: GraphQLObjectType = new GraphQLObjectType({
name: "GradeDistribution",
fields: () => ({
grade_a_count: { type: GraphQLFloat },
grade_b_count: { type: GraphQLFloat },
grade_c_count: { type: GraphQLFloat },
grade_d_count: { type: GraphQLFloat },
grade_f_count: { type: GraphQLFloat },
grade_p_count: { type: GraphQLFloat },
grade_np_count: { type: GraphQLFloat },
grade_w_count: { type: GraphQLFloat },
average_gpa: { type: GraphQLFloat },
course_offering: { type: courseOfferingType }
})
})
Example #10
Source File: index.ts From aloxide with Apache License 2.0 | 6 votes |
graphqlSchema = new GraphQLSchema({
types: graphqlFields.map(({ graphQLObjectType }) => graphQLObjectType),
query: new GraphQLObjectType({
name: 'Query',
fields: graphqlFields
.map(({ connectionQueryField }) => connectionQueryField)
.reduce(
(a, c) =>
Object.assign(a, {
[`query${c.name}`]: c,
}),
{},
),
}),
})
Example #11
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 #12
Source File: renderTyping.test.ts From genql with MIT License | 6 votes |
testCase = (
field: string,
expected: string,
undefinableValues: boolean,
undefinableFields: boolean,
) => {
const fields = (<GraphQLObjectType>schema.getType('Object')).getFields()
const actual = renderTyping(
fields[field].type,
undefinableValues,
undefinableFields,
)
expect(actual).toBe(expected)
}
Example #13
Source File: schema.ts From squid with GNU General Public License v3.0 | 6 votes |
export function buildModel(schema: GraphQLSchema): Model {
let types = schema.getTypeMap()
let model: Model = {}
for (let key in types) {
let type = types[key]
if (isEntityType(type)) {
addEntityOrJsonObjectOrInterface(model, type as GraphQLObjectType)
}
}
validateModel(model)
return model
}
Example #14
Source File: types.ts From tql with MIT License | 6 votes |
printField = (field: GraphQLField<any, any, any>): string => {
const { args } = field;
const isList = listType(field.type);
const isNonNull = field.type instanceof GraphQLNonNull;
const type = outputType(field.type);
const printVariables = () => {
return args.length > 0
? `(variables: { ${args.map(printVariable).join(", ")} })`
: "";
};
if (type instanceof GraphQLScalarType) {
return (
`${args.length > 0 ? "" : "readonly"} ${field.name}${printVariables()}: ${
isList ? `ReadonlyArray<${toPrimitive(type)}>` : `${toPrimitive(type)}`
}` + (isNonNull ? "" : " | null")
);
} else if (type instanceof GraphQLEnumType) {
return (
`${args.length > 0 ? "" : "readonly"} ${field.name}${printVariables()}: ${
isList ? `ReadonlyArray<${type.name}>` : `${type.name}`
}` + (isNonNull ? "" : " | null")
);
} else if (
type instanceof GraphQLInterfaceType ||
type instanceof GraphQLUnionType ||
type instanceof GraphQLObjectType
) {
return (
`${args.length > 0 ? "" : "readonly"} ${field.name}${printVariables()}: ${
isList ? `ReadonlyArray<I${type.name}>` : `I${type.name}`
}` + (isNonNull ? "" : " | null")
);
} else {
throw new Error("Unable to print field.");
}
}
Example #15
Source File: faderation-factory.util.ts From nestjs-mercurius with MIT License | 5 votes |
/**
* Inspired by https://github.com/mercurius-js/mercurius/blob/master/lib/federation.js#L231
* Accept a GraphQLSchema to transform instead of a plain string containing a graphql schema
* @param schema
*/
export function transformFederatedSchema(schema: GraphQLSchema) {
// FIXME remove this dependency
// but graphql#printSchema does not print necessary federation directives
const { printSubgraphSchema } = loadPackage(
'@apollo/subgraph',
'FederationFactory',
() => require('@apollo/subgraph'),
);
// Workaround for https://github.com/mercurius-js/mercurius/issues/273
const schemaString = printSubgraphSchema(schema)
.replace('type Query {', 'type Query @extends {')
.replace('type Mutation {', 'type Mutation @extends {')
.replace('type Subscription {', 'type Subscription @extends {');
schema = extendSchema(schema, parse(FEDERATION_SCHEMA), {
assumeValidSDL: true,
});
if (!schema.getType('Query')) {
schema = new GraphQLSchema({
...schema.toConfig(),
query: new GraphQLObjectType({
name: 'Query',
fields: {},
}),
});
}
schema = extendSchema(
schema,
parse(`
extend type Query {
_service: _Service!
}
`),
{
assumeValid: true,
},
);
const query = schema.getType('Query') as GraphQLObjectType;
const queryFields = query.getFields();
queryFields._service = {
...queryFields._service,
resolve: () => ({ sdl: schemaString }),
};
const entityTypes = Object.values(schema.getTypeMap()).filter(
(type) => isObjectType(type) && typeIncludesDirective(type, 'key'),
);
if (entityTypes.length > 0) {
schema = extendSchema(
schema,
parse(`
union _Entity = ${entityTypes.join(' | ')}
extend type Query {
_entities(representations: [_Any!]!): [_Entity]!
}
`),
{
assumeValid: true,
},
);
const query = schema.getType('Query') as GraphQLObjectType;
const queryFields = query.getFields();
queryFields._entities = {
...queryFields._entities,
resolve: (_source, { representations }, context, info) => {
return representations.map((reference) => {
const { __typename } = reference;
const type = info.schema.getType(__typename);
if (!type || !isObjectType(type)) {
throw new MER_ERR_GQL_GATEWAY_INVALID_SCHEMA(__typename);
}
const resolveReference = (type as any).resolveReference
? (type as any).resolveReference
: function defaultResolveReference() {
return reference;
};
const result = resolveReference(reference, {}, context, info);
if (result && 'then' in result && typeof result.then === 'function') {
return result.then((x) => addTypeNameToResult(x, __typename));
}
return addTypeNameToResult(result, __typename);
});
},
};
}
return schema;
}
Example #16
Source File: schema.ts From apollo-server-vercel with MIT License | 5 votes |
QueryRootType = new GraphQLObjectType({
name: `QueryRoot`,
fields: {
test: {
type: GraphQLString,
args: {
who: {
type: GraphQLString
}
},
resolve: (_, args): string => `Hello ${String(args.who) || `World`}`
},
thrower: {
type: new GraphQLNonNull(GraphQLString),
resolve: (): void => {
throw new Error(`Throws!`);
}
},
custom: {
type: GraphQLString,
args: {
foo: {
type: new GraphQLScalarType({
name: `Foo`,
serialize: <T>(v: T): T => v,
parseValue: (): void => {
throw new Error(`Something bad happened`);
},
parseLiteral: (): void => {
throw new Error(`Something bad happened`);
}
})
}
}
},
context: {
type: GraphQLString,
resolve: (_obj, _args, context): typeof context => context
}
}
})
Example #17
Source File: auth_builder.ts From graphql-mesh with MIT License | 5 votes |
/**
* Gets the viewer Object, resolve function, and arguments
*/
function getViewerOT<TSource, TContext, TArgs>(
name: string,
protocolName: string,
securityType: string,
queryFields: GraphQLFieldConfigMap<any, any>,
data: PreprocessingData<TSource, TContext, TArgs>,
logger: Logger
): Viewer<TSource, TContext, TArgs> {
const scheme: ProcessedSecurityScheme = data.security[protocolName];
// Resolve function:
const resolve = (root: any, args: any, context: any) => {
const security = {};
const saneProtocolName = Oas3Tools.sanitize(protocolName, Oas3Tools.CaseStyle.camelCase);
security[Oas3Tools.storeSaneName(saneProtocolName, protocolName, data.saneMap, logger)] = args;
/**
* Viewers are always root, so we can instantiate _openAPIToGraphQL here without
* previously checking for its existence
*/
return {
_openAPIToGraphQL: {
security,
},
};
};
// Arguments:
/**
* Do not sort because they are already "sorted" in preprocessing.
* Otherwise, for basic auth, "password" will appear before "username"
*/
const args = {};
if (typeof scheme === 'object') {
for (const parameterName in scheme.parameters) {
args[parameterName] = { type: new GraphQLNonNull(GraphQLString) };
}
}
let typeDescription = `A viewer for security scheme '${protocolName}'`;
/**
* HTTP authentication uses different schemes. It is not sufficient to name
* only the security type
*/
let description =
securityType === 'http'
? `A viewer that wraps all operations authenticated via security scheme ` +
`'${protocolName}', which is of type 'http' '${scheme.def.scheme}'`
: `A viewer that wraps all operations authenticated via security scheme ` +
`'${protocolName}', which is of type '${securityType}'`;
if (data.oass.length !== 1) {
typeDescription += ` in OAS '${scheme.oas.info?.title}'`;
description = `, in OAS '${scheme.oas.info?.title}`;
}
return {
type: new GraphQLObjectType({
name: Oas3Tools.capitalize(name), // Should already be sanitized and in camelCase
description: typeDescription,
fields: () => queryFields,
}),
resolve,
args,
description,
};
}
Example #18
Source File: getArgs.test.ts From amplify-codegen with Apache License 2.0 | 5 votes |
describe('getArgs', () => {
const id: GraphQLArgument = {
name: 'id',
type: GraphQLID,
defaultValue: '1',
};
const query: GraphQLArgument = {
name: 'query',
type: GraphQLString,
};
const blogArticle = new GraphQLObjectType({
name: 'BlogArticle',
fields: {
id: { type: GraphQLID },
content: { type: GraphQLString },
},
});
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
searchArticle: {
args: { id, query },
type: blogArticle,
},
},
}),
});
beforeEach(() => {
jest.resetAllMocks();
isRequired.mockReturnValue(false);
getType.mockReturnValue({ name: 'mockType' });
isRequiredList.mockReturnValue(false);
isList.mockReturnValue(false);
});
it('should return arguments', () => {
isList.mockReturnValueOnce(true);
const query = schema.getQueryType().getFields().searchArticle;
expect(getArgs(query.args)).toEqual([
{
name: 'id',
type: 'mockType',
defaultValue: '1',
isRequired: false,
isList: true,
isListRequired: false,
},
{
name: 'query',
type: 'mockType',
defaultValue: undefined,
isRequired: false,
isList: false,
isListRequired: false,
},
]);
expect(getType).toHaveBeenCalledTimes(2);
expect(getType.mock.calls[0][0]).toEqual(GraphQLID);
expect(getType.mock.calls[1][0]).toEqual(GraphQLString);
expect(isRequired).toHaveBeenCalledTimes(2);
expect(isRequired.mock.calls[0][0]).toEqual(query.args[0].type);
expect(isRequired.mock.calls[1][0]).toEqual(query.args[1].type);
expect(isList).toHaveBeenCalledTimes(2);
expect(isRequiredList).toHaveBeenCalledTimes(2);
});
});
Example #19
Source File: FetcherWriter.d.ts From graphql-ts-client with MIT License | 5 votes |
protected importedNamesForSuperType(superType: GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType): string[];
Example #20
Source File: simple.ts From graphql-sse with MIT License | 5 votes |
schemaConfig: GraphQLSchemaConfig = {
query: new GraphQLObjectType({
name: 'Query',
fields: {
getValue: {
type: new GraphQLNonNull(GraphQLString),
resolve: () => 'value',
},
},
}),
subscription: new GraphQLObjectType({
name: 'Subscription',
fields: {
greetings: {
type: new GraphQLNonNull(GraphQLString),
subscribe: async function* () {
for (const hi of ['Hi', 'Bonjour', 'Hola', 'Ciao', 'Zdravo']) {
yield { greetings: hi };
}
},
},
ping: {
type: new GraphQLNonNull(GraphQLString),
args: {
key: {
type: GraphQLString,
},
},
subscribe: function (_src, args) {
const key = args.key ? args.key : 'global';
return {
[Symbol.asyncIterator]() {
return this;
},
async next() {
if ((pendingPongs[key] ?? 0) > 0) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
pendingPongs[key]!--;
return { value: { ping: 'pong' } };
}
if (
await new Promise((resolve) => (pongListeners[key] = resolve))
)
return { done: true };
return { value: { ping: 'pong' } };
},
async return() {
pongListeners[key]?.(true);
delete pongListeners[key];
return { done: true };
},
async throw() {
throw new Error('Ping no gusta');
},
};
},
},
},
}),
}