0

我正在使用 Apollo Angular 和 .net core 来尝试完成订阅,我让它在 Playground 中工作,但在 Angular 应用程序中失败,收到此错误missing field 'baseNotificationAdded' while writing result {}

这是我在操场上的订阅

    subscription OnNotificationAdded($userId: Guid!) {
  baseNotificationAdded(userId: $userId) {
    body
    date
    htmlTemplate
    id
    isRead
    method
    roleType
    timeActive
    title
    type
    userId
  }
}

多变的

{ "userId": "aeebddaf-a00a-4f64-b6ca-13711a46745b"}

阿波罗配置角度

const cache = new InMemoryCache();
const notificationsUri = 'https://localhost:44367';
const notificationUriSubscription = 'wss://localhost:44367';
basenotificationssubscriptions: {
      // <-- this settings will be saved by name: products
      cache,
      link: split(({query}) => {
          const data = getMainDefinition(query);
          return (
            data.kind === 'OperationDefinition' && data.operation === 'subscription'
          );
        },
        new WebSocketLink({
          uri: `${notificationUriSubscription}/api/basenotificationssubscriptions/graphql` ,
          options: {
            reconnect: true,
          }
        }),
        httpLink.create({ uri: `${notificationsUri}/api/basenotificationssubscriptions/graphql` } ),
      )
    }

订阅:

public subscribeToAddNotification(userId: string): void {
    const ADD_BASE_NOTIFICATION_SUBSCRIPTION = gql`
      subscription OnNotificationAdded($userId: Guid!){
        baseNotificationAdded(userId: $userId){
             body,
             date,
             htmlTemplate,
             id,
             isRead,
             method,
             roleType,
             timeActive,
             title,
             type,
             userId
        }
      }
    `;
    this.apolloBaseBaseNotification.subscribe<any>({
      query: ADD_BASE_NOTIFICATION_SUBSCRIPTION,
      variables: {
        userId
      }
    }).subscribe(({ data }) => {
        console.log('got data ', data);
      },
      (error) => {
        console.log('there was an error sending the query', error);
      });
    // this.addNotificationQuery.subscribeToMore({
    //   document: ADD_BASE_NOTIFICATION_SUBSCRIPTION,
    //   variables: {
    //     userId
    //   },
    //   updateQuery: (prev, {subscriptionData}) => {
    //     if (!subscriptionData.data) {
    //       return prev;
    //     }
    //
    //     const notifications = subscriptionData.data.baseNotificationAdded;
    //
    //     return {
    //       ...prev,
    //       result: {
    //         notifications: [notifications, ...prev.result.notifications]
    //       }
    //     };
    //     // const data = subscriptionData.data.baseNotificationAdded;
    //     // console.log(data);
    //   },
    //   onError: (e) => {
    //     console.log(e);
    //   }
    // });
  }

在服务器端:订阅模式:

public class BaseNotificationSubscription : ObjectGraphType
    {
        private readonly BaseNotificationData _repositoryBaseNotification;

        public BaseNotificationSubscription(BaseNotificationData repositoryBaseNotification)
        {
            _repositoryBaseNotification = repositoryBaseNotification;
            Name = "BaseNotificationSubscription";

            AddField(new EventStreamFieldType
            {
                Name = "baseNotificationAdded",
                Type = typeof(ListGraphType<BaseNotificationType>),
                Arguments = new QueryArguments(
                    new QueryArgument<NonNullGraphType<GuidGraphType>> { Name = "userId" }
                ),
                Resolver = new FuncFieldResolver<List<BaseNotification>>(ResolveAllNotification),
                Subscriber = new EventStreamResolver<List<BaseNotification>>(SubscribeAll)
            });

            //AddField(new EventStreamFieldType
            //{
            //    Name = "baseNotificationAdded",
            //    Type = typeof(ListGraphType<BaseNotificationType>),
            //    Arguments = new QueryArguments(
            //        new QueryArgument<NonNullGraphType<GuidGraphType>> { Name = "userId" }
            //    ),
            //    Resolver = new FuncFieldResolver<BaseNotification>(ResolveNotification),
            //    Subscriber = new EventStreamResolver<BaseNotification>(Subscribe)
            //});

            //AddField(new EventStreamFieldType
            //{
            //    Name = "baseNotificationIsNotRead",
            //    Type = typeof(BaseNotificationType),
            //    Resolver = new FuncFieldResolver<BaseNotification>(ResolveNotification),
            //    Subscriber = new EventStreamResolver<BaseNotification>(SubscribeByIsRead)
            //});

            AddField(new EventStreamFieldType
            { 
                Name = "baseNotificationGetAll",
                Type = typeof(ListGraphType<BaseNotificationType>),
                Resolver = new FuncFieldResolver<List<BaseNotification>>(context => context.Source as List<BaseNotification>),
                Arguments = new QueryArguments(
                    new QueryArgument<NonNullGraphType<GuidGraphType>> { Name = "userId" }
                ),
                Subscriber = new EventStreamResolver<List<BaseNotification>>(context => repositoryBaseNotification.BaseNotificationObservableGetAll())
            });
        }

        private BaseNotification ResolveNotification(IResolveFieldContext context)
        {
            var message = context.Source as BaseNotification;

            return message;
        }

        private List<BaseNotification> ResolveAllNotification(IResolveFieldContext context)
        {
            var message = context.Source as List<BaseNotification>;

            return message;
        }

        private IObservable<BaseNotification> Subscribe(IResolveEventStreamContext context)
        {
            var userId = context.GetArgument<Guid>("userId");

            return _repositoryBaseNotification.BaseNotificationObservable().Where(notification => notification.UserId == userId);
        }

        private IObservable<List<BaseNotification>> SubscribeAll(IResolveEventStreamContext context)
        {
            var userId = context.GetArgument<Guid>("userId");

            return _repositoryBaseNotification.BaseNotificationObservableGetAll();
        }

        //private IObservable<BaseNotification> SubscribeByIsRead(IResolveEventStreamContext context)
        //{
        //    var id = context.GetArgument<string>("isRead");

        //    var messages = _repositoryBaseNotification.BaseNotificationObservable();
        //    return messages.Where(message => !message.IsRead);
        //}
    }

数据:

public class BaseNotificationData
    {
        private readonly ApplicationContext _context;
        private readonly ISubject<BaseNotification> _onBaseNotificationChange = new ReplaySubject<BaseNotification>(1);
        private readonly ISubject<List<BaseNotification>> _allNotifications = new ReplaySubject<List<BaseNotification>>(1);
        public ConcurrentStack<BaseNotification> AllBaseNotifications { get; }

        public BaseNotificationData(ApplicationContext context)
        {
            _context = context;
            AllBaseNotifications = new ConcurrentStack<BaseNotification>();
        }

        public async Task<BaseNotification> CreateNotification(SendBaseNotification notificationToSend)
        {
            try
            {
                var mongoDbHelper = new MongoDBNotificationHelper(_context);
                var notification = await mongoDbHelper.BuildBaseNotificationFromUI(notificationToSend.UserId, notificationToSend.Type);
                AllBaseNotifications.Push(notification);
                _onBaseNotificationChange.OnNext(notification);
                _allNotifications.OnNext(GetNotifications((Guid)notification.UserId));
                return notification;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void CheckForDistributionUI(BaseNotification notification)
        {
            try
            {
                var mongoDbHelper = new MongoDBNotificationHelper(_context);
                mongoDbHelper.RouteForEmailSenderTwilio(notification);
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        public List<BaseNotification> GetNotifications(Guid userId, int daysOld = 15, int size = 5)
        {
            try
            {
                var result = new List<BaseNotification>();
                var builder = Builders<BaseNotification>.Filter;
                var date = DateTime.UtcNow.AddDays(-Convert.ToDouble(daysOld));
                var filter = builder.Eq(widget => widget.UserId, userId) & builder.Gte(widget => widget.Date, date);
                var notifications = _context._mongoDBNotificationService.FindByFilter(filter);

                if (notifications.Count > size)
                {
                    result = notifications.GetRange(0, size);
                }
                else
                {
                    result = notifications;
                }
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public BaseNotification DeleteNotifications(Guid notificationId)
        {
            try
            {
                var builder = Builders<BaseNotification>.Filter;
                var filter = builder.Eq(widget => widget.Id, notificationId);
                var notification = _context._mongoDBNotificationService.FindByFilter(filter).FirstOrDefault();
                if (notification != null)
                {
                    _context._mongoDBNotificationService.Remove(notificationId);
                    _onBaseNotificationChange.OnNext(notification);
                    _allNotifications.OnNext(GetNotifications((Guid)notification.UserId));
                }
               
                return notification;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        public BaseNotification MarkAsRead(Guid notificationId, bool isRead)
        {
            try
            {
                var builder = Builders<BaseNotification>.Filter;
                var filter = builder.Eq(widget => widget.Id, notificationId);
                var notification = _context._mongoDBNotificationService.FindByFilter(filter).FirstOrDefault();
                if (notification != null)
                {
                    notification.IsRead = isRead;
                    _context._mongoDBNotificationService.Update(filter, notification);
                    _onBaseNotificationChange.OnNext(notification);
                    _allNotifications.OnNext(GetNotifications((Guid)notification.UserId));
                }
               
                return notification;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        public IObservable<BaseNotification> BaseNotificationObservable()
        {
            return _onBaseNotificationChange.Select(notification =>
            {
                return notification;
            }).AsObservable();
        }

        public IObservable<List<BaseNotification>> BaseNotificationObservableGetAll()
        {
            return _allNotifications.Select(notification =>
            {
                return notification.Where(l => !l.IsRead).ToList();
            }).AsObservable();
        }

        public void AddError(Exception exception)
        {
            _onBaseNotificationChange.OnError(exception);
        }
    }

突变:

public class BaseNotificationMutation : ObjectGraphType
    {
        public BaseNotificationMutation(BaseNotificationData repositoryBaseNotification)
        {

            FieldAsync<BaseNotificationType>(
                "sendSystemNotification",
                arguments: new QueryArguments(
                    new QueryArgument<NonNullGraphType<SendBaseNotificationInputType>> { Name = "sendSystemNotificationRequest" }
                ),
                resolve: async context =>
                {
                    var notificationToInsert = context.GetArgument<SendBaseNotification>("sendSystemNotificationRequest");
                    return await repositoryBaseNotification.CreateNotification(notificationToInsert);
                });}}

提醒一下,在 Playground 中运行良好,但在 Angular 应用程序中却没有,出现此错误:missing field while writing result {}

我的想法用完了,任何帮助都会非常受欢迎

4

0 回答 0