Graphql-yoga: Ability / documentation to add Apollo Engine

Created on 21 Nov 2017  Â·  26Comments  Â·  Source: dotansimha/graphql-yoga

There is a rather lengthy list of steps to add Apollo Engine to an Apollo Express server. I think this is a great opportunity to abstract those steps into something much easier to implement.

arereadme

Most helpful comment

I've implemented apollo engine with graphql yoga, following changes are required to make it work right now:

    const server = new GraphQLServer({ ... });

    const engine = new Engine({
        engineConfig: { apiKey: process.env.APOLLO_ENGINE_KEY },
        endpoint: '/',
        graphqlPort: parseInt(process.env.Port, 10) || 4000,
    })
    engine.start();

    server.express.use(engine.expressMiddleware());

Here is working demo:
https://github.com/playerx/graphql-yoga-sample

All 26 comments

Can you provide a pointer to the lengthy list? or you suggesting a change in the api or better documentation. plz clarify

All of the above. If Apollo Engine is added to make it easier to setup, then documentation needs to be added for that.

For reference, the instructions to setup Apollo Engine with Apollo Server (which graphql-yoga is using) are documented here

I've implemented apollo engine with graphql yoga, following changes are required to make it work right now:

    const server = new GraphQLServer({ ... });

    const engine = new Engine({
        engineConfig: { apiKey: process.env.APOLLO_ENGINE_KEY },
        endpoint: '/',
        graphqlPort: parseInt(process.env.Port, 10) || 4000,
    })
    engine.start();

    server.express.use(engine.expressMiddleware());

Here is working demo:
https://github.com/playerx/graphql-yoga-sample

I have added an example to the examples folder using Apollo Engine.

Just a note to say that Engine API has been replaced and now throws the following error:

As of apollo-engine 1.x, the Engine class has been replaced with a simpler API. See https://www.apollographql.com/docs/engine/1.0-migration.html to learn how to migrate.

I had a brief look, but I couldn't figure out how to integrate with the new ApolloEngine API.

Same problem here, seems that Engine is deprecated in favor of ApolloEngine I've not yet figured out how to integrate it with graphql-yoga

Me too. Waiting to see some solution.

due to Engine is deprecated, I used ApolloEngineLuncher as proxy to work with graphql-yoga according to the official docs, hope for help.

I've attempted to use the Apollo Engine with GraphQL with the ApolloEngineLauncher as @haoliangwu recommended:

const { ApolloEngineLauncher } = require('apollo-engine')

...

const launcher = new ApolloEngineLauncher({
        apiKey: process.env.APOLLO_ENGINE_KEY,  
        origins: [{
            http: { url: 'http://localhost:4000/graphql' }
        }],
        frontends: [{
            port: 3000,
            endpoints: ['/graphql'],
        }]
    })

    await launcher.start()

When I run the app locally I see these console logs when my GraphQL Yoga API starts.

INFO[0000] Started HTTP server.                          address="[::]:3000"
INFO[0000] Engine proxy started.                         build=2018.04-2-g43a64f6b7 version=1.0.5
graph service running - http://localhost:4000

The issue is, when I make queries of either http://localhost:3000/graphql or http://locahost:4000 from the playground, I do not see anything on engine.apollographql.com. It just says:

No data
Try adjusting time range or resetting filters.

Actually, the above code works. I'm not sure where the hiccup was, but today I noticed that I have data in Apollo Engine.

@MoonTahoe do you mind posting the rest of the code you use to setup the server and engine together? I've got it setup, but I'm not seeing any data on the Apollo engine site.

@c316 feel free to check out an example in https://github.com/graphcool/graphql-yoga/pull/209. More specifically, examples/apollo-engine/index.js.

That code uses the latest Apollo Engine, which is what you might want to go for anyway. The disadvantage, however, is that the example does not work in the "official" graphql-yoga yet. Nevertheless, you can temporary install @fabien0102/graphql-yoga and replace it back with graphql-yoga once the PR is approved. A discussion in https://github.com/graphcool/graphql-yoga/pull/209 should help you figure out the details of what's going on.

@kachkaev thanks

Should this also work with Prisma?

I've used the branch you mentioned in place of graphql-yoga and I'm getting an error.

const httpServer = graphQLServer.createHttpServer({
^

TypeError: graphQLServer.createHttpServer is not a function
at Object. (/Users/bobby/Dev/coffee-admin/server/src/index.js:30:34)
at Module._compile (internal/modules/cjs/loader.js:654:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
at Module.load (internal/modules/cjs/loader.js:566:32)
at tryModuleLoad (internal/modules/cjs/loader.js:506:12)
at Function.Module._load (internal/modules/cjs/loader.js:498:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:695:10)
at startup (internal/bootstrap/node.js:201:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:516:3)

And here is my code

const { GraphQLServer } = require('@fabien0102/graphql-yoga');
const { ApolloEngine } = require('apollo-engine');
const { Prisma } = require('prisma-binding');
const resolvers = require('./resolvers');
const { directiveResolvers } = require('./resolvers/DirectiveResolvers');

const prisma = new Prisma({
  typeDefs: 'src/generated/prisma.graphql',
  endpoint: process.env.PRISMA_ENDPOINT, // the endpoint of the Prisma DB service (value is set in .env)
  secret: process.env.PRISMA_SECRET, // taken from database/prisma.yml (value is set in .env)
  debug: true, // log all GraphQL queries & mutations
});

const graphQLServer = new GraphQLServer({
  typeDefs: 'src/schema.graphql',
  resolvers,
  context: req => ({
    ...req,
    db: prisma,
  }),
  directiveResolvers,
});

const port = parseInt(process.env.PORT, 10) || 4000;

const engine = new ApolloEngine({
  apiKey: process.env.APOLLO_ENGINE_KEY,
});

const httpServer = graphQLServer.createHttpServer({
  tracing: true,
  cacheControl: true,
});

engine.listen(
  {
    port,
    httpServer,
    graphqlPaths: ['/graphql'],
  },
  () =>
    console.log(`Server with Apollo Engine is running on http://localhost:${port}`)
);

Also, here are my related dependencies

  "dependencies": {
    "@fabien0102/graphql-yoga": "^1.9.0",
    "apollo-engine": "^1.1.0",

@c316 can you try const httpServer = server.configure({? I just checked my own code and found out that this is what I was currently using. We renamed configure() to createHttpServer() recently and this was not reflected in @fabien0102/graphql-yoga.

@fabien0102 could you please release v1.9.1 of your fork with with createHttpServer() instead of configure()? Perhaps, keeping configure() as an alias would be a good thing (only in the fork). But to be honest I hope this won't be needed because #209 simply gets merged. 🤞

I will do this tomorrow morning (GMT +1) ;) I was also hoping for the merge :)

@kachkaev That fixed the error, but I'm not seeing any data in the Engine UI.

@c316 a quick checklist:

  • Did you set up ENGINE_API_KEY environment variable before starting the server?
  • Do you see ‘Server with Apollo Engine is running on port XYZ’ in stdout?
  • Is the rest of stdout clear? (i.e. no errors from Engine saying it can't connect etc.)

You can have a look at my WIP integration with Apollo Engine 1.0, also based on @fabien0102/graphql-yoga. I'm waiting for #209 to be merged to finally close a PR in my pet project.

@kachkaev

Thanks for helping me trace down the problem here. It turns out I needed to change the graphqlPaths to graphqlPaths: ['/'],, which is where the project's endpoint default is.

For anyone else getting here from a search, you might look at the endpoint in the .graphqlconfig.yml file and then the "endpoints: default: ..."

@c316 and @kachkaev -> @fabien0102/[email protected] published (finally it's a breaking change for my fork, due to the createSubscriptionServer part ;) ) cf #209 :wink:

Migration guide between @fabien0102/[email protected] to @fabien0102/[email protected] :

  • rename graphQLServer.configure to graphQLServer.createHttpServer
  • remove the graphQLServer.createSubscriptionServer part (it's now internal)

Working example: https://github.com/fabien0102/graphql-yoga/blob/feature/apollo-engine-upgrade/examples/apollo-engine/index.js

Note: if you use TypeScript, you need explicitly type the output of createHttpServer into http.Server (cf https://github.com/apollographql/apollo-engine-js/pull/174#issuecomment-382647441)

@fabien0102 given that casting httpServer to Server will be always necessary, could you please add these comments to your #209 example?

// import { Server } from "http"; // TypeScript users only

engine.listen(
    {
      port: env.PORT,
      httpServer,
      // httpServer: httpServer as Server, // TypeScript users only
      graphqlPaths: [env.ENDPOINT_PATH],
    },
    () => {...}
);

Alternatively, you can add these instructions to the example's README. Otherwise, just seeing a TypeScript error and not having any guidance may drain someone's time to investigate it.

@kachkaev I will try to investigate to understand why typescript is not following here (the perfect solution is to have the correct output type regarding if you pass options = {https: {...}} or not) otherwise I will probably add a warn in the README ;)

Another option should be to add a real typescript example, but it's not really fit with the other examples available on this repository.

@fabien0102 by when can this be officially released.

@hereisnaman Good question! My PR #209 is ready, and I'm just waiting as you ;) after my npm fork is available if you have any needs (it strictly following the semver rules, so I'm on the v3.0.0 ^^)

Okay, thanks for the work. I am currently using your fork.

As #209 was merged including a new example, this issue can be closed now.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

woss picture woss  Â·  5Comments

marktani picture marktani  Â·  5Comments

2wce picture 2wce  Â·  4Comments

CaptainChemist picture CaptainChemist  Â·  4Comments

ahmedosama5200 picture ahmedosama5200  Â·  4Comments