How to use @apollo/federation - 10 common examples

To help you get started, we’ve selected a few @apollo/federation examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github apollographql / federation-demo / services / inventory / index.js View on Github external
return {
        ...object,
        ...inventory.find(product => product.upc === object.upc)
      };
    },
    shippingEstimate(object) {
      // free for expensive items
      if (object.price > 1000) return 0;
      // estimate is based on weight
      return object.weight * 0.5;
    }
  }
};

const server = new ApolloServer({
  schema: buildFederatedSchema([
    {
      typeDefs,
      resolvers
    }
  ])
});

server.listen({ port: 4004 }).then(({ url }) => {
  console.log(`πŸš€ Server ready at ${url}`);
});

const inventory = [
  { upc: "1", inStock: true },
  { upc: "2", inStock: false },
  { upc: "3", inStock: true }
];
github Urigo / graphql-modules / examples / apollo-federation / services / inventory / index.ts View on Github external
...object,
          ...inventory.find(product => product.upc === object.upc)
        };
      },
      shippingEstimate(object) {
        // free for expensive items
        if (object.price > 1000) return 0;
        // estimate is based on weight
        return object.weight * 0.5;
      }
    }
  }
});

const server = new ApolloServer({
  schema: buildFederatedSchema([InventoryModule]),
  context: session => session
});

server.listen({ port: 4004 }).then(({ url }) => {
  // tslint:disable-next-line: no-console
  console.log(`πŸš€ Server ready at ${url}`);
});

const inventory = [{ upc: '1', inStock: true }, { upc: '2', inStock: false }, { upc: '3', inStock: true }];
github webiny / webiny-js / packages / api / src / graphql / prepareSchema.js View on Github external
// Fetch schema plugins again, in case there were new plugins registered in the meantime.
    const schemaPlugins = plugins.byType("graphql-schema");
    for (let i = 0; i < schemaPlugins.length; i++) {
        const { schema } = schemaPlugins[i];
        if (!schema) {
            continue;
        }

        if (typeof schema === "function") {
            schemaDefs.push(await schema({ plugins }));
        } else {
            schemaDefs.push(schema);
        }
    }

    return buildFederatedSchema([...schemaDefs]);
}
github juicycleff / ultimate-backend / libs / nestjs-graphql-gateway / src / nestjs-graphql-distributed.module.ts View on Github external
} = this.options;
    const app = httpAdapter.getInstance();

    // @ts-ignore
    const typeDefs = await this.graphqlTypesLoader.getTypesFromPaths(typePaths);

    const mergedTypeDefs = extend(typeDefs, this.options.typeDefs);
    const apolloOptions = await this.graphqlDistributedFactory.mergeOptions({
      ...this.options,
      typeDefs: mergedTypeDefs,
    });

    if (this.options.definitions && this.options.definitions.path) {
      await this.graphqlFactory.generateDefinitions(
        // @ts-ignore
        printSchema(apolloOptions.schema),
        this.options,
      );
    }

    this.apolloServer = new ApolloServer(apolloOptions as any);
    this.apolloServer.applyMiddleware({
      app,
      path,
      disableHealthCheck,
      onHealthCheck,
      cors,
      bodyParserConfig,
    });

    if (this.options.installSubscriptionHandlers) {
      // TL;DR 
github TheBrainFamily / federation-testing-tool / index.js View on Github external
function buildLocalService(modules) {
  const schema = buildFederatedSchema(modules);
  return new LocalGraphQLDataSource(schema);
}
github TheBrainFamily / federation-testing-tool / index.js View on Github external
let serviceName = Object.keys(service)[0];
    if (!service[serviceName].resolvers) {
      service[serviceName].addMocks = true;
    }
    serviceMap[serviceName] = buildLocalService([service[serviceName]]);
    serviceMap[serviceName].__addMocks__ = service[serviceName].addMocks;
  });

  let mapForComposeServices = Object.entries(serviceMap).map(
    ([serviceName, service]) => ({
      name: serviceName,
      typeDefs: service.sdl()
    })
  );

  let composed = composeAndValidate(mapForComposeServices);

  if (composed.errors && composed.errors.length > 0) {
    throw new Error(JSON.stringify(composed.errors));
  }
  return { schema: composed.schema, serviceMap };
};
github apollographql / apollo-server / packages / apollo-gateway / src / __tests__ / execution-utils.ts View on Github external
): Promise {
  let schema: GraphQLSchema;
  const serviceMap = Object.fromEntries(
    services.map(({ name, typeDefs, resolvers }) => {
      return [
        name,
        new LocalGraphQLDataSource(
          buildFederatedSchema([{ typeDefs, resolvers }]),
        ),
      ] as [string, LocalGraphQLDataSource];
    }),
  );

  let errors: GraphQLError[];

  ({ schema, errors } = composeAndValidate(
    Object.entries(serviceMap).map(([serviceName, service]) => ({
      name: serviceName,
      typeDefs: service.sdl(),
    })),
  ));

  if (errors && errors.length > 0) {
    throw new GraphQLSchemaValidationError(errors);
  }
  const operationContext = buildOperationContext(schema, request.query);

  const queryPlan = buildQueryPlan(operationContext);

  const result = await executeQueryPlan(
    queryPlan,
    serviceMap,
github kriswep / graphql-microservices / service-post / src / index.js View on Github external
import { ApolloServer } from 'apollo-server';
import { buildFederatedSchema } from '@apollo/federation';

import typeDefs from './schema/post';
import resolvers from './resolver';

const PORT = process.env.PORT || 3010;

const server = new ApolloServer({
  schema: buildFederatedSchema([
    {
      typeDefs,
      resolvers
    }
  ])
});

server.listen(PORT).then(({ url }) => {
  console.log(`πŸš€ Server ready at ${url}`);
});
github 0xR / graphql-transform-federation / example / federation-server.ts View on Github external
const product = {
  id: '123',
  price: 899,
  weight: 100,
};

const resolvers = {
  Query: {
    findProduct() {
      return product;
    },
  },
};

const server = new ApolloServer({
  schema: buildFederatedSchema([
    {
      typeDefs,
      resolvers,
    },
  ]),
});

server.listen({ port: 4002 }).then(({ url }: ServerInfo) => {
  console.log(`πŸš€ Federation server ready at ${url}`);
});
github kriswep / graphql-microservices / service-user / src / index.js View on Github external
import { ApolloServer } from 'apollo-server';
import { buildFederatedSchema } from '@apollo/federation';

import typeDefs from './schema/user';
import resolvers from './resolver';

const PORT = process.env.PORT || 3020;

const server = new ApolloServer({
  schema: buildFederatedSchema([
    {
      typeDefs,
      resolvers
    }
  ])
});

server.listen(PORT).then(({ url }) => {
  console.log(`πŸš€ Server ready at ${url}`);
});