从nestjs后端发送通知到redux工具包查询前端

问题描述 投票:0回答:1

如果用户收到关注请求,我想向他发送通知。我可以在后端看到通知消息,但我不知道为什么套接字不监听通知。这是实现 WebSockets RTK Query Websockets.

的链接

这是我的 RTK 查询设置

import { createApi } from "@reduxjs/toolkit/query/react";
import { baseQuery } from "./config";
import { io } from "socket.io-client";

export const user = createApi({
  endpoints: (builder) => ({
    getNotifications: builder.query({
      queryFn: () => {
        return {
          data: []
        }
      },
      async onCacheEntryAdded(
        arg, {
          updateCachedData,
          cacheDataLoaded,
          cacheEntryRemoved
        }
      ) {
        try {
          await cacheDataLoaded;

          const socket = io('http://localhost:8000', {
            withCredentials: true,
          });

          socket.on("notifications", (message) => {
            updateCachedData((draft) => {
              draft.push(message);
            });
          });

          const listener = (event: MessageEvent) => {
            const data = JSON.parse(event.data);

            updateCachedData((draft) => {
              draft.push(data);
            });
          };

          socket.on("notifications", listener);
        } catch {

        await cacheEntryRemoved;
      },
    }),
  }),
});

我的后端followRequest.service

async acceptFollowRequest(requestId: string) {
  //

  // Create follower relationship: sender follows receiver
  await this.prisma.follower.create({
    data: {
      followerId: senderId,
      followingId: receiverId,
    },
  });

  this.notificationsGateway.sendNotification({
    message: `Your follow request has been accepted by user ${receiverId}`,
    userId: senderId,
  });
}
}

这是我的通知网关

import {
  WebSocketGateway,
  WebSocketServer,
  OnGatewayConnection,
  OnGatewayDisconnect,
} from '@nestjs/websockets';
import {
  Server
} from 'socket.io';

@WebSocketGateway({
  cors: {
    origin: process.env.FRONTEND_URL,
    credentials: true,
  },
})
export class NotificationsGateway
implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer() server: Server;

  handleConnection() {}

  handleDisconnect() {}

  sendNotification(notification: {
    message: string;userId: string
  }) {
    this.server
      .to(notification.userId)
      .emit('notifications', notification.message);
    console.log(notification.message);
  }
}

这有效,因为您可以在我的后端控制台中看到通知

Backend console

sockets websocket react-redux socket.io redux-toolkit
1个回答
0
投票

这非常有效。这是我第一次使用 WebSockets,所以我认为它会在“网络”选项卡中发送有效负载。

© www.soinside.com 2019 - 2024. All rights reserved.