Skip to content

Commit fbaf20e

Browse files
committed
Stop admin server listening for unused events
This now subscribes to only the Mockttp events that the remote client is interested in, which allows the server to skip some processing of irrelevant events, in the same way it works for local-only client usage.
1 parent 70dde84 commit fbaf20e

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

src/admin/mockttp-admin-model.ts

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -111,15 +111,27 @@ export function buildAdminServerModel(
111111
ruleParams
112112
};
113113

114-
for (let [gqlName, eventName] of graphqlSubscriptionPairs) {
115-
mockServer.on(eventName as any, (evt) => {
116-
pubsub.publish(eventName, { [gqlName]: evt });
117-
});
118-
}
114+
// Build a set of event publishing callbacks (but don't subscribe them yet - we only
115+
// want to subscribe on demand, to allow the server to opt-out unused event processing).
116+
const eventListeners = graphqlSubscriptionPairs.reduce((acc, [, eventName]) => {
117+
acc[eventName] = (evt: any) => {
118+
pubsub.publish(eventName, { [eventName]: evt });
119+
};
120+
return acc;
121+
}, {} as { [eventName: string]: (...args: any[]) => void });
119122

120123
const subscriptionResolvers = Object.fromEntries(graphqlSubscriptionPairs.map(([gqlName, eventName]) => ([
121124
gqlName, {
122-
subscribe: () => pubsub.asyncIterator(eventName)
125+
subscribe: () => {
126+
// Subscribe to the underlying server event, if we haven't already. Needs to actively check
127+
// currently listeners because reset() clears all listeners, so they may disappear any time.
128+
if (mockServer.listenerCount(eventName, eventListeners[eventName]) === 0) {
129+
mockServer.on(eventName as any, (evt) => {
130+
pubsub.publish(eventName, { [gqlName]: evt });
131+
});
132+
}
133+
return pubsub.asyncIterator(eventName);
134+
}
123135
}
124136
])));
125137

src/server/mockttp-server.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,10 @@ export class MockttpServer extends AbstractMockttp implements Mockttp {
363363
return Promise.resolve();
364364
}
365365

366+
public listenerCount(event: string, listener?: Function): number {
367+
return this.eventEmitter.listenerCount(event, listener);
368+
}
369+
366370
private announceBodyDataAsync(
367371
type: 'request' | 'response',
368372
id: string,

0 commit comments

Comments
 (0)