Schema-Stitching
Installation
npm i @graphql-hive/coreWe recommend installing Hive Client package as a direct dependency of your project, because it includes a runtime to send usage reports and schemas to Hive registry.
The @graphql-hive/core package exports a utility function called createServicesFetcher that can
be used to fetch services definition from Hive's CDN. You can use it to create a GraphQL schema from
the all services schemas published to Hive.
The createServicesFetcher function is a part of the @graphql-hive/core
package, and it can be used with any GraphQL server runtime. You may use it
with Apollo Server, GraphQL Yoga, or any other library to implement a custom
GraphQL gateway.
Fetching Services Info from CDN
Once you have all services schemas pushed to Hive, and available in the CDN, you can create a CDN Access Token and gain access to the CDN endpoint.
In this example, we are using GraphQL-Yoga to create the Gateway server.
import { createServer } from "node:http";
import { buildSchema } from "graphql";
import { createYoga } from "graphql-yoga";
import { createCDNArtifactFetcher } from "@graphql-hive/core";
import { buildHTTPExecutor } from "@graphql-tools/executor-http";
import { stitchSchemas } from "@graphql-tools/stitch";
const fetcher = createCDNArtifactFetcher({
endpoint: [
"https://cdn.graphql-hive.com/artifacts/v1/<target_id>/services",
"https://cdn-mirror.graphql-hive.com/artifacts/v1/<target_id>/services",
],
accessKey: "<cdn_access_key>",
});
async function main() {
const services = JSON.parse(await fetcher.fetch());
const subschemas = services.map((service) => {
return {
schema: buildSchema(service.sdl),
executor: buildHTTPExecutor({ endpoint: service.url }),
};
});
const schema = stitchSchemas({ subschemas });
const yoga = createYoga({ schema });
const server = createServer(yoga);
server.listen(4000, () => {
console.info("Gateway is running on http://localhost:4000/graphql");
});
}
main().catch((err) => {
console.error(err);
process.exit(1);
});Usage Reporting
Based on the server runtime you choosed, you can enable the usage reporting activate the Hive plugin for the server you are running.