How to use the apollo-server-express.ApolloServer function in apollo-server-express

To help you get started, we’ve selected a few apollo-server-express 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 gatsbyjs / api.gatsbyjs.org / src / graphql / server.js View on Github external
if (process.env.NODE_ENV !== 'development') {
  // In production, make sure a valid token is present before doing anything.
  app.use(requireValidJWT);

  // If there’s an error, send it as JSON so it’s useful in the GraphQL output.
  app.use((err, _, res, next) => {
    if (err) {
      res.json(err);
    }

    next();
  });
}

// Set up the GraphQL server.
const server = new ApolloServer({
  typeDefs,
  resolvers,
  playground: process.env.NODE_ENV === 'development'
});

server.applyMiddleware({ app, cors: true });

// Turn the Express server into a lambda-compatible handler function.
const handler = serverless(app);

export const graphql = async (event, context) => {
  // Prevents Lambda cold starts
  if (event.source === 'serverless-plugin-warmup') {
    return 'Lambda is warm!';
  }
github gourmetjs / gourmet-ssr / tests / todo-apollo / lib / app.js View on Github external
module.exports = function(def) {
  const args = serverArgs(Object.assign({
    workDir: __dirname + "/..",
    outputDir: "../../.gourmet/todo-apollo"
  }, def));
  const app = express();

  const apollo = new ApolloServer({
    typeDefs: schema,
    dataSources() {
      return {todoData: new TodoData()};
    },
    resolvers
  });

  app.use(morgan("dev"));

  app.use((req, res, next) => {
    if (req.url === "/custom-graphql" && req.headers["x-gourmet-test-name"] !== "@gourmet/test-todo-apollo")
      next(Error("x-gourmet-test-name header error"));
    else
      next();
  });
github harmboschloo / graphql-to-elm / tests / test-browser / server.ts View on Github external
let mocks: { [type: string]: any } = {};

  if (typeDefs.includes("scalar Time")) {
    resolvers["Time"] = timeScalar;
    mocks["Time"] = () => Date.now();
  }

  const schema = makeExecutableSchema({
    typeDefs,
    resolvers,
    resolverValidationOptions: { requireResolversForResolveType: false }
  });

  addMockFunctionsToSchema({ schema, mocks });

  const server = new ApolloServer({
    schema,
    introspection: false,
    playground: false
  });

  const endpointURL = `/graphql/${id}`;

  app.use(endpointURL, bodyParser.json(), (req, resp, next) => {
    if (Array.isArray(req.body)) {
      req.body.forEach(setNamedQuery);
    } else {
      setNamedQuery(req.body);
      setNamedQuery(req.query);
    }
    next();
  });
github atherosai / graphql-gateway-apollo-express / server / server.js View on Github external
import express from 'express';
import { ApolloServer } from 'apollo-server-express';
import schema from './schema';

const app = express();
const PORT = 3000;
const dev = process.env.NODE_ENV === 'development';

const apolloServer = new ApolloServer({
  schema,
  playground: dev,
  engine: false,
});

apolloServer.applyMiddleware({ app, path: '/graphql' });

app.listen(PORT, () => {
  console.info(`\n\nExpress listen at http://localhost:${PORT} \n`);
});
github mizchi-sandbox / graphql-react-apollo-playground / server / index.ts View on Github external
import setup from './setup';
import { ApolloServer, gql } from 'apollo-server-express';
import express from 'express';
import fs from 'fs';
import path from 'path';
import { resolvers } from './resolvers';

const typeDefs = fs
  .readFileSync(path.join(__dirname, '../graphql/schema.graphql'))
  .toString();

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

const apolloServer = new ApolloServer({
  typeDefs: gql`
    ${typeDefs}
  `,
  resolvers: resolvers as any,
});

apolloServer.applyMiddleware({ app });

app.get('/', (req, res) => {
  res.send('It works');
});

setup().then(() => {
  app.listen(PORT, () => {
    console.log(`🚀 Server ready at http://localhost:3333`);
  });
github birkir / prime / packages / prime-core / src / routes / external / index.ts View on Github external
};
  } else if (Object.keys(inputs).length > 0) {
    queriesAndMutations.mutation = new GraphQLObjectType({
      name: 'Mutation',
      fields: inputs,
    });
  }

  queriesAndMutations.query = new GraphQLObjectType({
    name: 'Query',
    fields: realQueries,
  });

  const schema = new GraphQLSchema(queriesAndMutations);

  const server = new ApolloServer({
    introspection: true,
    tracing: true,
    schema,
    context: async ({ req }) => {
      try {
        const cookie = String(req.headers.cookie);
        const cookies = new Map(cookie.split(';').map(n => n.trim().split('=')) as any);

        if (req.headers['x-prime-version-id'] && req.headers['x-prime-version-id'].length === 36) {
          cookies.set('prime.versionId', req.headers['x-prime-version-id']);
        }

        const context: IContext = {
          settings,
          sequelizeDataLoader: createContext(sequelize),
          public: settings.accessType === 'public',
github fanout / apollo-serverless-demo / api / _lib / FanoutGraphqlExpressServer.ts View on Github external
mainDefinition.kind === "OperationDefinition" &&
          mainDefinition.operation === "mutation";
        return isMutation;
      };
      const isGripRequest = (request: express.Request) =>
        "grip-sig" in request.headers;
      const subscriptionsEnabledForRequest = (
        request: express.Request,
      ): boolean => {
        return isGripRequest(request) || requestIsGraphqlMutation(request);
      };
      const apolloServerConfig = createApolloServerConfig(
        subscriptionsEnabledForRequest(req),
        pubsub,
      );
      const apolloServer = new ApolloServer({
        ...apolloServerConfig,
        playground: {
          cdnUrl: "https://fanoutapp-files.sfo2.digitaloceanspaces.com",
          version: undefined,
        },
      });
      const apolloServerExpressApp = ApolloServerExpressApp(
        apolloServer,
        req.url,
      );
      return apolloServerExpressApp(req, res, next);
    });
github cleverbeagle / pup / startup / server / graphql.js View on Github external
import { ApolloServer } from 'apollo-server-express';
import { WebApp } from 'meteor/webapp';
import { getUser } from 'meteor/apollo';
import schema from './api';

const server = new ApolloServer({
  schema,
  context: async ({ req }) => ({
    user: await getUser(req.headers.authorization),
  }),
  uploads: false,
});

server.applyMiddleware({
  app: WebApp.connectHandlers,
  path: '/graphql',
});
github metaspace2020 / metaspace / metaspace / graphql / server.js View on Github external
async function createHttpServerAsync(config, connection) {
  let app = express();
  let httpServer = http.createServer(app);

  configureSentryRequestHandler(app);

  app.use(cors());
  app.use(compression());

  configureCronSchedule(connection.manager);

  app.use(bodyParser.json());
  configureSession(app);
  await configureAuth(app, connection.manager);

  const apollo = new ApolloServer({
    schema: executableSchema,
    context: ({req, res}) => getContext(req.user, connection.manager, req, res),
    playground: {
      settings: {
        'editor.theme': 'light',
        'editor.cursorShape': 'line',
      }
    },
    formatError: formatGraphQLError,
    introspection: true,
  });
  apollo.applyMiddleware({ app });

  configureSentryErrorHandler(app);

  app.use(function (err, req, res, next) {