How to use graphql-tools - 10 common examples

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 tomitrescak / apollo-mobx / src / testing / index.tsx View on Github external
mutations = {},
  resolvers = {},
  reducers = {},
  typeDefs = global.globalTypeDefs,
  context,
  loadingComponent
}: ApolloProps) {
  // add crap around mocks
  const finalMocks = {
    ...resolvers,
    Mutation: () => mutations || {},
    Query: () => queries || {},
  };

  const schema = makeExecutableSchema({ typeDefs, resolvers: global.globalResolvers });
  addMockFunctionsToSchema({
    mocks: finalMocks,
    schema,
  });

  const apolloCache = new InMemoryCache(global.__APOLLO_STATE_);

  const spyLink = new SpyLink();
  const graphqlClient: ApolloClient = new ApolloClient({
    cache: apolloCache as any,
    context,
    link: ApolloLink.from([
      spyLink,
      new MockLink({ schema }),
    ]),
    loadingComponent
  });
github ember-graphql / ember-apollo-client / tests / dummy / app / instance-initializers / mock-graphql.js View on Github external
};
  let mocks = {
    // This is where you tell graphql-tools how to generate a mock for a custom
    // scalar type:
    //
    // Time() {
    //   return moment().utc().format('YYYY-MM-DDTHH:mm:ss.SSSZ');
    // }

    Date() {
      return '2019-09-28';
    },
  };

  let schema = makeExecutableSchema({ typeDefs: schemaString, resolvers });
  addResolveFunctionsToSchema({
    schema,
    resolvers: typeResolvers,
    inheritResolversFromInterfaces: true,
  });
  addMockFunctionsToSchema({ schema, mocks, preserveResolvers: true });

  let pretender = new Pretender();

  pretender.post('https://test.example/graphql', function(request) {
    let body = JSON.parse(request.requestBody);

    return graphql(schema, body.query, {}, {}, body.variables).then(result => {
      return [200, { 'Content-Type': 'application/json' }, result];
    });
  });
github mrdulin / apollo-server-express-starter / src / graphql-error-and-logger / index.ts View on Github external
import express from 'express';
import bodyParser from 'body-parser';
import { graphqlExpress, graphiqlExpress } from 'apollo-server-express';
import { makeExecutableSchema } from 'graphql-tools';
import { GraphQLSchema } from 'graphql';
import http from 'http';
import { GraphQLOptions } from 'apollo-server-core';

import { resolvers } from './resolvers';
import { typeDefs } from './typeDefs';
import { config } from '../config';
import { logger, log } from '../utils';
import { Book } from './models';

const schema: GraphQLSchema = makeExecutableSchema({ typeDefs, resolvers, logger: { log } });

async function main(): Promise {
  const app: express.Application = express();
  const graphqlOptions: GraphQLOptions = {
    schema,
    context: {
      Book
    },
    formatError: err => {
      logger.info('formatError');
      const logErr = {
        path: err.path,
        locations: err.locations
      };
      // tslint:disable-next-line:no-console
      console.error(logErr);
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 mrdulin / apollo-server-express-starter / src / mocking / mockList.spec.js View on Github external
paginatedFriends: (o, { pageNo }) => {
        // console.log('pageNo: ', pageNo);
        return new MockList(pageNo * PAGE_SIZE, () => {
          return { id: casual.id, name: casual.name };
        });
      }
    };
github mrdulin / apollo-server-express-starter / src / mocking / mockList.spec.js View on Github external
allUsers: () => {
        const mockList = new MockList([USER_MIN_NUM, USER_MAX_NUM], (source, args, context, info) => {
          return { id: casual.id, name: casual.name };
        });
        // console.log('mockList: ', mockList);
        return mockList;
      },
      user: (source, { id }, context, info) => {
github olymp / olymp / packages / graphql / server / schema-builder / index.js View on Github external
});
          let value;
          onAfter.forEach((hook) => {
            promise = promise.then((newValue) => {
              value = newValue || value;
              return hook({ keys, source, value, variables, context, resolverAST, ast });
            });
          });
          return promise.then(newValue => newValue || value);
        };
      } else {
        store[key] = obj[key];
      } return store;
    }, {});
  };
  addResolveFunctionsToSchema(builtSchema, recurse(resolvers));
  // console.log(resolvers);
  return builtSchema;
};
github Kong / mockbin / lib / routes / bins / view_graphql.js View on Github external
//const data = "{'books': [{ 'title': 'blah', 'author': 'blah'},{ 'title': 'what', 'author': 'ever'}]}"
	//const typeDefs = 'type Query { getBooks: [Book], getString: String! } type Book { title: String author: String!}'

	// TEMP nice to see the qury in the window
	console.log("\nQuery:\n" + query);

	var index = 0;
	var d = JSON.parse(value);
	//const mocks = { Books: () => ({ title: JSON.stringify(d.books[index++]), author: "aaaa" }) }
	const mocks = { String: () => casual.sentence, Int: () => casual.integer(0, 10000), Float: () => casual.double(0.1, 10000) }
	//const mocks = utils.mocksFromJSON(value);
        console.log(mocks);

	const preserveResolvers = false
	const server = mockServer(schema, mocks, preserveResolvers);
	const variables = {}

        try {
		server.query(query, variables)
  			.then(function(response){  
      				console.log(response);
      				res.status(200).location('/').body = response;
      				next()
     			})

        } catch(e) {
	
		res.status(500).location('/').body = "{ \"error\" : \"Error mocking server\" }";
		next()
	}
    }
github apollographql / apollo-server / src / apolloServer.js View on Github external
addResolveFunctionsToSchema(executableSchema, resolvers || {});
        addMockFunctionsToSchema({
          schema: executableSchema,
          mocks: myMocks,
          preserveResolvers: true,
        });
      } else {
        // this is just basics, makeExecutableSchema should catch the rest
        // TODO: should be able to provide a GraphQLschema and still use resolvers
        // and connectors if you want, but at the moment this is not possible.
        if (schema instanceof GraphQLSchema) {
          if (logger) {
            addErrorLoggingToSchema(schema, logger);
          }
          if (printErrors) {
            addErrorLoggingToSchema(schema, { log: (e) => console.error(e.stack) });
          }
          if (!allowUndefinedInResolve) {
            addCatchUndefinedToSchema(schema);
          }
          executableSchema = schema;
          if (resolvers) {
            addResolveFunctionsToSchema(executableSchema, resolvers);
          }
        } else {
          if (!resolvers) {
            // TODO: test this error
            throw new Error('resolvers is required option if mocks is not provided');
          }
          executableSchema = makeExecutableSchema({
            typeDefs: schema,
            resolvers,
github apollographql / apollo-server / src / apolloServer.js View on Github external
addResolveFunctionsToSchema(executableSchema, resolvers);
          }
        } else {
          if (!resolvers) {
            // TODO: test this error
            throw new Error('resolvers is required option if mocks is not provided');
          }
          executableSchema = makeExecutableSchema({
            typeDefs: schema,
            resolvers,
            connectors,
            logger,
            allowUndefinedInResolve,
          });
          if (printErrors) {
            addErrorLoggingToSchema(executableSchema, { log: (e) => console.error(e.stack) });
          }
        }
      }

      // Tracer-related stuff ------------------------------------------------

      tracerLogger = { log: undefined, report: undefined };
      if (tracer) {
        tracerLogger = tracer.newLoggerInstance();
        tracerLogger.log('request.info', {
          headers: req.headers,
          baseUrl: req.baseUrl,
          originalUrl: req.originalUrl,
          method: req.method,
          httpVersion: req.httpVersion,
          remoteAddr: req.connection.remoteAddress,