graphql#GraphQLArgument TypeScript Examples
The following examples show how to use
graphql#GraphQLArgument.
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: getArgs.ts From amplify-codegen with Apache License 2.0 | 6 votes |
export default function getArgs(args: GraphQLArgument[]): Array<GQLTemplateArgDeclaration> {
const argMaps = args.map((arg: GraphQLArgument) => ({
name: arg.name,
type: getType(arg.type).name,
isRequired: isRequired(arg.type),
isList: isList(arg.type),
isListRequired: isRequiredList(arg.type),
defaultValue: arg.defaultValue,
}));
return argMaps;
}
Example #2
Source File: selectors.ts From tql with MIT License | 6 votes |
printArgument = (arg: GraphQLArgument): string => {
const type = inputType(arg.type);
const typename =
type instanceof GraphQLScalarType
? toPrimitive(type)
: type instanceof GraphQLEnumType
? type.toString()
: "I" + type.toString();
return `Argument<"${arg.name}", V['${arg.name}']>`;
}
Example #3
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 #4
Source File: getBody.test.ts From amplify-codegen with Apache License 2.0 | 5 votes |
describe('getBody', () => {
const arg: GraphQLArgument = {
name: 'id',
type: GraphQLID,
};
const blogArticle = new GraphQLObjectType({
name: 'BlogArticle',
fields: {
id: { type: GraphQLID },
content: { type: GraphQLString },
},
});
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
article: {
args: { id: { type: GraphQLID } },
type: blogArticle,
},
},
}),
});
const mockFields = {
filed1: 'field1',
field2: 'field2',
};
beforeEach(() => {
getFields.mockReturnValue(mockFields);
});
it('should return a list of arguments', () => {
const query = schema.getQueryType().getFields().article;
expect(getBody(query, schema, maxDepth, { useExternalFragmentForS3Object: true })).toEqual({
args: [{ name: 'id', value: '$id' }],
...mockFields,
});
expect(getFields).toHaveBeenCalledWith(query, schema, maxDepth, { useExternalFragmentForS3Object: true });
});
});
Example #5
Source File: FetcherWriter.d.ts From graphql-ts-client with MIT License | 5 votes |
protected fieldArgsMap: Map<string, GraphQLArgument[]>;
Example #6
Source File: FetcherWriter.ts From graphql-ts-client with MIT License | 5 votes |
protected fieldArgsMap: Map<string, GraphQLArgument[]>;
Example #7
Source File: comment.ts From genql with MIT License | 5 votes |
argumentComment = (arg: GraphQLArgument | GraphQLInputField) =>
comment({
text: arg.description,
})
Example #8
Source File: objectType.ts From genql with MIT License | 5 votes |
objectType = (
type: GraphQLObjectType | GraphQLInterfaceType | GraphQLInputObjectType,
ctx: RenderContext,
) => {
const typeObj: FieldMap<string> = Object.keys(type.getFields()).reduce<
FieldMap<string>
>((r, f) => {
const field = type.getFields()[f]
const namedType = getNamedType(field.type)
const fieldObj: Field<string> = { type: namedType.name }
r[f] = fieldObj
const args: GraphQLArgument[] =
(<GraphQLField<any, any>>field).args || []
if (args.length > 0) {
fieldObj.args = args.reduce<ArgMap<string>>((r, a) => {
const concreteType = a.type.toString()
const typename = getNamedType(a.type).name
r[a.name] = [typename]
if (typename !== concreteType) {
r[a.name]?.push(concreteType)
}
return r
}, {})
}
return r
}, {})
if (isInterfaceType(type) && ctx.schema) {
ctx.schema.getPossibleTypes(type).map((t) => {
if (!isEmpty(typeObj)) {
typeObj[`on_${t.name}`] = { type: t.name }
}
})
}
if (!isEmpty(typeObj)) {
typeObj.__typename = { type: 'String' }
}
// const scalar = Object.keys(type.getFields())
// .map(f => type.getFields()[f])
// .filter(f => isScalarType(getNamedType(f.type)) || isEnumType(getNamedType(f.type)))
// .map(f => f.name)
// if (scalar.length > 0) typeObj.scalar = scalar
return typeObj
}
Example #9
Source File: selectors.ts From tql with MIT License | 5 votes |
printVariable = (arg: GraphQLArgument): string => {
return `${arg.name}${
arg.type instanceof GraphQLNonNull ? "" : "?"
}: Variable<string> | ${printInputType(arg.type)}`;
}
Example #10
Source File: selectors.ts From tql with MIT License | 5 votes |
printMethod = (field: GraphQLField<any, any, any>): string => {
const { name, args } = field;
const type = outputType(field.type);
const comments = [
field.description && `@description ${field.description}`,
field.deprecationReason && `@deprecated ${field.deprecationReason}`,
].filter(Boolean);
const jsDocComment =
comments.length > 0
? `
/**
${comments.map((comment) => "* " + comment).join("\n")}
*/
`
: "";
if (type instanceof GraphQLScalarType || type instanceof GraphQLEnumType) {
// @todo render arguments correctly
return args.length > 0
? jsDocComment.concat(
`${name}: (variables) => field("${name}", Object.entries(variables).map(([k, v]) => argument(k, v)) as any),`
)
: jsDocComment.concat(`${name}: () => field("${name}"),`);
} else {
const renderArgument = (arg: GraphQLArgument): string => {
return `argument("${arg.name}", variables.${arg.name})`;
};
// @todo restrict allowed Field types
return args.length > 0
? `
${jsDocComment}
${name}:(
variables,
select,
) => field("${name}", Object.entries(variables).map(([k, v]) => argument(k, v)) as any, selectionSet(select(${type.toString()}Selector))),
`
: `
${jsDocComment}
${name}: (
select,
) => field("${name}", undefined as never, selectionSet(select(${type.toString()}Selector))),
`;
}
}
Example #11
Source File: types.ts From tql with MIT License | 5 votes |
printVariable = (arg: GraphQLArgument): string => {
return `${arg.name}: ${printInputType(arg.type)} ${
arg.type instanceof GraphQLNonNull ? "" : "| undefined"
}`;
}
Example #12
Source File: index.ts From graphql-mesh with MIT License | 4 votes |
async getMeshSource(): Promise<MeshSource> {
const {
addLimitArgument,
baseUrl,
customFetch,
genericPayloadArgName,
operationHeaders,
qs,
selectQueryOrMutationField,
} = this.config;
let fetch: WindowOrWorkerGlobalScope['fetch'];
if (customFetch) {
fetch = await loadFromModuleExportExpression(customFetch, {
defaultExportName: 'default',
cwd: this.baseDir,
importFn: this.importFn,
});
} else {
fetch = getCachedFetch(this.cache);
}
const spec = await this.getCachedSpec(fetch);
const headersFactory = getInterpolatedHeadersFactory(operationHeaders);
const queryStringFactoryMap = new Map<string, ResolverDataBasedFactory<string>>();
for (const queryName in qs || {}) {
queryStringFactoryMap.set(queryName, getInterpolatedStringFactory(qs[queryName]));
}
const searchParamsFactory = (resolverData: ResolverData, searchParams: URLSearchParams) => {
for (const queryName in qs || {}) {
searchParams.set(queryName, queryStringFactoryMap.get(queryName)(resolverData));
}
return searchParams;
};
const { schema } = await createGraphQLSchema(spec, {
fetch,
baseUrl,
operationIdFieldNames: this.config.operationIdFieldNames,
fillEmptyResponses: true,
includeHttpDetails: this.config.includeHttpDetails,
provideErrorExtensions: this.config.provideErrorExtensions,
genericPayloadArgName: genericPayloadArgName === undefined ? false : genericPayloadArgName,
selectQueryOrMutationField:
selectQueryOrMutationField === undefined
? {}
: selectQueryOrMutationField.reduce((acc, curr) => {
let operationType: GraphQLOperationType;
switch (curr.type) {
case 'Query':
operationType = GraphQLOperationType.Query;
break;
case 'Mutation':
operationType = GraphQLOperationType.Mutation;
break;
}
return {
...acc,
[curr.title]: {
...acc[curr.title],
[curr.path]: {
...((acc[curr.title] && acc[curr.title][curr.path]) || {}),
[curr.method]: operationType,
},
},
};
}, {} as OasTitlePathMethodObject<GraphQLOperationType>),
addLimitArgument: addLimitArgument === undefined ? true : addLimitArgument,
sendOAuthTokenInQuery: true,
viewer: false,
equivalentToMessages: true,
pubsub: this.pubsub,
logger: this.logger,
resolverMiddleware: (getResolverParams, originalFactory) => (root, args, context, info: any) => {
const resolverData: ResolverData = { root, args, context, info, env: process.env };
const resolverParams = getResolverParams();
resolverParams.requestOptions = {
headers: headersFactory(resolverData),
};
resolverParams.qs = qs;
/* FIXME: baseUrl is coming from Fastify Request
if (context?.baseUrl) {
resolverParams.baseUrl = context.baseUrl;
}
*/
if (baseUrl) {
resolverParams.baseUrl = stringInterpolator.parse(baseUrl, resolverData);
}
if (resolverParams.baseUrl) {
const urlObj = new URL(resolverParams.baseUrl);
searchParamsFactory(resolverData, urlObj.searchParams);
} else {
this.logger.debug(
() =>
`Warning: There is no 'baseUrl' defined for this OpenAPI definition. We recommend you to define one manually!`
);
}
if (context?.fetch) {
resolverParams.fetch = context.fetch;
}
if (context?.qs) {
resolverParams.qs = context.qs;
}
return originalFactory(() => resolverParams, this.logger)(root, args, context, info);
},
});
const { args, contextVariables } = parseInterpolationStrings(Object.values(operationHeaders || {}));
const rootFields = [
...Object.values(schema.getQueryType()?.getFields() || {}),
...Object.values(schema.getMutationType()?.getFields() || {}),
...Object.values(schema.getSubscriptionType()?.getFields() || {}),
];
await Promise.all(
rootFields.map(rootField =>
Promise.all(
Object.entries(args).map(async ([argName, { type }]) =>
(rootField?.args as GraphQLArgument[]).push({
name: argName,
description: undefined,
defaultValue: undefined,
extensions: undefined,
astNode: undefined,
deprecationReason: undefined,
type: (typeof type === 'string' ? (schema.getType(type) as GraphQLInputType) : type) || GraphQLID,
})
)
)
)
);
contextVariables.push('fetch' /*, 'baseUrl' */);
return {
schema,
contextVariables,
};
}
Example #13
Source File: FetcherWriter.ts From graphql-ts-client with MIT License | 4 votes |
constructor(
protected modelType: GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType,
protected ctx: FetcherContext,
stream: WriteStream,
config: GeneratorConfig
) {
super(stream, config);
this.fetcherTypeName = `${this.modelType.name}${config.fetcherSuffix ?? "Fetcher"}`;
if (modelType instanceof GraphQLUnionType) {
const map: { [key: string]: GraphQLField<any, any> } = {};
const itemCount = modelType.getTypes().length;
if (itemCount !== 0) {
const fieldCountMap = new Map<string, number>();
for (const type of modelType.getTypes()) {
for (const fieldName in type.getFields()) {
fieldCountMap.set(fieldName, (fieldCountMap.get(fieldName) ?? 0) + 1);
}
}
const firstTypeFieldMap = modelType.getTypes()[0].getFields();
for (const fieldName in firstTypeFieldMap) {
if (fieldCountMap.get(fieldName) === itemCount) {
map[fieldName] = firstTypeFieldMap[fieldName]!;
}
}
}
this.fieldMap = map;
} else {
this.fieldMap = modelType.getFields();
}
const fieldArgsMap = new Map<string, GraphQLArgument[]>();
const fieldCategoryMap = new Map<string, string>();
const defaultFetcherProps: string[] = [];
this.hasArgs = false;
for (const fieldName in this.fieldMap) {
const field = this.fieldMap[fieldName]!;
const targetType = targetTypeOf(field.type);
if (this.modelType.name !== "Query" &&
this.modelType.name !== "Mutation" &&
targetType === undefined &&
field.args.length === 0 &&
!field.isDeprecated) {
if (config.defaultFetcherExcludeMap !== undefined) {
const excludeProps = config.defaultFetcherExcludeMap[modelType.name];
if (excludeProps !== undefined && excludeProps.filter(name => name === fieldName).length !== 0) {
continue;
}
}
defaultFetcherProps.push(fieldName);
}
if (field.args.length !== 0) {
fieldArgsMap.set(fieldName, field.args);
}
const fieldCoreType =
field.type instanceof GraphQLNonNull ?
field.type.ofType :
field.type;
if (this.ctx.embeddedTypes.has(fieldCoreType)) {
fieldCategoryMap.set(fieldName, "SCALAR");
} else if (this.ctx.connections.has(fieldCoreType)) {
fieldCategoryMap.set(fieldName, "CONNECTION");
} else if (fieldCoreType instanceof GraphQLList) {
const elementType =
fieldCoreType.ofType instanceof GraphQLNonNull ?
fieldCoreType.ofType.ofType :
fieldCoreType.ofType;
if (elementType instanceof GraphQLObjectType ||
elementType instanceof GraphQLInterfaceType ||
elementType instanceof GraphQLUnionType
) {
fieldCategoryMap.set(fieldName, "LIST");
}
} else if (fieldCoreType instanceof GraphQLObjectType ||
fieldCoreType instanceof GraphQLInterfaceType ||
fieldCoreType instanceof GraphQLUnionType
) {
fieldCategoryMap.set(fieldName, "REFERENCE");
} else if (this.ctx.idFieldMap.get(this.modelType) === field) {
fieldCategoryMap.set(fieldName, "ID");
} else {
fieldCategoryMap.set(fieldName, "SCALAR");
}
if (field.args.length !== 0) {
this.hasArgs = true;
}
}
this.defaultFetcherProps = defaultFetcherProps;
this.fieldArgsMap = fieldArgsMap;
this.fieldCategoryMap = fieldCategoryMap;
let prefix = instancePrefix(this.modelType.name);
this.emptyFetcherName = `${prefix}$`;
this.defaultFetcherName = defaultFetcherProps.length !== 0 ? `${prefix}$$` : undefined;
}