I need to get context using websocket on appolo server

I need to get context using websocket on appolo server


0

Before I could get the context using startStandaloneServer but now I have to use a websecket and I’m not getting the token

how is the file server.Js

import { ApolloServer } from '@apollo/server';
import { createServer } from 'http';
import { expressMiddleware } from '@apollo/server/express4';
import express from 'express';
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { WebSocketServer } from 'ws';
import { useServer } from 'graphql-ws/lib/use/ws';
import { resolvers, typeDefs } from './src/graphql/modules/index.js';
import { startStandaloneServer } from '@apollo/server/standalone';
import jwt from 'jsonwebtoken';
import cors from 'cors';
import bodyParser from 'body-parser';
import { PubSub } from 'graphql-subscriptions';

const app = express();
const httpServer = createServer(app);

const schema = makeExecutableSchema({ typeDefs, resolvers });

const wsServer = new WebSocketServer({
  server: httpServer,
  path: '/graphql',
});

const serverCleanup = useServer(
  { schema,
    context: async (ctx, msg, args) => {
      console.log(ctx.extra.request.headers);
      return { ctx , pub };
    }
  },
  wsServer
);

const pub = new PubSub();

const server = new ApolloServer({
  schema,
  context: ({ req }) => ({ Property, User, currentUser: req.currentUser }),
  plugins: [
    ApolloServerPluginDrainHttpServer({ httpServer }),
    {
      async serverWillStart() {
        return {
          async drainServer() {
            await serverCleanup.dispose();
          },
        };
      },
    },
  ],
});

await server.start();
// context(async (req, res, next) => {
//   const token = req.headers['authorization'];
//   console.log(token);
//   if(token !== "null"){
//       try {
//           const currentUser = await jwt.decode(token, process.env.SECRET)
//           req.currentUser = currentUser
//       } catch(e) {
//           console.error(e);
//       }
//   }
//   next();
// });

app.all('/graphql', function (req, res, next){
  const token = req.headers.authorization.split(" ")[1] || '';
  
  req.token = token;

  if(token !== "null"){
    try {
      const currentUser = jwt.decode(token, process.env.SECRET)
    } catch(e) {
      console.error(e);
    }
  }

  next();
});

app.use('/graphql', cors(), bodyParser.json(), expressMiddleware(server));

httpServer.listen(4000);  


// const { url } = await startStandaloneServer(server, {
//   listen: { port: 4000 },
//   context: async ({ req, res }) => {
//     if (!req.headers.authorization){
//       return null;
//     }

//     const token = req.headers.authorization.split(" ")[1] || '';

//     if (!!token){
//       const user = jwt_decode(token);
//       return { user };
//     }

//     return null;
//   },
// }).then();

// console.log(url + 'graphql');


how is the file resolver.js

const resolvers = {
  Query : {
    notificacoesUsuario(_, args, contextValue){

      console.log(contextValue);

      if (!contextValue.user){
        throw new GraphQLError('User is not authenticated', {
          extensions: {
            code: 'UNAUTHENTICATED',
            https: { status: 401 },
          },
        });
      }
      
      return notificacaoDb.getByReceptor(contextValue.user.id);
    },

    visualizarNotificacao(_, { id }){
      return notificacaoDb.visualizarNotificacao(id);
    }
  },

  Notificacao: {
    data(args){
      return args.data.toISOString();
    },
  },

  Subscription: {
    notificacaoCriada: {
      subscribe: (_, {}, contex) => contex.pub.asyncIterator(['NOTIFICACAO_CRIADA'])
    }
  }
};

export default { resolvers };

I already tried using colors and searching chatGPT didn’t help much. It is not possible to startStandaloneServer and I don’t know how I do it anymore

1 Answer
1


0

I struggled with it today. There is a context in expressMiddleware

https://www.apollographql.com/docs/apollo-server/api/express-middleware/

  app.use(
    '/graphql',
    cors(),
    bodyParser.json(),
    expressMiddleware(server, {
      context: async ({ req, res }) => {
        if (!req.headers.authorization) {
          return null;
        }

        const token = req.headers.authorization.split(' ')[1] || '';

        if (!!token) {
          const user = jwt_decode(token);
          return { user };
        }

        return null;
      },
    })
  );



Leave a Reply

Your email address will not be published. Required fields are marked *