Skip to content

Commit

Permalink
Import database in subscriptions example
Browse files Browse the repository at this point in the history
  • Loading branch information
okjulian committed Jun 3, 2018
1 parent 95b245f commit d68e13b
Showing 1 changed file with 27 additions and 2 deletions.
29 changes: 27 additions & 2 deletions manuscript/chapter-5.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,17 +120,18 @@ const {

const { addPin } = require("./index");
const { verify, authorize } = require("../authentication");
const database = require("../database");

const pubsub = new PostgresPubSub({
connectionString: `${process.env.DATABASE_URL}?ssl=true`
});

const resolvers = {
Query: {
pins: (_, __, { database }) => database("pins").select()
pins: () => database("pins").select()
},
Mutation: {
addPin: async (_, { pin }, { token, database }) => {
addPin: async (_, { pin }, { token }) => {
const [user] = await authorize(database, token);
const {
user: updatedUser,
Expand All @@ -153,6 +154,30 @@ const resolvers = {
module.exports = resolvers;
```

The final changes you need to make are in `src/server.js`. You need to add `subscriptions: true` to the Apollo Server constructor. You also need to check for the existence of `req` and `req.headers`, because subscriptions don't send a `req` object.

```js
const { ApolloServer } = require('apollo-server');

const schema = require('./schema');

const server = new ApolloServer({
schema,
context: async ({ req }) => {
const context = {};
if (req && req.headers && req.headers.authorization) {
context.token = req.headers.authorization;
}
return context;
},
subscriptions: true
});

server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
```

[Remix](https://glitch.com/edit/#!/remix/pinapp-subscriptions) if you need a working version of the subscriptions example.

Congratulations! You just implemented server side subscriptions. Now head over to your project's GraphQL Playground by clicking "Show".
Expand Down

0 comments on commit d68e13b

Please sign in to comment.