graphql#validateSchema TypeScript Examples

The following examples show how to use graphql#validateSchema. 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: handler.spec.ts    From graphql-mesh with MIT License 5 votes vote down vote up
describe.each<[string, string]>([
  ['Movie', 'movie.proto'],
  ['Empty', 'empty.proto'],
  ['Nested', 'nested.proto'],
  ['Import Nested', 'import-nested.proto'],
  ['With All Values', 'allvalues.proto'],
  ['No Package Nested', 'nopackage-nested.proto'],
  ['With Underscores', 'underscores.proto'],
  ['Outside', 'outside.proto'],
  ['Custom Message', 'custom-message.proto'],
  ['Custom Message2', 'custom-message-2.proto'],
  ['Comments', 'comments.proto'],
])('Interpreting Protos', (name, file) => {
  test(`should load the ${name} proto`, async () => {
    const cache = new InMemoryLRUCache();
    const pubsub = new PubSub();
    const config: YamlConfig.GrpcHandler = {
      endpoint: 'localhost',
      protoFilePath: {
        file: join(__dirname, './fixtures/proto-tests', file),
        load: { includeDirs: [join(__dirname, './fixtures/proto-tests')] },
      },
    };
    const store = new MeshStore(name, new InMemoryStoreStorageAdapter(), {
      readonly: false,
      validate: false,
    });
    const logger = new DefaultLogger(name);
    const handler = new GrpcHandler({
      name: Date.now().toString(),
      config,
      cache,
      pubsub,
      store,
      logger,
      importFn: m => import(m),
      baseDir: __dirname,
    });

    const { schema } = await handler.getMeshSource();

    expect(schema).toBeInstanceOf(GraphQLSchema);
    expect(validateSchema(schema)).toHaveLength(0);
    expect(printSchema(schema)).toMatchSnapshot();
  });
});
Example #2
Source File: schema.ts    From squid with GNU General Public License v3.0 5 votes vote down vote up
export function buildSchema(doc: DocumentNode): GraphQLSchema {
    let schema = extendSchema(baseSchema, doc)
    let errors = validateSchema(schema).filter(err => !/query root/i.test(err.message))
    if (errors.length > 0) {
        throw errors[0]
    }
    return schema
}
Example #3
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
  }
}