Skip to main content
Aviso eliminado Atraer atención por ComunidadBot
Recompensa finalizada sin una respuesta ganadora por ComunidadBot
se añadieron 3173 caracteres en el cuerpo
Origen Enlace
Enzo
  • 131
  • 7
  • 28
async function main() {
  //CONFIG
  config();
  const app = express();
  const PORT = Number(process.env.PORT) || 4000;
  const serverHTTP = createServer(app);

  //SERVER APOLLO
  const serverApollo = new ApolloServer({
    subscriptions: {
      path: "/subscriptions",
      onConnect: async (connectionParams: any) => {
        console.log("nuevo usuario conectado")
        const { authToken }: any = connectionParams;
        if (authToken) {
          const payload: any = decode(authToken);
          const user = await Models.Usuarios.findById(payload._id)
          return { Models, user };
        }
      },
    },
    schema: await buildSchema({
      resolvers: [
        AuthenticationResolver,
        UserResolver,
        PublicationResolver,
        FriendsResolver,
        //SUBCRIPTIONS
        PublicationSubscriptionResolver,
      ],
      authChecker: ({ context }) => {
        if (!context.user) return false;
        return true;
      },
      authMode: "null",
    }),
    context: async ({ req, res, connection }) => {
      if (connection) return connection.context;
      const token: any = req.headers.authorization;
      if (!token) return { req, res, Models };
      if (token) {
        const payload: any = decode(token);
        const user = await Models.Usuarios.findById(payload._id)
        return { req, res, Models, user };
      }
    }
  });

  serverApollo.applyMiddleware({ app });
  serverApollo.installSubscriptionHandlers(serverHTTP)

  serverHTTP.listen(PORT, async () => {
    console.log(`Server http://localhost:${PORT}${serverApollo.graphqlPath}`);
    console.log(`Subscriptions ws://localhost:${PORT}${serverApollo.subscriptionsPath}`);
  });
}

main();
async function main() {
  //CONFIG
  config();
  const app = express();
  const PORT = Number(process.env.PORT) || 4000;
  const serverHTTP = createServer(app);

  //SERVER APOLLO
  const serverApollo = new ApolloServer({
    subscriptions: {
      path: "/subscriptions",
      onConnect: async (connectionParams: any) => {
        console.log("nuevo usuario conectado")
        const { authToken }: any = connectionParams;
        if (authToken) {
          const payload: any = decode(authToken);
          const user = await Models.Usuarios.findById(payload._id)
          return { Models, user };
        }
      },
    },
    schema: await buildSchema({
      resolvers: [
        AuthenticationResolver,
        UserResolver,
        PublicationResolver,
        FriendsResolver,
        //SUBCRIPTIONS
        PublicationSubscriptionResolver,
      ],
      authChecker: ({ context }) => {
        if (!context.user) return false;
        return true;
      },
      authMode: "null",
    }),
    context: async ({ req, res, connection }) => {
      if (connection) return connection.context;
      const token: any = req.headers.authorization;
      if (!token) return { req, res, Models };
      if (token) {
        const payload: any = decode(token);
        const user = await Models.Usuarios.findById(payload._id)
        return { req, res, Models, user };
      }
    }
  });

  serverApollo.applyMiddleware({ app });
  serverApollo.installSubscriptionHandlers(serverHTTP)

  serverHTTP.listen(PORT, async () => {
    console.log(`Server http://localhost:${PORT}${serverApollo.graphqlPath}`);
    console.log(`Subscriptions ws://localhost:${PORT}${serverApollo.subscriptionsPath}`);
  });
}

main();
async function main() {
  //CONFIG
  config();
  const app = express();
  const PORT = Number(process.env.PORT) || 4000;
  const serverHTTP = createServer(app);

  //SERVER APOLLO
  const serverApollo = new ApolloServer({
    subscriptions: {
      path: "/subscriptions",
      onConnect: async (connectionParams: any) => {
        console.log("nuevo usuario conectado")
        const { authToken }: any = connectionParams;
        if (authToken) {
          const payload: any = decode(authToken);
          const user = await Models.Usuarios.findById(payload._id)
          return { Models, user };
        }
      },
    },
    schema: await buildSchema({
      resolvers: [
        AuthenticationResolver,
        UserResolver,
        PublicationResolver,
        //SUBCRIPTIONS
        PublicationSubscriptionResolver,
      ],
      authChecker: ({ context }) => {
        if (!context.user) return false;
        return true;
      },
      authMode: "null",
    }),
    context: async ({ req, res, connection }) => {
      if (connection) return connection.context;
      const token: any = req.headers.authorization;
      if (!token) return { req, res, Models };
      if (token) {
        const payload: any = decode(token);
        const user = await Models.Usuarios.findById(payload._id)
        return { req, res, Models, user };
      }
    }
  });

  serverApollo.applyMiddleware({ app });
  serverApollo.installSubscriptionHandlers(serverHTTP)

  serverHTTP.listen(PORT, async () => {
    console.log(`Server http://localhost:${PORT}${serverApollo.graphqlPath}`);
    console.log(`Subscriptions ws://localhost:${PORT}${serverApollo.subscriptionsPath}`);
  });
}

main();
se añadieron 3173 caracteres en el cuerpo
Origen Enlace
Enzo
  • 131
  • 7
  • 28

si necesitan mas info, con gusto lo agregare.

voy agregar mi configuraciones de apollo:

  1. servidor

async function main() {
  //CONFIG
  config();
  const app = express();
  const PORT = Number(process.env.PORT) || 4000;
  const serverHTTP = createServer(app);

  //SERVER APOLLO
  const serverApollo = new ApolloServer({
    subscriptions: {
      path: "/subscriptions",
      onConnect: async (connectionParams: any) => {
        console.log("nuevo usuario conectado")
        const { authToken }: any = connectionParams;
        if (authToken) {
          const payload: any = decode(authToken);
          const user = await Models.Usuarios.findById(payload._id)
          return { Models, user };
        }
      },
    },
    schema: await buildSchema({
      resolvers: [
        AuthenticationResolver,
        UserResolver,
        PublicationResolver,
        FriendsResolver,
        //SUBCRIPTIONS
        PublicationSubscriptionResolver,
      ],
      authChecker: ({ context }) => {
        if (!context.user) return false;
        return true;
      },
      authMode: "null",
    }),
    context: async ({ req, res, connection }) => {
      if (connection) return connection.context;
      const token: any = req.headers.authorization;
      if (!token) return { req, res, Models };
      if (token) {
        const payload: any = decode(token);
        const user = await Models.Usuarios.findById(payload._id)
        return { req, res, Models, user };
      }
    }
  });

  serverApollo.applyMiddleware({ app });
  serverApollo.installSubscriptionHandlers(serverHTTP)

  serverHTTP.listen(PORT, async () => {
    console.log(`Server http://localhost:${PORT}${serverApollo.graphqlPath}`);
    console.log(`Subscriptions ws://localhost:${PORT}${serverApollo.subscriptionsPath}`);
  });
}

main();
  1. Este es el cliente

const wsLink = new WebSocketLink({
uri: "ws://localhost:4000/subscriptions",
  options: {
    reconnect: true,
    connectionParams: {
      authToken: localStorage.getItem("access_token")
    }
  }
});

const httpLink = createHttpLink({
  uri: "http://localhost:4000/graphql"
})

const authLink = setContext((_, { headers }) => {
  const token = localStorage.getItem("access_token");
  return {
    headers: {
      ...headers,
      Authorization: token ? token : "",
    }
  }
});

const splitLink = split(
  ({ query }) => {
    const definition = getMainDefinition(query);
    return (
      definition.kind === 'OperationDefinition' &&
      definition.operation === 'subscription'
    );
  },
  wsLink,
  authLink.concat(httpLink),
);

const Client = new ApolloClient({
  link: splitLink,
  cache: new InMemoryCache()
});

export default Client

si necesitan mas info, con gusto lo agregare

si necesitan mas info, con gusto lo agregare.

voy agregar mi configuraciones de apollo:

  1. servidor

async function main() {
  //CONFIG
  config();
  const app = express();
  const PORT = Number(process.env.PORT) || 4000;
  const serverHTTP = createServer(app);

  //SERVER APOLLO
  const serverApollo = new ApolloServer({
    subscriptions: {
      path: "/subscriptions",
      onConnect: async (connectionParams: any) => {
        console.log("nuevo usuario conectado")
        const { authToken }: any = connectionParams;
        if (authToken) {
          const payload: any = decode(authToken);
          const user = await Models.Usuarios.findById(payload._id)
          return { Models, user };
        }
      },
    },
    schema: await buildSchema({
      resolvers: [
        AuthenticationResolver,
        UserResolver,
        PublicationResolver,
        FriendsResolver,
        //SUBCRIPTIONS
        PublicationSubscriptionResolver,
      ],
      authChecker: ({ context }) => {
        if (!context.user) return false;
        return true;
      },
      authMode: "null",
    }),
    context: async ({ req, res, connection }) => {
      if (connection) return connection.context;
      const token: any = req.headers.authorization;
      if (!token) return { req, res, Models };
      if (token) {
        const payload: any = decode(token);
        const user = await Models.Usuarios.findById(payload._id)
        return { req, res, Models, user };
      }
    }
  });

  serverApollo.applyMiddleware({ app });
  serverApollo.installSubscriptionHandlers(serverHTTP)

  serverHTTP.listen(PORT, async () => {
    console.log(`Server http://localhost:${PORT}${serverApollo.graphqlPath}`);
    console.log(`Subscriptions ws://localhost:${PORT}${serverApollo.subscriptionsPath}`);
  });
}

main();
  1. Este es el cliente

const wsLink = new WebSocketLink({
uri: "ws://localhost:4000/subscriptions",
  options: {
    reconnect: true,
    connectionParams: {
      authToken: localStorage.getItem("access_token")
    }
  }
});

const httpLink = createHttpLink({
  uri: "http://localhost:4000/graphql"
})

const authLink = setContext((_, { headers }) => {
  const token = localStorage.getItem("access_token");
  return {
    headers: {
      ...headers,
      Authorization: token ? token : "",
    }
  }
});

const splitLink = split(
  ({ query }) => {
    const definition = getMainDefinition(query);
    return (
      definition.kind === 'OperationDefinition' &&
      definition.operation === 'subscription'
    );
  },
  wsLink,
  authLink.concat(httpLink),
);

const Client = new ApolloClient({
  link: splitLink,
  cache: new InMemoryCache()
});

export default Client
etiquetas editadas
Enlace
Jorgesys
  • 111.1k
  • 14
  • 55
  • 134
título editado
Enlace
Enzo
  • 131
  • 7
  • 28
Loading
Aviso añadido Atraer atención por Enzo
Recompensa iniciada por un valor de 150 de reputación por Enzo
título editado
Enlace
Enzo
  • 131
  • 7
  • 28
Loading
se añadieron 48 caracteres en el cuerpo
Origen Enlace
Enzo
  • 131
  • 7
  • 28
Loading
Origen Enlace
Enzo
  • 131
  • 7
  • 28
Loading