How to use apollo-server - 10 common examples

To help you get started, we’ve selected a few apollo-server 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 lXSPandora / apollo-server-boilerplate / src / index.js View on Github external
(async () => {
  try {
    const info = await connectDatabase();
    console.log(`Connected to mongodb 🍃 at ${info.host}:${info.port}/${info.name}`);
  } catch (error) {
    console.error('Unable to connect to database');
    process.exit(1);
  }
  const server = new ApolloServer({
    resolvers: globalResolvers,
    typeDefs: globalQuery,
    // user authentication
    context: async ({ req }) => {
      const token = req.headers.authorization ? req.headers.authorization : '';
      const { user } = await getUser(token);
      return {
        user,
      };
    },
    tracing: true,
  });
  const graphqlPort = 3000;
  server.setGraphQLPath('graphql');
  server.listen(graphqlPort).then(({ url }) => {
    console.log(`🚀 Apollo server ready on ${url}`);
github arjunyel / angular-apollo-example / backend / src / index.ts View on Github external
// Increment likes on tweet, in real life you'd use a transaction!
        let tweetDoc = await tweetRef.get();
        const tweet = tweetDoc.data() as Tweet;
        await tweetRef.update({ likes: tweet.likes + 1 });

        tweetDoc = await tweetRef.get();
        return tweetDoc.data();
      } catch (error) {
        throw new ApolloError(error);
      }
    }
  }
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
  introspection: true
});

server.listen().then(({ url }) => {
  console.log(`🚀  Server ready at ${url}`);
});
github MichalLytek / type-graphql / examples / simple-subscriptions / index.ts View on Github external
async function bootstrap() {
  // Build the TypeGraphQL schema
  const schema = await buildSchema({
    resolvers: [SampleResolver],
  });

  // Create GraphQL server
  const server = new ApolloServer({
    schema,
    playground: true,
    // you can pass the endpoint path for subscriptions
    // otherwise it will be the same as main graphql endpoint
    // subscriptions: "/subscriptions",
  });

  // Start the server
  const { url } = await server.listen(4000);
  console.log(`Server is running, GraphQL Playground available at ${url}`);
}
github MichalLytek / type-graphql / examples / redis-subscriptions / index.ts View on Github external
// create Redis-based pub-sub
  const pubSub = new RedisPubSub({
    publisher: new Redis(options),
    subscriber: new Redis(options),
  });

  // Build the TypeGraphQL schema
  const schema = await buildSchema({
    resolvers: [RecipeResolver],
    validate: false,
    pubSub, // provide redis-based instance of PubSub
  });

  // Create GraphQL server
  const server = new ApolloServer({ schema });

  // Start the server
  const { url } = await server.listen(4000);
  console.log(`Server is running, GraphQL Playground available at ${url}`);
}
github nemanjam / rn-chat / server / src / data / resolvers.js View on Github external
const chat = await group.getChat();
          return Boolean(chat.id === payload.messageAdded.chatId);
        },
      ),
    },
    groupAdded: {
      subscribe: withFilter(
        () => pubsub.asyncIterator(GROUP_ADDED_TOPIC),
        (payload, args) => {
          // console.log(JSON.stringify(payload, null, 2));
          return Boolean(true /*args.userId === payload.groupAdded.userId*/);
        },
      ),
    },
    messageInGroupAdded: {
      subscribe: withFilter(
        () => pubsub.asyncIterator(MESSAGE_IN_GROUP_ADDED_TOPIC),
        (payload, args) => {
          console.log(JSON.stringify(payload, null, 2));
          return Boolean(
            true /*args.userId === payload.defaultGroupAdded.userId*/,
          );
        },
      ),
    },
  },

  Mutation: {
    async addFriend(_, { userId, friendId }, ctx) {
      const user = await UserModel.findOne({
        where: { id: userId },
      });
github venusdev85 / Vue-Express-Mongo / server / routes / graphql.js View on Github external
module.exports = function(app, db) {

	// Register graphql server
	app.use("/graphql", auth.isAuthenticatedOrApiKey, ApolloServer( (req) => {
		const query = req.query.query || req.body.query;
		if (query && query.length > 2000) {
			// None of our app's queries are this long
			// Probably indicates someone trying to send an overly expensive query
			throw new Error("Query too large.");
		}		

		return {
			graphiql: config.isDevMode(),
			pretty: config.isDevMode(),
			printErrors: config.isDevMode(),
			schema: Schema,
			resolvers: Resolvers,
			logger: { log: (e) => console.error(e.stack) },
			context: {
				user: req.user,
github feats / perfect-graphql-starter / server / index.js View on Github external
import express from 'express';
import bodyParser from 'body-parser';
import { apolloExpress, graphiqlExpress } from 'apollo-server';
import schema from '/domain/schemas';
import connectors from './connectors';
import resolvers from './resolvers';

// Initial fixtures
require('./fixtures').run(connectors.MongoDB.connect());

const PORT = 8080;
const app = express();

app.use('/graphql', bodyParser.json(), apolloExpress({
  schema,
  resolvers,
  context: {},
  formatError(error) {
    console.error(error.stack);
    return error;
  },
}));

app.use(
  '/graphiql',
  graphiqlExpress({
    endpointURL: '/graphql',
  })
);
github MichalLytek / type-graphql / examples / authorization / index.ts View on Github external
void (async function bootstrap() {
  // build TypeGraphQL executable schema
  const schema = await buildSchema({
    resolvers: [ExampleResolver],
    authChecker, // register auth checking function
  });

  // Create GraphQL server
  const server = new ApolloServer({
    schema,
    context: () => {
      const ctx: Context = {
        // create mocked user in context
        // in real app you would be mapping user from `req.user` or sth
        user: {
          id: 1,
          name: "Sample user",
          roles: ["REGULAR"],
        },
      };
      return ctx;
    },
  });

  // Start the server
github nusmodifications / nusmods / api / data / src / index.js View on Github external
function makeServer() {
  // enable hot-reload server side
  // eslint-disable-next-line global-require
  const graphqlSchema = require('./graphql').default;
  return new ApolloServer({
    typeDefs: graphqlSchema.typeDefs,
    /* Apollo is mutating resolvers */
    resolvers: { ...graphqlSchema.resolvers },
    playground: playgroundConfig,
    formatError: (error) => {
      log.error(error);
      return error;
    },
    formatResponse: (response) => {
      log.info(response);
      return response;
    },
  });
}
github LFSCamargo / Chatify / packages / server / src / server.ts View on Github external
import { ApolloServer, PubSub } from 'apollo-server';
import * as mongoose from 'mongoose';
import * as dotenv from 'dotenv';
import graphqlTypes from './graphqlTypes';
import resolvers from './resolvers';
import { getUser } from './auth/authMethods';
import { MongoError } from 'mongodb';

dotenv.config();

const pubsub = new PubSub();

const server = new ApolloServer({
  resolvers,
  typeDefs: graphqlTypes,
  // @ts-ignore
  context: async ({ req, connection }) => {
    if (connection) {
      return {
        ...connection.context,
        pubsub,
      };
    } else {
      // check from req
      const token = req.headers.authorization ? req.headers.authorization : '';
      const user = await getUser(token);
      return {