How to use the graphql-tools.mergeSchemas function in graphql-tools

To help you get started, we’ve selected a few graphql-tools 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 ezyang / ghstack / github-fake / src / index.js View on Github external
}
    input ResetGitHubInput {
      clientMutationId: String
    }
    type ResetGitHubPayload {
      clientMutationId: String
    }
    type Mutation {
      resetGitHub(input: ResetGitHubInput!): ResetGitHubPayload
    }
  `,
  resolvers: controlResolvers,
});
const githubSchema = makeExecutableSchema({ typeDefs: githubTypeDefs, resolvers: githubResolvers, resolverValidationOptions });

const schema = mergeSchemas({
  schemas: [
    controlSchema,
    githubSchema,
  ],
});

const server = new ApolloServer({ schema });

// This `listen` method launches a web-server.  Existing apps
// can utilize middleware options, which we'll discuss later.
const port = process.argv[2] ? process.argv[2] : 4000;
server.listen(port).then(({ url }) => {
  console.log(`${url}`);
});
github apollographql / apollo-client-devtools / src / devtools / components / Explorer / Explorer.js View on Github external
// add add-hoc client only directives
            // XXX replace this with better directives => types function
            // XXX this is a bottleneck but only happens once
            let remoteSchemaString = printSchema(remoteSchema);

            remoteSchemaString =
              remoteSchemaString + ` ${directivesOnly.join("\n")}`;
            remoteSchema = buildSchema(remoteSchemaString);

            directives = directives.concat(remoteSchema._directives);

            mergedSchema = mergeSchemas({
              schemas: [remoteSchema].concat(built),
            });
          } else {
            mergedSchema = mergeSchemas({ schemas: built });
          }

          // Incorporate client schemas

          const clientSchemas = schemas.filter(
            ({ directives }) => directives === "directive @client on FIELD",
          );

          if (clientSchemas.length > 0) {
            // Add all the directives for all the client schemas! This will produce
            // duplicates; that's ok because duplicates are filtered below.
            directives = directives.concat(
              ...clientSchemas.map(clientSchema =>
                buildSchema(clientSchema.directives).getDirectives(),
              ),
            );
github jakelowen / nextjs_hasura_magic_login / createServer.js View on Github external
null,
    linkOverRide // the admin override above used for introspection,
  );

  // the local custom schema out of custom resolvers and typedefs
  // mainly auth stuff
  const executableCustomSchema = makeExecutableSchema({
    typeDefs,
    resolvers: {
      Mutation,
      Query,
    },
  });

  // merge custom resolvers with Hasura schema
  const finalSchema = mergeSchemas({
    schemas: [executableHasuraSchema, executableCustomSchema],
  });

  // intialize db
  const db = knex();

  return new ApolloServer({
    schema: finalSchema,
    resolverValidationOptions: {
      requireResolversForResolveType: false,
    },
    context: async ({ req, res, connection }) => {
      if (connection) {
        return connection.context;
      }
      return { db, res, userId: req.userId || null };
github genie-team / graphql-genie / examples / apollo-server2-redis-jwt-auth / src / main.ts View on Github external
// don't change user if logged
			if (context && context.hasOwnProperty('currUser') && isEmpty(context.currUser)) {
				// the mutate r*esolver will return with other metadata but we just want the actual record
				const userData = getRecordFromResolverReturn(createdUser);
				context.currUser['id'] = userData['id'];
				context.currUser['roles'] = userData['roles'];
			}

		}
		return createdUser;
	};

	// TODO: alter createUser mutation to return JWT, need to add jwt to UserPayload and wrap the resolver

	// create the new queries/mutations and resolvers
	return mergeSchemas({
		schemas: [
			schema,
			`extend type Mutation {
				login(identifier: String!, password: String!): ID
			}
			extend type UserPayload {
				"""
				Provided on signup (createUser mutation)
				"""
				jwt: String
			}`
		],
		resolvers: {
			UserPayload: {
				jwt: {
					fragment: `... on UserPayload { id, roles }`,
github aerogear / graphback / packages / graphback / src / schema / SchemaParser.ts View on Github external
let preValidationSchema = this.schema;
    if (!this.schema.getQueryType()) {
      // Definition has no Query type
      // To validate schema we need to merge definition with example query type
      const placeholderSchema = new GraphQLSchema({
        query: new GraphQLObjectType({
          name: 'RootQueryType',
          fields: {
            sample: {
              type: GraphQLString
            }
          }
        }),
      });

      preValidationSchema = mergeSchemas({
        schemas: [placeholderSchema, this.schema]
      })
    }
    // Schema needed to compare results
    this.introspectionSchema = introspectionFromSchema(preValidationSchema, { descriptions: false })

    return graphql(preValidationSchema, introspectionQuery)
  }
github supercycle91 / graphql-microservices-example / main-api / server.js View on Github external
(async function () {
	try {
		//promise.all to grab all remote schemas at the same time, we do not care what order they come back but rather just when they finish
		allSchemas = await Promise.all(endpoints.map(ep => getIntrospectSchema(ep)));
		//create function for /graphql endpoint and merge all the schemas
		app.use('/graphql', bodyParser.json(), graphqlExpress({ schema: mergeSchemas({ schemas: allSchemas }) }));
		//start up a graphql endpoint for our main server
		app.listen(PORT, () => console.log('GraphQL API listening on port:' + PORT));
	} catch (error) {
		console.log('ERROR: Failed to grab introspection queries', error);
	}
})();
github revskill10 / next-template / modules / core / api / create-schema.js View on Github external
if (urlMap.hasOwnProperty(key)) {
      let tmp = null
      if (urlMap[key].type === 'graphql') {
        tmp = await getRemoteSchema(adminLinks[key])        
      }     
      if (urlMap[key].type === 'soap') {
        tmp = await soapGraphqlSchema(urlMap[key].url)        
      }
      if (urlMap[key].permissions) {
        tmp = applyMiddleware(tmp, urlMap[key].permissions)
      }
      remoteSchemas.push(tmp)
    }
  }
  
  return mergeSchemas({
    schemas: [
      ...remoteSchemas,
      localSchema,
    ],
  })
}
github tlivings / graphql-seneca-example / gateway / lib / merge.js View on Github external
function merge(partials) {
    const schemas = [];

    for (const partial of partials) {
        schemas.push(makeExecutableSchema({
            typeDefs: [partial.rootTypes, ...partials.map((partial) => partial.types)],
            resolvers: partial.resolvers
        }));
    }

    const mergedSchema = mergeSchemas({
        schemas
    });

    return mergedSchema;
};
github ashinzekene / generator-nestjs-app / generators / app / templates / 12-graphql-apollo / src / modules / app.module.ts View on Github external
createSchema() {
    const typeDefs = this.graphQLFactory.mergeTypesByPaths('./**/*.graphql');
    const schema = this.graphQLFactory.createSchema({ typeDefs });

    const delegates = this.graphQLFactory.createDelegates();
    const { humanSchema, linkTypeDefs } = this.createDelegatedSchema();
    return mergeSchemas({
      schemas: [schema, humanSchema, linkTypeDefs],
      resolvers: delegates,
    });
  }
github gramps-graphql / gramps--legacy / src / gramps.js View on Github external
apolloOptions,
  );

  const sourcesWithStitching = sources.filter(source => source.stitching);
  const linkTypeDefs = sourcesWithStitching.map(
    source => source.stitching.linkTypeDefs,
  );
  const resolvers = sourcesWithStitching.map(
    source => source.stitching.resolvers,
  );

  const remoteSources = sources.filter(source => source.remoteSchema);

  const remoteSchemas = await handleRemoteSchemas(remoteSources);

  const schema = mergeSchemas({
    schemas: [...schemas, ...linkTypeDefs, ...remoteSchemas],
    resolvers,
  });

  const getContext = req => {
    const extra = extraContext(req);
    return sources.reduce((allContext, source) => {
      const sourceContext =
        typeof source.context === 'function'
          ? source.context(req)
          : source.context;

      return {
        ...allContext,
        [source.namespace]: { ...extra, ...sourceContext },
      };