Apollo-server: Use Apollo Server internally within a function

Created on 21 Sep 2018  路  6Comments  路  Source: apollographql/apollo-server

Is it possible to run Apollo Server 2 within a function so that other logic code in the same function can 'post' queries/mutations to the Apollo Server part of the function?

Use case: We use Google Cloud Functions and have a function that needs to run some logic and periodically make requests to Apollo Server (we don't want to give it direct access to our database and this enforces set API logic). We don't want to split Apollo Server into its own function as then every time we make a request from the logic function to the Apollo Server function we would effectively be paying ~double and we would have to add extra authentication.

Most helpful comment

@itsezc hopefully you got it working. Below are some code examples if you didn't or for next person.

Given you have ./server.js such as:

import { ApolloServer, gql, makeExecutableSchema } from 'apollo-server'

const typeDefs = gql`
  type Query {
    users: [User!]!
  }
  type User {
    name: String
    username: String
  }
`;

const resolvers = {
  Query: {
    users() {
      return [{ name: 'Test', username: 'test' }];
    },
  },
};

export const schema = makeExecutableSchema({ typeDefs, resolvers });
export default new ApolloServer({ schema });

Then in ./consumer.js

import { graphql } from 'graphql';
import { schema } from './server.js';

const query = `
  query {
    users {
      name
      username
    }
  }
`;

graphql({ schema, source: query }).then(console.log);

You can pass in more options to graphql as sbrichardson describes above (such as variables) or visit latest docs at https://graphql.org/graphql-js/graphql/#graphql

Thanks to other contributors to this issue as it helped me to resolve my issue when wanting to consume a local graphql schema to build a static Next.js website.

All 6 comments

Check out this solution from StackOverflow:

GraphQL.js itself does not require a http server to run. express-graphql is just a helper to mount the query resolver to a http endpoint.

You can pass your schema and the query to graphql, it'll return a Promise that'll resolve the query to the data.

graphql(schema, query).then(result => {
  console.log(result);
});

Here's a copy of the comments from graphql.js source, showing how you can maintain passing
context etc with the direct approach.

/**
 * This is the primary entry point function for fulfilling GraphQL operations
 * by parsing, validating, and executing a GraphQL document along side a
 * GraphQL schema.
 *
 * More sophisticated GraphQL servers, such as those which persist queries,
 * may wish to separate the validation and execution phases to a static time
 * tooling step, and a server runtime step.
 *
 * Accepts either an object with named arguments, or individual arguments:
 *
 * schema:
 *    The GraphQL type system to use when validating and executing a query.
 * source:
 *    A GraphQL language formatted string representing the requested operation.
 * rootValue:
 *    The value provided as the first argument to resolver functions on the top
 *    level type (e.g. the query object type).
 * contextValue:
 *    The context value is provided as an argument to resolver functions after
 *    field arguments. It is used to pass shared information useful at any point
 *    during executing this query, for example the currently logged in user and
 *    connections to databases or other services.
 * variableValues:
 *    A mapping of variable name to runtime value to use for all variables
 *    defined in the requestString.
 * operationName:
 *    The name of the operation to use if requestString contains multiple
 *    possible operations. Can be omitted if requestString contains only
 *    one operation.
 * fieldResolver:
 *    A resolver function to use when one is not provided by the schema.
 *    If not provided, the default field resolver is used (which looks for a
 *    value or method on the source value with the field's name).
 */

Does this help?

@sbrichardson couldn't get this working with Apollo Server but appreciate the response

You can use ruhHttpQuery() to do this:

I'm using the following code under Express that provides context information as well as running the query:

         const contextValue = await server.createGraphQLServerOptions(req, res);

        runHttpQuery([req, res], {
            method: req.method,
            options: contextValue,
            query: {
                query: activeQuery.text,
                variables: { ...req.params, ...req.query },
            },
            request: convertNodeHttpToRequest(req)
        })
            .then(result => {
                res.setHeader('Content-Type', 'application/json');
                return res.send(result.graphqlResponse);
            })
            .catch(error => console.log(error));

Hopefully one of the solutions mentioned in this thread helped out. Closing - thanks!

@hwillson None of the solutions have worked so far, would you be able to reopen the issue thanks

@itsezc hopefully you got it working. Below are some code examples if you didn't or for next person.

Given you have ./server.js such as:

import { ApolloServer, gql, makeExecutableSchema } from 'apollo-server'

const typeDefs = gql`
  type Query {
    users: [User!]!
  }
  type User {
    name: String
    username: String
  }
`;

const resolvers = {
  Query: {
    users() {
      return [{ name: 'Test', username: 'test' }];
    },
  },
};

export const schema = makeExecutableSchema({ typeDefs, resolvers });
export default new ApolloServer({ schema });

Then in ./consumer.js

import { graphql } from 'graphql';
import { schema } from './server.js';

const query = `
  query {
    users {
      name
      username
    }
  }
`;

graphql({ schema, source: query }).then(console.log);

You can pass in more options to graphql as sbrichardson describes above (such as variables) or visit latest docs at https://graphql.org/graphql-js/graphql/#graphql

Thanks to other contributors to this issue as it helped me to resolve my issue when wanting to consume a local graphql schema to build a static Next.js website.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

disyam picture disyam  路  3Comments

veeramarni picture veeramarni  路  3Comments

manuelfink picture manuelfink  路  3Comments

hiucimon picture hiucimon  路  3Comments

leinue picture leinue  路  3Comments