graphql#print TypeScript Examples
The following examples show how to use
graphql#print.
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: generate-query.test.ts From graphql-query-generator with MIT License | 6 votes |
test(`Obtain random query from GitHub schema`, () => {
const config: Configuration = {
breadthProbability: 0.5,
depthProbability: 0.5,
maxDepth: 10,
ignoreOptionalArguments: true,
argumentsToConsider: ['first'],
considerInterfaces: true,
considerUnions: true,
seed: 3,
providePlaceholders: true
}
const { queryDocument, variableValues } = generateRandomQuery(
schemaGitHub,
config
)
const opDef = getOperationDefinition(queryDocument)
const errors = validate(schemaGitHub, queryDocument)
expect(queryDocument).toBeDefined()
expect(print(queryDocument).replace(/\s/g, '')).toEqual(
`query RandomQuery($Query__codeOfConduct__key: String!) {
codeOfConduct(key: $Query__codeOfConduct__key) {
name
url
}
}`.replace(/\s/g, '')
)
expect(Object.keys(opDef.variableDefinitions).length).toEqual(
Object.keys(variableValues).length
)
expect(errors).toEqual([])
})
Example #2
Source File: index.ts From amplify-codegen with Apache License 2.0 | 6 votes |
compileFragment(fragmentDefinition: FragmentDefinitionNode): Fragment {
const fragmentName = fragmentDefinition.name.value;
const filePath = filePathForNode(fragmentDefinition);
const source = print(fragmentDefinition);
const type = typeFromAST(this.schema, fragmentDefinition.typeCondition) as GraphQLCompositeType;
return {
fragmentName,
filePath,
source,
type,
selectionSet: this.compileSelectionSet(fragmentDefinition.selectionSet, type),
};
}
Example #3
Source File: consider-listsize-directive.test.ts From graphql-query-generator with MIT License | 6 votes |
test(`Multiple (single level) slicing arguments`, () => {
const schema = buildSchema(`
directive @listSize(requireOneSlicingArgument: Boolean = true, assumedSize: Int, slicingArguments: [String], sizedFields: [String]) on FIELD_DEFINITION
type Order {
id: ID
date: String
}
type Query {
orders(first: Int, after: ID, last: Int, before: ID): [Order] @listSize(slicingArguments: ["first", "last"])
}
`)
const config = {
providePlaceholders: true,
seed: 1
}
const { queryDocument, variableValues } = generateRandomQuery(schema, config)
const query = print(queryDocument)
expect(query.trim()).toEqual(
dedent(`
query RandomQuery($Query__orders__first: Int) {
orders(first: $Query__orders__first) {
id
date
}
}
`).trim()
)
const variables = JSON.stringify(variableValues, null, 2)
expect(variables.trim()).toEqual(
dedent(`
{
"Query__orders__first": 10
}
`).trim()
)
expect(validate(schema, queryDocument)).toEqual([])
})
Example #4
Source File: consider-listsize-directive.test.ts From graphql-query-generator with MIT License | 6 votes |
test(`Multiple (single level) slicing arguments with requireOneSlicinArgument set to false`, () => {
const schema = buildSchema(`
directive @listSize(requireOneSlicingArgument: Boolean = true, assumedSize: Int, slicingArguments: [String], sizedFields: [String]) on FIELD_DEFINITION
type Order {
id: ID
date: String
}
type Query {
orders(first: Int, after: ID, last: Int, before: ID): [Order] @listSize(requireOneSlicingArgument: false, slicingArguments: ["first", "last"])
}
`)
const config = {
providePlaceholders: true,
seed: 1
}
const { queryDocument, variableValues } = generateRandomQuery(schema, config)
const query = print(queryDocument)
expect(query.trim()).toEqual(
dedent(`
query RandomQuery {
orders {
id
date
}
}
`).trim()
)
const variables = JSON.stringify(variableValues, null, 2)
expect(variables.trim()).toEqual(
dedent(`
{}
`).trim()
)
expect(validate(schema, queryDocument)).toEqual([])
})
Example #5
Source File: consider-listsize-directive.test.ts From graphql-query-generator with MIT License | 6 votes |
test(`@listSize with only assumedSize`, () => {
const schema = buildSchema(`
directive @listSize(requireOneSlicingArgument: Boolean = true, assumedSize: Int, slicingArguments: [String], sizedFields: [String]) on FIELD_DEFINITION
type Order {
id: ID
date: String
}
type Query {
orders(first: Int, after: ID, last: Int, before: ID): [Order] @listSize(assumedSize: 10)
}
`)
const config = {
providePlaceholders: true,
seed: 1
}
const { queryDocument, variableValues } = generateRandomQuery(schema, config)
const query = print(queryDocument)
expect(query.trim()).toEqual(
dedent(`
query RandomQuery {
orders {
id
date
}
}
`).trim()
)
const variables = JSON.stringify(variableValues, null, 2)
expect(variables.trim()).toEqual(
dedent(`
{}
`).trim()
)
expect(validate(schema, queryDocument)).toEqual([])
})
Example #6
Source File: consider-listsize-directive.test.ts From graphql-query-generator with MIT License | 6 votes |
test(`@listSize with assumedSize and required argument`, () => {
const schema = buildSchema(`
directive @listSize(requireOneSlicingArgument: Boolean = true, assumedSize: Int, slicingArguments: [String], sizedFields: [String]) on FIELD_DEFINITION
type Order {
id: ID
date: String
}
type Query {
orders(first: Int!, after: ID, last: Int, before: ID): [Order] @listSize(assumedSize: 10)
}
`)
const config = {
providePlaceholders: true,
seed: 1
}
const { queryDocument, variableValues } = generateRandomQuery(schema, config)
const query = print(queryDocument)
expect(query.trim()).toEqual(
dedent(`
query RandomQuery($Query__orders__first: Int!) {
orders(first: $Query__orders__first) {
id
date
}
}
`).trim()
)
const variables = JSON.stringify(variableValues, null, 2)
expect(variables.trim()).toEqual(
dedent(`
{
"Query__orders__first": 10
}
`).trim()
)
expect(validate(schema, queryDocument)).toEqual([])
})
Example #7
Source File: generate-query.test.ts From graphql-query-generator with MIT License | 6 votes |
test(`Obtain random query from example schema`, () => {
const config: Configuration = {
breadthProbability: 0.1,
depthProbability: 0.1,
providePlaceholders: true
}
const { queryDocument, variableValues } = generateRandomQuery(schema, config)
expect(queryDocument).toBeDefined()
expect(print(queryDocument) === '').toEqual(false)
const opDef = getOperationDefinition(queryDocument)
expect(Object.keys(opDef.variableDefinitions).length).toEqual(
Object.keys(variableValues).length
)
const errors = validate(schema, queryDocument)
expect(errors).toEqual([])
})
Example #8
Source File: generate-query.test.ts From graphql-query-generator with MIT License | 6 votes |
test(`Obtain complete query from example schema`, () => {
const config: Configuration = {
breadthProbability: 1,
depthProbability: 1,
maxDepth: 2,
providePlaceholders: true
}
const { queryDocument, variableValues } = generateRandomQuery(schema, config)
const opDef = getOperationDefinition(queryDocument)
const errors = validate(schema, queryDocument)
expect(queryDocument).toBeDefined()
expect(print(queryDocument) === '').toEqual(false)
expect(Object.keys(opDef.variableDefinitions).length).toEqual(
Object.keys(variableValues).length
)
expect(errors).toEqual([])
})
Example #9
Source File: generate-query.test.ts From graphql-query-generator with MIT License | 6 votes |
test(`Avoid picking field with only nested subfields when approaching max depth`, () => {
const config: Configuration = {
breadthProbability: 1,
depthProbability: 1,
maxDepth: 3,
considerInterfaces: true,
considerUnions: true,
providePlaceholders: true
}
const { queryDocument, variableValues } = generateRandomQuery(schema, config)
const opDef = getOperationDefinition(queryDocument)
const errors = validate(schema, queryDocument)
expect(queryDocument).toBeDefined()
expect(print(queryDocument) === '').toEqual(false)
expect(Object.keys(opDef.variableDefinitions).length).toEqual(
Object.keys(variableValues).length
)
expect(errors).toEqual([])
})
Example #10
Source File: index.ts From fullstack-starterkit with MIT License | 6 votes |
private async graphqlRequest({ query, variables, context, operationName }: GraphQLRequest): Promise<any> {
const queryNode: DocumentNode = allQueries[operationName];
const queryNodeString: string = print(queryNode);
const source: string = query || queryNodeString;
const contextValue = (context = context ? { ...this.context, ...context } : this.context);
const { data, errors } = await graphql({ schema, source, variableValues: variables, contextValue });
if (errors && errors.length) {
throw errors[0];
}
if (!data) {
throw new Error(`Invalid query ${operationName}.`);
}
return data[operationName];
}
Example #11
Source File: generate-query.test.ts From graphql-query-generator with MIT License | 6 votes |
test(`Seeded query generation is deterministic`, () => {
const config: Configuration = {
breadthProbability: 0.5,
depthProbability: 0.5,
maxDepth: 10,
ignoreOptionalArguments: true,
argumentsToConsider: ['first'],
considerInterfaces: true,
considerUnions: true,
seed: 3,
providePlaceholders: true
}
const { queryDocument, variableValues } = generateRandomQuery(
schemaGitHub,
config
)
const opDef = getOperationDefinition(queryDocument)
const errors = validate(schemaGitHub, queryDocument)
expect(queryDocument).toBeDefined()
expect(print(queryDocument).replace(/\s/g, '')).toEqual(
`query RandomQuery($Query__codeOfConduct__key: String!) {
codeOfConduct(key: $Query__codeOfConduct__key) {
name
url
}
}`.replace(/\s/g, '')
)
expect(Object.keys(opDef.variableDefinitions).length).toEqual(
Object.keys(variableValues).length
)
expect(errors).toEqual([])
})
Example #12
Source File: generate-query.test.ts From graphql-query-generator with MIT License | 6 votes |
test(`Null providers are allowed`, () => {
const config: Configuration = {
breadthProbability: 0.5,
depthProbability: 0.5,
maxDepth: 10,
ignoreOptionalArguments: true,
argumentsToConsider: ['first'],
considerInterfaces: true,
considerUnions: true,
seed: 3,
providerMap: { '*__*__*': null }
}
const { queryDocument, variableValues } = generateRandomQuery(
schemaGitHub,
config
)
const opDef = getOperationDefinition(queryDocument)
const errors = validate(schemaGitHub, queryDocument)
expect(queryDocument).toBeDefined()
expect(print(queryDocument).replace(/\s/g, '')).toEqual(
`query RandomQuery($Query__codeOfConduct__key: String!) {
codeOfConduct(key: $Query__codeOfConduct__key) {
name
url
}
}`.replace(/\s/g, '')
)
expect(Object.keys(opDef.variableDefinitions).length).toEqual(
Object.keys(variableValues).length
)
expect(errors).toEqual([])
})
Example #13
Source File: generate-query.test.ts From graphql-query-generator with MIT License | 6 votes |
test(`Provide custom provider map for GitHub schema`, () => {
const config: Configuration = {
breadthProbability: 0.2,
depthProbability: 0.3,
maxDepth: 7,
ignoreOptionalArguments: true,
argumentsToConsider: ['first'],
providerMap: GITHUB_PROVIDERS,
considerInterfaces: true,
considerUnions: true
}
const { queryDocument, variableValues } = generateRandomQuery(
schemaGitHub,
config
)
const opDef = getOperationDefinition(queryDocument)
const errors = validate(schemaGitHub, queryDocument)
expect(queryDocument).toBeDefined()
expect(print(queryDocument) === '').toEqual(false)
expect(Object.keys(opDef.variableDefinitions).length).toEqual(
Object.keys(variableValues).length
)
expect(errors).toEqual([])
})
Example #14
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 #15
Source File: generate-query.test.ts From graphql-query-generator with MIT License | 6 votes |
test(`Provided variables are passed to providers`, () => {
const config: Configuration = {
breadthProbability: 1,
depthProbability: 1,
providerMap: {
'*__*__name': (providedVars) => {
if (typeof providedVars['Query__repository__owner'] === 'string') {
return 'Two'
}
return 'One'
},
'*__*__owner': (providedVars) => {
if (typeof providedVars['Query__repository__name'] === 'string') {
return 'Two'
}
return 'One'
}
}
}
const { queryDocument, variableValues } = generateRandomQuery(
schemaSimple,
config
)
const errors = validate(schemaSimple, queryDocument)
expect(queryDocument).toBeDefined()
expect(print(queryDocument).replace(/\s/g, '')).toEqual(
`query RandomQuery($Query__repository__name: String!, $Query__repository__owner: String!) {
name
repository(name: $Query__repository__name, owner: $Query__repository__owner)
}`.replace(/\s/g, '')
)
expect(errors).toEqual([])
expect(
variableValues['Query__repository__name'] !=
variableValues['Query__repository__owner']
).toBeTruthy()
})
Example #16
Source File: parseAndPrintWithCache.ts From graphql-mesh with MIT License | 6 votes |
printWithCache = memoize1(function printWithCache(document: DocumentNode): string {
const stringifedDocumentJson = JSON.stringify(document);
let sdl: string = printCache.get(stringifedDocumentJson);
if (!sdl) {
sdl = print(document).trim();
printCache.set(stringifedDocumentJson, sdl);
parseCache.set(sdl, document);
}
return sdl;
})
Example #17
Source File: get-mesh.ts From graphql-mesh with MIT License | 6 votes |
function normalizeSelectionSetParam(selectionSetParam: SelectionSetParam) {
if (typeof selectionSetParam === 'string') {
return parseSelectionSet(selectionSetParam);
}
if (isDocumentNode(selectionSetParam)) {
return parseSelectionSet(print(selectionSetParam));
}
return selectionSetParam;
}
Example #18
Source File: generate-operations.ts From graphql-mesh with MIT License | 6 votes |
export function generateOperations(schema: GraphQLSchema, options: YamlConfig.GenerateOperationsConfig): Source[] {
const sources: Source[] = [];
const rootTypeMap = getRootTypeMap(schema);
for (const [operationType, rootType] of rootTypeMap) {
const fieldMap = rootType.getFields();
for (const fieldName in fieldMap) {
const operationNode = buildOperationNodeForField({
schema,
kind: operationType,
field: fieldName,
depthLimit: options.selectionSetDepth,
});
const defaultName = `operation_${sources.length}`;
const virtualFileName = operationNode.name?.value || defaultName;
const rawSDL = print(operationNode);
const source = parseGraphQLSDL(`${virtualFileName}.graphql`, rawSDL);
sources.push(source);
}
}
return sources;
}
Example #19
Source File: consider-listsize-directive.test.ts From graphql-query-generator with MIT License | 6 votes |
test(`Ignore arguments when no @listSize is used`, () => {
const schema = buildSchema(`
directive @listSize(requireOneSlicingArgument: Boolean = true, assumedSize: Int, slicingArguments: [String], sizedFields: [String]) on FIELD_DEFINITION
type Order {
id: ID
date: String
}
type Query {
orders(first: Int, after: ID, last: Int, before: ID): [Order]
}
`)
const { queryDocument } = generateRandomQuery(schema, { seed: 1 })
const query = print(queryDocument)
expect(query.trim()).toEqual(
dedent(`
query RandomQuery {
orders {
id
date
}
}
`).trim()
)
expect(validate(schema, queryDocument)).toEqual([])
})
Example #20
Source File: remote-schema.ts From one-platform with MIT License | 6 votes |
function getExecutor ( uri: string, serviceName: string ) {
return async ( { document, variables, context }: any ) => {
console.log( new Date().toISOString(), '- forward via http to:', serviceName );
const query = print( document );
const fetchResult = await fetch( uri, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-OP-User-ID': context?.uid,
'X-OP-User-Roles': context?.roles ?? [],
'X-OP-User-Scopes': context?.scopes ?? [],
'X-OP-Token': context?.token,
'From': 'OP-API-GATEWAY'
},
body: JSON.stringify( { query, variables } ),
} );
return fetchResult.json();
};
}
Example #21
Source File: graphql-client.ts From dt-mergebot with MIT License | 6 votes |
export function createMutation<T>(name: keyof schema.Mutation, input: T, subquery?: string): MutationOptions<void, { input: T }> {
const mutation = {
toJSON: () => print(mutation),
...(gql`mutation($input: ${name[0]!.toUpperCase() + name.slice(1)}Input!) {
${name}(input: $input) {
__typename
${subquery || ""}
}
}` as TypedDocumentNode<void, { input: T }>),
};
return { mutation, variables: { input } };
}
Example #22
Source File: customWhitespaceMatcher.ts From ra-data-prisma with MIT License | 6 votes |
toEqualGraphql = (
received: ASTNode | ASTNode[],
expected: string | string[],
) => {
const receivedArray = Array.isArray(received) ? received : [received];
const expectedArray = Array.isArray(expected) ? expected : [expected];
const expectedArrayCompressed = expectedArray.map(cleanString);
const receivedPrinted = receivedArray.map((node) => cleanString(print(node)));
const pass = receivedPrinted.every(
(s, index) => s === expectedArrayCompressed[index],
);
const message = pass
? () =>
`${matcherHint(`.not.${name}`)}\n\n` +
` ${printExpected(expectedArrayCompressed)}\n` +
`Received:\n` +
` ${printReceived(receivedPrinted)}`
: () => {
const diffString = diff(expectedArrayCompressed, receivedPrinted);
return (
`${matcherHint(`.${name}`)}\n\n` +
`Expected value to equal:\n` +
` ${printExpected(expectedArrayCompressed)}\n` +
`Received:\n` +
` ${printReceived(receivedPrinted)}${
diffString ? `\n\nDifference:\n\n${diffString}` : ``
}`
);
};
return {
actual: received,
expected,
message,
name,
pass,
};
}
Example #23
Source File: generate-corpus.ts From graphql-query-generator with MIT License | 6 votes |
async function getEntry(
token: string,
queryGenerator: GitHubQueryGenerator,
id: number,
fd: number
) {
try {
const {
queryDocument,
variableValues
} = queryGenerator.generateRandomGitHubQuery()
const query = print(queryDocument)
const request = { query, variables: variableValues }
await delay(1000)
const data = withResponse
? await runGitHubGraphQLQuery(JSON.stringify(request), token)
: null
const timestamp = Date.now()
const entry = {
id,
timestamp,
query,
variableValues,
response: { data }
}
console.log(`Generated query ${id + 1} out of ${ITERATIONS}`)
fs.write(
fd,
`${JSON.stringify(entry, null, 2)}${id < ITERATIONS - 1 ? ',' : ''}\n`,
(err) => {
if (err) console.log('Error writing file:', err)
}
)
} catch (error) {
console.log(`Error while generating query ${id}: ${error}`)
await getEntry(token, queryGenerator, id, fd)
}
}
Example #24
Source File: generate-github-query.test.ts From graphql-query-generator with MIT License | 6 votes |
test('Generate random GitHub query', () => {
return getGitHubQueryGenerator(gitHubAccessToken).then(
(gitHubQueryGenerator) => {
const query = gitHubQueryGenerator.generateRandomGitHubQuery()
const { queryDocument, variableValues } = query
console.log(print(queryDocument))
console.log(JSON.stringify(variableValues, null, 2))
expect(queryDocument).toBeTruthy()
}
)
})
Example #25
Source File: generate-corpus.ts From graphql-query-generator with MIT License | 6 votes |
async function getEntry(
token: string,
queryGenerator: YelpQueryGenerator,
id: number,
fd: number
) {
try {
const {
queryDocument,
variableValues
} = queryGenerator.generateRandomYelpQuery()
const query = print(queryDocument)
const request = { query, variables: variableValues }
await delay(1000)
const data = withResponse
? await runYelpGraphQLQuery('json', JSON.stringify(request), token)
: null
const timestamp = Date.now()
const entry = {
id,
timestamp,
query,
variableValues,
response: { data }
}
console.log(`Generated query ${id + 1} out of ${ITERATIONS}`)
fs.write(
fd,
`${JSON.stringify(entry, null, 2)}${id < ITERATIONS - 1 ? ',' : ''}\n`,
(err) => {
if (err) console.log('Error writing file:', err)
}
)
} catch (error) {
console.log(`Error while generating query ${id}: ${error}`)
await getEntry(token, queryGenerator, id, fd)
}
}
Example #26
Source File: generate-yelp-query.test.ts From graphql-query-generator with MIT License | 6 votes |
test('Generate random Yelp query', () => {
return getYelpQueryGenerator(yelpAccessToken).then((yelpQueryGenerator) => {
const query = yelpQueryGenerator.generateRandomYelpQuery()
const { queryDocument, variableValues } = query
console.log(print(queryDocument))
console.log(JSON.stringify(variableValues, null, 2))
expect(queryDocument).toBeTruthy()
})
}, 10000)
Example #27
Source File: index.test.ts From mercurius-typescript with MIT License | 6 votes |
test('gql helper', (t) => {
t.plan(2)
const a = gql`
query A {
hello
}
`
const b = gql`
query B {
hello
}
${a}
`
t.snapshot(print(parse(a)))
t.snapshot(print(parse(b)))
})
Example #28
Source File: consider-listsize-directive.test.ts From graphql-query-generator with MIT License | 6 votes |
test(`Add "first" slicing argument when defined in @listSize`, () => {
const schema = buildSchema(`
directive @listSize(requireOneSlicingArgument: Boolean = true, assumedSize: Int, slicingArguments: [String], sizedFields: [String]) on FIELD_DEFINITION
type Order {
id: ID
date: String
}
type Query {
orders(first: Int, after: ID, last: Int, before: ID): [Order] @listSize(slicingArguments: ["first"])
}
`)
const config = {
providePlaceholders: true,
seed: 1
}
const { queryDocument, variableValues } = generateRandomQuery(schema, config)
const query = print(queryDocument)
expect(query.trim()).toEqual(
dedent(`
query RandomQuery($Query__orders__first: Int) {
orders(first: $Query__orders__first) {
id
date
}
}
`).trim()
)
const variables = JSON.stringify(variableValues, null, 2)
expect(variables.trim()).toEqual(
dedent(`
{
"Query__orders__first": 10
}
`).trim()
)
expect(validate(schema, queryDocument)).toEqual([])
})
Example #29
Source File: consider-listsize-directive.test.ts From graphql-query-generator with MIT License | 6 votes |
test(`Add "last" slicing argument when defined in @listSize`, () => {
const schema = buildSchema(`
directive @listSize(requireOneSlicingArgument: Boolean = true, assumedSize: Int, slicingArguments: [String], sizedFields: [String]) on FIELD_DEFINITION
type Order {
id: ID
date: String
}
type Query {
orders(first: Int, after: ID, last: Int, before: ID): [Order] @listSize(slicingArguments: ["last"])
}
`)
const { queryDocument } = generateRandomQuery(schema, { seed: 1 })
const query = print(queryDocument)
expect(query.trim()).toEqual(
dedent(`
query RandomQuery($Query__orders__last: Int) {
orders(last: $Query__orders__last) {
id
date
}
}
`).trim()
)
expect(validate(schema, queryDocument)).toEqual([])
})