简体   繁体   中英

Apollo Server Express + Subscriptions error

I am working on a Express backend project ( Apollo Server + Express + GraphQL ) and its frontend part is made with React.

I wanted to make a number changes in the frontend according to the database changes. For instance, when a user is created. I was reading a couple of documents till arrived on Apollo documentation regarding React subscriptions .

Then I have read Apollo Boost migration to set up client manually because it didn't support subscriptions. Then I moved forward till setting up Express to support subscriptions but my code didn't work.

This is the error I get in console:

app.use(process.env.GRAPHQL_PATH, _bodyParser["default"].json(), (0, _apolloServerExpress.graphqlExpress)({

TypeError: (0 , _apolloServerExpress.graphqlExpress) is not a function at Object. (C:\\Web\\backend\\src/index.js:83:5)

This is the line 83: graphqlExpress({ schema }) , I made a comment in the right of it below.

First of all I had my Express like this:

import cors from 'cors';
import express from 'express';
import jwt from 'jsonwebtoken';
import mongoose from 'mongoose';
import { ApolloServer, AuthenticationError } from 'apollo-server-express';
import errorMessages from './mensajes/errors.json';
require('dotenv').config();

import schemas from './schemas';
import resolvers from './resolvers';

import userModel from './models/usuario';

const app = express();

app.use(cors());

const getUser = async (req) => {
    const token = req.headers.token;

    if (token) {
        try {
            return await jwt.verify(token, process.env.JWT_SECRET);
        } catch (e) {
            throw new AuthenticationError(mensajesError.sesionExpirada);
        }
    }
};

const server = new ApolloServer({
    typeDefs: schemas,
    resolvers,
    context: async ({ req }) => {
        if (req) {
            const me = await getUser(req);

            return {
                me,
                models: {
                    userModel
                },
            };
        }
    }
});

server.applyMiddleware({ app, path: process.env.GRAPHQL_PATH });

const options = { 
    useNewUrlParser: true, 
    useUnifiedTopology: true, 
    useCreateIndex: true 
};

app.listen(process.env.PORT, () => {
    console.clear();
    mongoose.connect('mongodb://.../sandbox', options)
    .then(() => {
        console.log(`Database and server running on port ${process.env.PORT}`);
    })
    .catch(error => {
        console.error(`The server or the database cannot start:`);
        console.error(error);
    });
});

Then I have changed my code according to the previous Apollo documentation to:

import { graphqlExpress } from 'apollo-server-express';
import { createServer } from 'http';
import { execute, subscribe } from 'graphql';
import { PubSub } from 'graphql-subscriptions';
import { SubscriptionServer } from 'subscriptions-transport-ws';
require('dotenv').config();

import schema from './schemas';
import resolvers from './resolvers';

import userModel from './models/usuario';

const app = express();

app.use(
    process.env.GRAPHQL_PATH,
    bodyParser.json(),
    graphqlExpress({ schema }) // <-- Line 83
);

const pubsub = new PubSub();
const server = createServer(app);

server.listen(process.env.PORT, () => {
    new SubscriptionServer({
        execute,
        subscribe,
        schema,
    }, {
        server,
        path: '/subscriptions'
    });
});

Of course there is a lot of information missing but I still have to understand this, I guess. Do you understand that error? Any comments are appreciated.

I tried to do it as well with subscriptions-transport-ws but it didn't work because of this issue .

Here is a configuration that works for me.

const http = require('http');
const { ApolloServer } = require('apollo-server-express');
const express = require('express');
const graphQlSchema = require("./graphql/schema");
const grapgQlResolvers = require("./graphql/resolvers");

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

const server = new ApolloServer({ 
  typeDefs: graphQlSchema, 
  resolvers: grapgQlResolvers,
});

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

const httpServer = http.createServer(app);
server.installSubscriptionHandlers(httpServer);

httpServer.listen(PORT, () => {
    console.log(`🚀 Server ready at http://localhost:${PORT}${server.graphqlPath}`)
    console.log(`🚀 Subscriptions ready at ws://localhost:${PORT}${server.subscriptionsPath}`)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM