graphql#buildClientSchema TypeScript Examples

The following examples show how to use graphql#buildClientSchema. 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: diffGraphql.ts    From one-platform with MIT License 6 votes vote down vote up
diffGraphql = async (oldSpec: string, newSpec: string): Promise<GraphqlDiff> => {
  const oldIntrospectionResult = JSON.parse(oldSpec).data;
  const oldGraphqlSchema = buildClientSchema(oldIntrospectionResult);
  const newIntrospectionResult = JSON.parse(newSpec).data;
  const newGraphqlSchema = buildClientSchema(newIntrospectionResult);
  const diff = await gqlDifference(oldGraphqlSchema, newGraphqlSchema);

  const changes = partitionByCriticalLevel(diff);
  const hasChanged =
    Boolean(changes.breakingDiff.length) ||
    Boolean(changes.dangerous.length) ||
    Boolean(changes.nonBreakingDiff.length);

  return { ...changes, hasChanged };
}
Example #2
Source File: generate.test.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
describe('generate', () => {
  const getQueryType = jest.fn();
  const getMutationType = jest.fn();
  const getSubscriptionType = jest.fn();

  const mockSchema = {
    getQueryType,
    getMutationType,
    getSubscriptionType,
  };
  const maxDepth = 4;
  const generateOption: GQLDocsGenOptions = { useExternalFragmentForS3Object: true };
  beforeEach(() => {
    jest.resetAllMocks();
    getQueryType.mockReturnValue('QUERY_TYPE');
    getMutationType.mockReturnValue('MUTATION_TYPE');
    getSubscriptionType.mockReturnValue('SUBSCRIPTION_TYPE');

    buildClientSchema.mockReturnValue(mockSchema);
    generateQueries.mockReturnValue('MOCK_GENERATED_QUERY');
    generateMutations.mockReturnValue('MOCK_GENERATED_MUTATION');
    generateSubscriptions.mockReturnValue('MOCK_GENERATED_SUBSCRIPTION');
  });

  it('should generate operations using the helper methods', () => {
    generate(mockSchema, maxDepth, generateOption);
    expect(generateQueries).toHaveBeenCalledWith(mockSchema.getQueryType(), mockSchema, maxDepth, generateOption);
    expect(generateMutations).toHaveBeenCalledWith(mockSchema.getMutationType(), mockSchema, maxDepth, generateOption);
    expect(generateSubscriptions).toHaveBeenCalledWith(mockSchema.getSubscriptionType(), mockSchema, maxDepth, generateOption);
  });

  it('should call the individual operation generator and return the value from them', () => {
    expect(generate(mockSchema, maxDepth, generateOption)).toEqual({
      queries: 'MOCK_GENERATED_QUERY',
      subscriptions: 'MOCK_GENERATED_SUBSCRIPTION',
      mutations: 'MOCK_GENERATED_MUTATION',
    });
  });
});
Example #3
Source File: loading.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
function loadIntrospectionSchema(schemaPath: string): GraphQLSchema {
  if (!fs.existsSync(schemaPath)) {
    throw new Error(`Cannot find GraphQL schema file: ${schemaPath}`);
  }
  const schemaData = require(schemaPath);

  if (!schemaData.data && !schemaData.__schema) {
    throw new Error('GraphQL schema file should contain a valid GraphQL introspection query result');
  }
  return buildClientSchema(schemaData.data ? schemaData.data : schemaData);
}
Example #4
Source File: loading.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
function loadIntrospectionSchema(schemaPath: string): GraphQLSchema {
  if (!fs.existsSync(schemaPath)) {
    throw new ToolError(`Cannot find GraphQL schema file: ${schemaPath}`);
  }
  const schemaData = require(schemaPath);

  if (!schemaData.data && !schemaData.__schema) {
    throw new ToolError('GraphQL schema file should contain a valid GraphQL introspection query result');
  }
  return buildClientSchema(schemaData.data ? schemaData.data : schemaData);
}
Example #5
Source File: fetchSchema.ts    From genql with MIT License 6 votes vote down vote up
customFetchSchema = async (
    fetcher: SchemaFetcher,
    options?: GraphQLSchemaValidationOptions,
) => {
    const result = await fetcher(getIntrospectionQuery(), fetch, qs)

    if (!result.data) {
        throw new Error(
            'introspection request did not receive a valid response',
        )
    }

    return buildClientSchema(result.data as any, options)
}
Example #6
Source File: render.ts    From genql with MIT License 6 votes vote down vote up
toClientSchema = async (schemaGql: string) => {
    const schema = buildSchema(schemaGql)

    const introspectionResponse = await graphql(
        schema,
        getIntrospectionQuery(),
    )

    if (!introspectionResponse.data) {
        throw new Error(JSON.stringify(introspectionResponse.errors))
    }

    return buildClientSchema(introspectionResponse.data as any)
}
Example #7
Source File: CLI.ts    From tql with MIT License 6 votes vote down vote up
async function remoteSchema(url: string) {
  const { data, errors } = await fetch(url, {
    method: "post",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      operationName: "IntrospectionQuery",
      query: getIntrospectionQuery(),
    }),
  }).then((res) => res.json());

  if (errors) {
    throw new Error("Error fetching remote schema!");
  }

  return printSchema(buildClientSchema(data));
}
Example #8
Source File: index.ts    From graphql-mesh with MIT License 5 votes vote down vote up
async getNonExecutableSchemaForHTTPSource(
    httpSourceConfig: YamlConfig.GraphQLHandlerHTTPConfiguration
  ): Promise<GraphQLSchema> {
    const schemaHeadersFactory = getInterpolatedHeadersFactory(httpSourceConfig.schemaHeaders || {});
    const customFetch = await this.getCustomFetchImpl(httpSourceConfig.customFetch);
    if (httpSourceConfig.introspection) {
      const headers = schemaHeadersFactory({
        env: process.env,
      });
      const sdlOrIntrospection = await readFileOrUrl<string | IntrospectionQuery | DocumentNode>(
        httpSourceConfig.introspection,
        {
          cwd: this.baseDir,
          allowUnknownExtensions: true,
          fetch: customFetch,
          headers,
        }
      );
      if (typeof sdlOrIntrospection === 'string') {
        return buildSchema(sdlOrIntrospection);
      } else if (isDocumentNode(sdlOrIntrospection)) {
        return buildASTSchema(sdlOrIntrospection);
      } else if (sdlOrIntrospection.__schema) {
        return buildClientSchema(sdlOrIntrospection);
      }
      throw new Error(`Invalid introspection data: ${util.inspect(sdlOrIntrospection)}`);
    }
    return this.nonExecutableSchema.getWithSet(() => {
      const endpointFactory = getInterpolatedStringFactory(httpSourceConfig.endpoint);
      const executor = this.urlLoader.getExecutorAsync(httpSourceConfig.endpoint, {
        ...httpSourceConfig,
        customFetch,
        subscriptionsProtocol: httpSourceConfig.subscriptionsProtocol as SubscriptionProtocol,
      });
      return introspectSchema(function meshIntrospectionExecutor(params: ExecutionRequest) {
        const resolverData = getResolverData(params);
        return executor({
          ...params,
          extensions: {
            ...params.extensions,
            headers: schemaHeadersFactory(resolverData),
            endpoint: endpointFactory(resolverData),
          },
        });
      });
    });
  }
Example #9
Source File: fetchSchema.ts    From genql with MIT License 5 votes vote down vote up
fetchSchema = async ({
    endpoint,
    usePost = false,
    headers,
    options,
}: {
    endpoint: string
    usePost: boolean
    headers?: Record<string, string>
    options?: GraphQLSchemaValidationOptions
}) => {
    const response = await fetch(
        usePost
            ? endpoint
            : `${endpoint}?${qs.stringify({ query: getIntrospectionQuery() })}`,
        usePost
            ? {
                  method: usePost ? 'POST' : 'GET',
                  body: JSON.stringify({ query: getIntrospectionQuery() }),
                  headers: { ...headers, 'Content-Type': 'application/json' },
              }
            : {
                  headers,
              },
    )
    if (!response.ok) {
        throw new Error(
            'introspection query was not successful, ' + response.statusText,
        )
    }

    const result = await response.json().catch((e) => {
        const contentType = response.headers.get('Content-Type')
        console.log(`content type is ${contentType}`)
        throw new Error(
            `endpoint '${endpoint}' did not return valid json, check that your endpoint points to a valid graphql api`,
        )
    })
    if (!result.data) {
        throw new Error(
            'introspection request did not receive a valid response',
        )
    }

    // console.log(result.data)
    // console.log(JSON.stringify(result.data, null, 4))

    return buildClientSchema(result.data, options)
}