Skip to content

Instantly share code, notes, and snippets.

@AugustoCalaca
Last active March 26, 2021 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AugustoCalaca/76ad8e49bc6313bc4f6c969c71dabdc0 to your computer and use it in GitHub Desktop.
Save AugustoCalaca/76ad8e49bc6313bc4f6c969c71dabdc0 to your computer and use it in GitHub Desktop.
How to filter who might receive a subscription
import { NotificationSentModel } from '@entities';
import { GraphQLID, GraphQLNonNull } from 'graphql';
// import { subscriptionWithClientId } from 'graphql-relay-subscription';
import { withFilter } from 'graphql-subscriptions';
import { fromGlobalToId, subscriptionObjectType } from './utils';
import pubSub, { EVENTS } from '../../../pubSub';
import NotificationSentType from '../NotificationSentType';
const subscriptionAsyncIterator = () => pubSub.asyncIterator(EVENTS.NOTIFICATION.SENT);
const subscriptionFilter = (root, args) => {
const meUserId = fromGlobalToId(args.meUserId);
// @TODO - improve the asymptotic complexity
return root.toUsersIds.some((id) => id === meUserId);
};
const CreatedNotificationSubscription = subscriptionObjectType({
name: 'NotificationSentSubscription',
description: 'Subscribe notification and publish event to all or specific users',
inputFields: {
meUserId: {
type: GraphQLNonNull(GraphQLID),
},
},
outputFields: {
notificationSent: {
type: NotificationSentType,
},
},
subscribe: withFilter(subscriptionAsyncIterator, subscriptionFilter),
getPayload: async ({ notification }, input) => {
const meUserId = fromGlobalToId(input.meUserId);
const notificationSent = await NotificationSentModel().getNotificationSentToUser(notification.id, meUserId);
return { notificationSent };
},
});
export default CreatedNotificationSubscription;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment