-
Notifications
You must be signed in to change notification settings - Fork 25
How to write graphql subscriptions
veeramarni edited this page Jun 1, 2021
·
3 revisions
- Write Graphql Service
// services.graqphl
"""
Subscription event for timer
"""
enum TimeTrackerPubSubEvents {
TimeTrackerCreated
TimeTrackerUpdated
TimeTrackerConfigurationUpdate
}
// timerecord.graphql
extend type Subscription {
SubscribeToTimeTracker(orgNameFilter: string, userId: String): TimeRecord
}
// resolvers
import {withFilter} from 'graphql-subscriptions';
export const resolver = (options) => ({
....
Subscription: {
SubscribeToOrganizationContext: {
subscribe: withFilter(
() =>
options.pubsub.asyncIterator([
ITimeRecordPubSubEvents.TimeRecordCreated,
ITimeRecordPubSubEvents.TimeRecordUpdated,
]),
async (payload, variables, context: {}) =>
payload.SubscribeToOrganizationContext.orgId === variables.orgNameFilter &&
payload.SubscribeToOrganizationContext.userId === variables.userId,
),
},
},
})
/// service file
public async createTimeRecord(userId: string, orgId: string, request: ITimeRecordRequest) {
const data = await this.timeRecordRepository.createTimeRecord(userId, orgId, request);
this.pubsub.publish(ITimeRecordPubSubEvents.TimeRecordCreated, { SubscribeToTimeTracker: data });
return data;
}