graphql#validate TypeScript Examples

The following examples show how to use graphql#validate. 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: example_api.test.ts    From graphql-mesh with MIT License 6 votes vote down vote up
test('Option customResolver using resolver arguments that are sanitized', () => {
  const options: Options<any, any, any> = {
    customResolvers: {
      'Example API': {
        '/products/{product-id}': {
          get: (obj, args, context, info) => {
            return {
              // Note that the argument name is sanitized
              productName: 'abcdef',
            };
          },
        },
      },
    },
    fetch,
  };

  const query = `{
    productWithId (productId: "123" productTag: "blah") {
      productName
    }
  }`;

  return openAPIToGraphQL.createGraphQLSchema(oas, options).then(({ schema }) => {
    const ast = parse(query);
    const errors = validate(schema, ast);
    expect(errors).toEqual([]);
    return graphql({ schema, source: query }).then((result: any) => {
      expect(result).toEqual({
        data: {
          productWithId: {
            productName: 'abcdef',
          },
        },
      });
    });
  });
});
Example #2
Source File: generate-query.test.ts    From graphql-query-generator with MIT License 6 votes vote down vote up
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 #3
Source File: cloudfunction.test.ts    From graphql-mesh with MIT License 6 votes vote down vote up
test('Get response', async () => {
  const query = `mutation {
    mutationViewerBasicAuth (username: "test" password: "data") {
      postTestAction2 (payloadInput: {age: 27}) {
        payload
        age
      }
    }
  }`;
  // validate that 'limit' parameter is covered by options:
  const ast = parse(query);
  const errors = validate(createdSchema, ast);
  expect(errors).toEqual([]);
});
Example #4
Source File: consider-listsize-directive.test.ts    From graphql-query-generator with MIT License 6 votes vote down vote up
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 #5
Source File: example_api.test.ts    From graphql-mesh with MIT License 6 votes vote down vote up
test('Header arguments are not created when they are provided through headers option', () => {
  // The GET snack operation has a snack_type and snack_size header arguments
  const options: Options<any, any, any> = {
    headers: {
      snack_type: 'chips',
      snack_size: 'large',
    },
    fetch,
  };

  const query = `{
    __schema {
      queryType {
        fields {
          name
          args {
            name
          }
        }
      }
    }
  }`;

  return openAPIToGraphQL.createGraphQLSchema(oas, options).then(({ schema }) => {
    const ast = parse(query);
    const errors = validate(schema, ast);
    expect(errors).toEqual([]);
    return graphql({ schema, source: query }).then((result: any) => {
      expect(
        result.data.__schema.queryType.fields.find((field: { name: string }) => {
          return field.name === 'snack';
        })
      ).toEqual({
        name: 'snack',
        args: [], // No arguments
      });
    });
  });
});
Example #6
Source File: validation.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
export function validateQueryDocument(schema: GraphQLSchema, document: DocumentNode) {
  const specifiedRulesToBeRemoved = [NoUnusedFragmentsRule];

  const rules = [NoAnonymousQueries, NoTypenameAlias, ...specifiedRules.filter(rule => !specifiedRulesToBeRemoved.includes(rule))];

  const validationErrors = validate(schema, document, rules);
  if (validationErrors && validationErrors.length > 0) {
    for (const error of validationErrors) {
      logError(error);
    }
    throw new ToolError('Validation of GraphQL query document failed');
  }
}
Example #7
Source File: generate-query.test.ts    From graphql-query-generator with MIT License 6 votes vote down vote up
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 #8
Source File: example_api.test.ts    From graphql-mesh with MIT License 5 votes vote down vote up
test('Option selectQueryOrMutationField', () => {
  const query = `{
    __schema {
      queryType {
        fields {
          name
          description
        }
      }
      mutationType {
        fields {
          name
          description
        }
      }
    }
  }`;

  // The users field should exist as a Query field
  const promise = graphql({ schema: createdSchema, source: query }).then((result: any) => {
    expect(
      result.data.__schema.queryType.fields.find((field: { name: string }) => {
        return field.name === 'user';
      })
    ).toEqual({
      name: 'user',
      description: 'Returns a user from the system.\n\nEquivalent to GET /users/{username}',
    });

    expect(
      result.data.__schema.mutationType.fields.find((field: { name: string }) => {
        return field.name === 'user';
      })
    ).toEqual(undefined);
  });

  const options: Options<any, any, any> = {
    selectQueryOrMutationField: {
      'Example API': {
        '/users/{username}': {
          get: GraphQLOperationType.Mutation,
        },
      },
    },
    fetch,
  };

  // The users (now named getUserByUsername) field should exist as a Mutation field
  const promise2 = openAPIToGraphQL.createGraphQLSchema(oas, options).then(({ schema }) => {
    const ast = parse(query);
    const errors = validate(schema, ast);
    expect(errors).toEqual([]);
    return graphql({ schema, source: query }).then((result: any) => {
      expect(
        result.data.__schema.queryType.fields.find((field: { name: string }) => {
          return field.name === 'getUserByUsername';
        })
      ).toEqual(undefined);

      expect(
        result.data.__schema.mutationType.fields.find((field: { name: string }) => {
          return field.name === 'getUserByUsername';
        })
      ).toEqual({
        name: 'getUserByUsername',
        description: 'Returns a user from the system.\n\nEquivalent to GET /users/{username}',
      });
    });
  });

  return Promise.all([promise, promise2]);
});
Example #9
Source File: consider-listsize-directive.test.ts    From graphql-query-generator with MIT License 5 votes vote down vote up
test(`Add nested slicing argument ("args.first") when defined in @listSize`, () => {
  const schema = buildSchema(`
    directive @listSize(requireOneSlicingArgument: Boolean = true, assumedSize: Int, slicingArguments: [String], sizedFields: [String]) on FIELD_DEFINITION

    input Args {
      first: Int
      after: ID
      last: Int
      before: ID
    }

    type Order {
      id: ID
      date: String
    }

    type Query {
      orders(args: Args): [Order] @listSize(slicingArguments: ["args.first", "args.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__args: Args) {
        orders(args: $Query__orders__args) {
          id
          date
        }
      }
    `).trim()
  )
  const variables = JSON.stringify(variableValues, null, 2)
  expect(variables.trim()).toEqual(
    dedent(`
      {
        "Query__orders__args": {
          "first": 10
        }
      }
    `).trim()
  )
  expect(validate(schema, queryDocument)).toEqual([])
})
Example #10
Source File: example_api.test.ts    From graphql-mesh with MIT License 5 votes vote down vote up
test('Header arguments are not created when they are provided through requestOptions option', () => {
  // The GET snack operation has a snack_type and snack_size header arguments
  const options: Options<any, any, any> = {
    requestOptions: {
      headers: {
        snack_type: 'chips',
        snack_size: 'large',
      },
    },
    fetch,
  };

  const query = `{
    __schema {
      queryType {
        fields {
          name
          args {
            name
          }
        }
      }
    }
  }`;

  return openAPIToGraphQL.createGraphQLSchema(oas, options).then(({ schema }) => {
    const ast = parse(query);
    const errors = validate(schema, ast);
    expect(errors).toEqual([]);
    return graphql({ schema, source: query }).then((result: any) => {
      expect(
        result.data.__schema.queryType.fields.find((field: { name: string }) => {
          return field.name === 'snack';
        })
      ).toEqual({
        name: 'snack',
        args: [], // No arguments
      });
    });
  });
});
Example #11
Source File: consider-listsize-directive.test.ts    From graphql-query-generator with MIT License 5 votes vote down vote up
test(`Add nested required argument ("args.first")`, () => {
  const schema = buildSchema(`
    directive @listSize(requireOneSlicingArgument: Boolean = true, assumedSize: Int, slicingArguments: [String], sizedFields: [String]) on FIELD_DEFINITION

    input Args {
      first: Int!
      after: ID
    }

    type Order {
      id: ID
      date: String
    }

    type Query {
      orders(args: Args!): [Order]
    }
  `)
  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__args: Args!) {
        orders(args: $Query__orders__args) {
          id
          date
        }
      }
    `).trim()
  )
  const variables = JSON.stringify(variableValues, null, 2)
  expect(variables.trim()).toEqual(
    dedent(`
      {
        "Query__orders__args": {
          "first": 10
        }
      }
    `).trim()
  )
  expect(validate(schema, queryDocument)).toEqual([])
})
Example #12
Source File: example_api.test.ts    From graphql-mesh with MIT License 5 votes vote down vote up
test('Option idFormats', () => {
  const options: Options<any, any, any> = {
    idFormats: ['specialIdFormat'],
    fetch,
  };

  // Check query/mutation field descriptions
  const query = `{
    __type(name: "PatentWithId") {
      fields {
        name
        type {
          kind
          ofType {
            name
            kind
          }
        }
      }
    }
  }`;

  return openAPIToGraphQL.createGraphQLSchema(oas, options).then(({ schema }) => {
    const ast = parse(query);
    const errors = validate(schema, ast);
    expect(errors).toEqual([]);
    return graphql({ schema, source: query }).then((result: any) => {
      expect(
        result.data.__type.fields.find((field: { name: string }) => {
          return field.name === 'patentId';
        })
      ).toEqual({
        name: 'patentId',
        type: {
          kind: 'NON_NULL',
          ofType: {
            name: 'ID',
            kind: 'SCALAR',
          },
        },
      });
    });
  });
});
Example #13
Source File: generate-query.test.ts    From graphql-query-generator with MIT License 5 votes vote down vote up
test(`Counts are as expected`, () => {
  const config: Configuration = {
    breadthProbability: 0.5,
    depthProbability: 0.5,
    maxDepth: 10,
    ignoreOptionalArguments: true,
    argumentsToConsider: ['first'],
    considerInterfaces: true,
    considerUnions: true,
    seed: 5
  }

  const {
    queryDocument,
    variableValues,
    typeCount,
    resolveCount,
    seed
  } = 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__marketplaceListings__first: Int) {
    marketplaceListings(first: $Query__marketplaceListings__first) {
      edges {
        node {
          secondaryCategory {
            description
            howItWorks
            primaryListingCount
            resourcePath
            secondaryListingCount
            url
          }
          app {
            databaseId
            id
            logoBackgroundColor
            slug
            url
          }
          configurationUrl
          extendedDescription
          extendedDescriptionHTML
          fullDescriptionHTML
          hasApprovalBeenRequested
          howItWorks
          howItWorksHTML
          installedForViewer
          isApproved
          isDelisted
          isPaid
          logoUrl
          name
          normalizedShortDescription
          resourcePath
          slug
          statusUrl
          supportUrl
          url
          viewerCanDelist
          viewerCanEditCategories
          viewerCanEditPlans
          viewerCanReject
          viewerHasPurchasedForAllOrganizations
        }
        cursor
      }
    }
  }`.replace(/\s/g, '')
  )
  expect(Object.keys(opDef.variableDefinitions).length).toEqual(
    Object.keys(variableValues).length
  )
  expect(errors).toEqual([])
})
Example #14
Source File: graphql-js-validation.ts    From graphql-eslint with MIT License 5 votes vote down vote up
function validateDocument(
  context: GraphQLESLintRuleContext,
  schema: GraphQLSchema | null = null,
  documentNode: DocumentNode,
  rule: ValidationRule
): void {
  if (documentNode.definitions.length === 0) {
    return;
  }
  try {
    const validationErrors = schema
      ? validate(schema, documentNode, [rule])
      : validateSDL(documentNode, null, [rule as any]);

    for (const error of validationErrors) {
      const { line, column } = error.locations[0];
      const sourceCode = context.getSourceCode();
      const { tokens } = sourceCode.ast;
      const token = tokens.find(token => token.loc.start.line === line && token.loc.start.column === column - 1);

      let loc: { line: number; column: number } | AST.SourceLocation = {
        line,
        column: column - 1,
      };
      if (token) {
        loc =
          // if cursor on `@` symbol than use next node
          (token.type as any) === '@' ? sourceCode.getNodeByRangeIndex(token.range[1] + 1).loc : token.loc;
      }

      context.report({
        loc,
        message: error.message,
      });
    }
  } catch (e) {
    context.report({
      loc: REPORT_ON_FIRST_CHARACTER,
      message: e.message,
    });
  }
}
Example #15
Source File: consider-listsize-directive.test.ts    From graphql-query-generator with MIT License 5 votes vote down vote up
test(`Add nested required argument ("args.first" and "args.complex.last")`, () => {
  const schema = buildSchema(`
    directive @listSize(requireOneSlicingArgument: Boolean = true, assumedSize: Int, slicingArguments: [String], sizedFields: [String]) on FIELD_DEFINITION
    
    input MoreArgs {
      last: Int!
      before: ID
    }

    input Args {
      first: Int!
      after: ID
      complex: MoreArgs!
    }

    type Order {
      id: ID
      date: String
    }

    type Query {
      orders(args: Args!): [Order]
    }
  `)
  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__args: Args!) {
        orders(args: $Query__orders__args) {
          id
          date
        }
      }
    `).trim()
  )
  const variables = JSON.stringify(variableValues, null, 2)
  expect(variables.trim()).toEqual(
    dedent(`
      {
        "Query__orders__args": {
          "first": 10,
          "complex": {
            "last": 10
          }
        }
      }
    `).trim()
  )
  expect(validate(schema, queryDocument)).toEqual([])
})
Example #16
Source File: example_api.test.ts    From graphql-mesh with MIT License 5 votes vote down vote up
test('Option customResolver with links', () => {
  const options: Options<any, any, any> = {
    customResolvers: {
      'Example API': {
        '/users/{username}': {
          get: () => {
            return {
              name: 'Jenifer Aldric',
              employerId: 'binsol',
            };
          },
        },
      },
    },
    fetch,
  };

  const query = `query {
    user(username: "abcdef") {
      name
      employerId
      employerCompany {
        name
        ceoUsername
        ceoUser {
          name
        }
      }
    }
  }`;

  return openAPIToGraphQL.createGraphQLSchema(oas, options).then(({ schema }) => {
    const ast = parse(query);
    const errors = validate(schema, ast);
    expect(errors).toEqual([]);
    return graphql({ schema, source: query }).then((result: any) => {
      expect(result).toEqual({
        data: {
          user: {
            name: 'Jenifer Aldric',
            employerId: 'binsol',
            employerCompany: {
              name: 'Binary Solutions',
              ceoUsername: 'johnny',
              ceoUser: {
                name: 'Jenifer Aldric',
              },
            },
          },
        },
      });
    });
  });
});
Example #17
Source File: single-query.test.ts    From graphql-query-generator with MIT License 5 votes vote down vote up
test(`Generate single random query`, () => {
  const config: Configuration = {
    breadthProbability: (nesting) => {
      if (nesting === 0) {
        return 0.5
      } else {
        return 1 / Math.pow(2, nesting)
      }
    },
    depthProbability: (nesting) => {
      if (nesting === 0) {
        return 0.5
      } else {
        return 1 / Math.pow(2, nesting)
      }
    },
    maxDepth: 10,
    ignoreOptionalArguments: true,
    argumentsToConsider: ['first'],
    providerMap: {
      '*__*__*': (existingVars, argType) => {
        if (argType.name === 'String') {
          return 'test'
        } else if (argType.name === 'Int') {
          return 1
        } else if (argType.name === 'Float') {
          return 1.0
        } else if (argType.name === 'Boolean') {
          return true
        }
      }
    },
    considerInterfaces: false,
    considerUnions: true,
    pickNestedQueryField: true,
    seed: 0.9366856322996101
  }

  const { queryDocument, variableValues } = generateRandomQuery(
    schemaGitHub,
    config
  )
  const errors = validate(schemaGitHub, queryDocument)

  expect(errors).toEqual([])
})
Example #18
Source File: index.ts    From hono with MIT License 4 votes vote down vote up
graphqlServer = (options: Options) => {
  const schema = options.schema
  const rootValue = options.rootValue
  const pretty = options.pretty ?? false
  const validationRules = options.validationRules ?? []
  // const showGraphiQL = options.graphiql ?? false

  return async (c: Context, next: Next) => {
    // GraphQL HTTP only supports GET and POST methods.
    if (c.req.method !== 'GET' && c.req.method !== 'POST') {
      return c.json(errorMessages(['GraphQL only supports GET and POST requests.']), 405, {
        Allow: 'GET, POST',
      })
    }

    let params: GraphQLParams
    try {
      params = await getGraphQLParams(c.req)
    } catch (e) {
      if (e instanceof Error) {
        console.error(`${e.stack || e.message}`)
        return c.json(errorMessages([e.message], [e]), 400)
      }
      throw e
    }

    const { query, variables, operationName } = params

    if (query == null) {
      return c.json(errorMessages(['Must provide query string.']), 400)
    }

    const schemaValidationErrors = validateSchema(schema)
    if (schemaValidationErrors.length > 0) {
      // Return 500: Internal Server Error if invalid schema.
      return c.json(
        errorMessages(['GraphQL schema validation error.'], schemaValidationErrors),
        500
      )
    }

    let documentAST: DocumentNode
    try {
      documentAST = parse(new Source(query, 'GraphQL request'))
    } catch (syntaxError: unknown) {
      // Return 400: Bad Request if any syntax errors errors exist.
      if (syntaxError instanceof Error) {
        console.error(`${syntaxError.stack || syntaxError.message}`)
        const e = new GraphQLError(syntaxError.message, {
          originalError: syntaxError,
        })
        return c.json(errorMessages(['GraphQL syntax error.'], [e]), 400)
      }
      throw syntaxError
    }

    // Validate AST, reporting any errors.
    const validationErrors = validate(schema, documentAST, [...specifiedRules, ...validationRules])

    if (validationErrors.length > 0) {
      // Return 400: Bad Request if any validation errors exist.
      return c.json(errorMessages(['GraphQL validation error.'], validationErrors), 400)
    }

    if (c.req.method === 'GET') {
      // Determine if this GET request will perform a non-query.
      const operationAST = getOperationAST(documentAST, operationName)
      if (operationAST && operationAST.operation !== 'query') {
        /*
        Now , does not support GraphiQL
        if (showGraphiQL) {
          //return respondWithGraphiQL(response, graphiqlOptions, params)
        }
        */

        // Otherwise, report a 405: Method Not Allowed error.
        return c.json(
          errorMessages([
            `Can only perform a ${operationAST.operation} operation from a POST request.`,
          ]),
          405,
          { Allow: 'POST' }
        )
      }
    }

    let result: FormattedExecutionResult

    try {
      result = await execute({
        schema,
        document: documentAST,
        rootValue,
        variableValues: variables,
        operationName: operationName,
      })
    } catch (contextError: unknown) {
      if (contextError instanceof Error) {
        console.error(`${contextError.stack || contextError.message}`)
        const e = new GraphQLError(contextError.message, {
          originalError: contextError,
          nodes: documentAST,
        })
        // Return 400: Bad Request if any execution context errors exist.
        return c.json(errorMessages(['GraphQL execution context error.'], [e]), 400)
      }
      throw contextError
    }

    if (!result.data) {
      if (result.errors) {
        return c.json(errorMessages([result.errors.toString()], result.errors), 500)
      }
    }

    /*
    Now, does not support GraphiQL
    if (showGraphiQL) {
    }
    */

    if (pretty) {
      const payload = JSON.stringify(result, null, pretty ? 2 : 0)
      return c.text(payload, 200, {
        'Content-Type': 'application/json',
      })
    } else {
      return c.json(result)
    }

    await next() // XXX
  }
}
Example #19
Source File: example_api3.test.ts    From graphql-mesh with MIT License 4 votes vote down vote up
test('Option customResolver with two APIs and interrelated links', () => {
  const options: Options<any, any, any> = {
    fetch,
    customResolvers: {
      'Example API': {
        '/users/{username}': {
          get: () => {
            return {
              name: 'Jenifer Aldric',
              employerId: 'binsol',
            };
          },
        },
      },
      'Example API 3': {
        '/authors/{authorId}': {
          get: () => {
            return {
              name: 'Jenifer Aldric, the author',
              masterpieceTitle: 'A collection of stories',
            };
          },
        },
        '/books/{bookId}': {
          get: () => {
            return {
              title: 'A collection of stories for babies',
              authorName: 'Jenifer Aldric, yet another author',
            };
          },
        },
      },
    },
  };
  const query = `query {
    author(authorId: "abcdef") {
      name
      employee{
        name
        employerCompany{
          name
        }
        author{
          name
          masterpiece{
            title
            author{
              name
              employee{
                name
              }
            }
          }
        }
      }
    }
  }`;
  return openAPIToGraphQL.createGraphQLSchema([oas, oas3], options).then(({ schema }) => {
    const ast = parse(query);
    const errors = validate(schema, ast);
    expect(errors).toEqual([]);
    return graphql({ schema, source: query }).then((result: any) => {
      expect(result).toEqual({
        data: {
          author: {
            name: 'Jenifer Aldric, the author',
            employee: {
              name: 'Jenifer Aldric',
              employerCompany: {
                name: 'Binary Solutions',
              },
              author: {
                name: 'Jenifer Aldric, the author',
                masterpiece: {
                  title: 'A collection of stories for babies',
                  author: {
                    name: 'Jenifer Aldric, the author',
                    employee: {
                      name: 'Jenifer Aldric',
                    },
                  },
                },
              },
            },
          },
        },
      });
    });
  });
});
Example #20
Source File: generate-query.test.ts    From graphql-query-generator with MIT License 4 votes vote down vote up
test(`Utilize type__field provider`, () => {
  const config: Configuration = {
    breadthProbability: 0.2,
    depthProbability: 0.3,
    maxDepth: 7,
    ignoreOptionalArguments: true,
    argumentsToConsider: ['first'],
    providerMap: GITHUB_PROVIDERS,
    considerInterfaces: true,
    considerUnions: true,
    seed: 0.2805754930509623
  }

  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($Repository__releases__first: Int, $Project__columns__first: Int, $Repository__projects__first: Int, $RepositoryOwner__pinnedRepositories__first: Int, $PullRequest_
  _assignees__first: Int, $User__publicKeys__first: Int, $User__commitComments__first: Int, $User__organization__login: String!, $User__pullRequests__first: Int, $User__starredRepositories__
  first: Int, $User__watching__first: Int, $PullRequest__participants__first: Int, $Repository__deployKeys__first: Int, $Repository__assignableUsers__first: Int, $Repository__collaborators__
  first: Int, $Repository__issueOrPullRequest__number: Int!, $PullRequest__comments__first: Int, $PullRequest__labels__first: Int, $Repository__pullRequest__number: Int!, $Query__repository_
  _name: String!, $Query__repository__owner: String!) {
    repository(name: $Query__repository__name, owner: $Query__repository__owner) {
      releases(first: $Repository__releases__first) {
        totalCount
      }
      projects(first: $Repository__projects__first) {
        nodes {
          columns(first: $Project__columns__first) {
            pageInfo {
              hasNextPage
            }
          }
          updatedAt
          url
        }
      }
      pullRequest(number: $Repository__pullRequest__number) {
        headRepositoryOwner {
          pinnedRepositories(first: $RepositoryOwner__pinnedRepositories__first) {
            edges {
              cursor
            }
          }
          avatarUrl
          ... on User {
            bio
            companyHTML
            createdAt
            id
            isSiteAdmin
            location
            login
            updatedAt
            websiteUrl
          }
        }
        assignees(first: $PullRequest__assignees__first) {
          nodes {
            bioHTML
            isBountyHunter
            isCampusExpert
          }
        }
        headRef {
          repository {
            description
            diskUsage
            viewerHasStarred
            viewerSubscription
          }
        }
        mergeCommit {
          abbreviatedOid
          changedFiles
          deletions
          id
          treeResourcePath
          treeUrl
          url
          viewerSubscription
        }
        mergedBy {
          login
          ... on User {
            isCampusExpert
            viewerCanFollow
          }
        }
        participants(first: $PullRequest__participants__first) {
          nodes {
            publicKeys(first: $User__publicKeys__first) {
              pageInfo {
                hasNextPage
              }
            }
            commitComments(first: $User__commitComments__first) {
              totalCount
            }
            organization(login: $User__organization__login) {
              databaseId
              id
              location
              newTeamUrl
              resourcePath
              viewerCanAdminister
            }
            pullRequests(first: $User__pullRequests__first) {
              nodes {
                baseRefOid
                changedFiles
                closedAt
                databaseId
                headRefOid
                revertUrl
                state
                title
                updatedAt
                viewerCanApplySuggestion
                viewerCanReact
                viewerCanUpdate
                viewerCannotUpdateReasons
                viewerSubscription
              }
              edges {
                cursor
              }
            }
            starredRepositories(first: $User__starredRepositories__first) {
              pageInfo {
                endCursor
              }
            }
            watching(first: $User__watching__first) {
              nodes {
                hasIssuesEnabled
                hasWikiEnabled
                isFork
                projectsResourcePath
                updatedAt
                viewerCanCreateProjects
                viewerSubscription
              }
            }
            avatarUrl
            company
            createdAt
            email
            isBountyHunter
            isEmployee
          }
          pageInfo {
            hasPreviousPage
          }
        }
        potentialMergeCommit {
          authoredDate
          committedDate
          committedViaWeb
          deletions
          treeUrl
        }
        reactionGroups {
          createdAt
        }
        repository {
          deployKeys(first: $Repository__deployKeys__first) {
            edges {
              node {
                verified
              }
            }
          }
          assignableUsers(first: $Repository__assignableUsers__first) {
            nodes {
              company
              email
              isCampusExpert
              isDeveloperProgramMember
              isSiteAdmin
              resourcePath
            }
          }
          collaborators(first: $Repository__collaborators__first) {
            pageInfo {
              endCursor
            }
            nodes {
              bioHTML
              databaseId
              isHireable
            }
            totalCount
          }
          issueOrPullRequest(number: $Repository__issueOrPullRequest__number) {
            ... on Issue {
              bodyHTML
              id
            }
          }
          pullRequest(number: $Repository__pullRequest__number) {
            comments(first: $PullRequest__comments__first) {
              pageInfo {
                startCursor
              }
            }
            editor {
              avatarUrl
              ... on Bot {
                createdAt
              }
            }
            labels(first: $PullRequest__labels__first) {
              totalCount
            }
            milestone {
              url
            }
            activeLockReason
            body
            createdViaEmail
            headRefOid
            number
            permalink
            viewerCanReact
            viewerDidAuthor
          }
          descriptionHTML
          forkCount
          isArchived
          isMirror
          mergeCommitAllowed
          nameWithOwner
          projectsUrl
          rebaseMergeAllowed
          viewerCanAdminister
          viewerHasStarred
        }
        suggestedReviewers {
          reviewer {
            avatarUrl
            isBountyHunter
            isEmployee
            isSiteAdmin
          }
        }
        authorAssociation
        baseRefName
        baseRefOid
        bodyHTML
        bodyText
        changedFiles
        mergedAt
        publishedAt
        state
        viewerCanApplySuggestion
        viewerCanSubscribe
        viewerCannotUpdateReasons
      }
      createdAt
      isArchived
      isLocked
      mergeCommitAllowed
      nameWithOwner
      pushedAt
      viewerHasStarred
    }
  }`.replace(/\s/g, '')
  )

  expect(Object.keys(opDef.variableDefinitions).length).toEqual(
    Object.keys(variableValues).length
  )
  expect(errors).toEqual([])
  expect(print(queryDocument).trim().split(`\n`).length).toBe(247)
})