Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: ensure asyncIterator call return() when fail at calling next() #447

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/__tests__/server.ts
Expand Up @@ -1740,6 +1740,44 @@ describe('Subscribe', () => {
fail("Shouldn't have received a message");
}, 20);
});

it('should execute "return" of the subscription when error occurs in "next" call', async (done) => {
const iterator = (async function* () {
yield { data: { greetings: 'Hi' } };
throw new Error('error');
})();

jest.spyOn(iterator, 'return').mockImplementation(done);

const { url } = await startTServer({
schema,
subscribe: () => iterator,
});

const client = await createTClient(url);
client.ws.send(
stringifyMessage<MessageType.ConnectionInit>({
type: MessageType.ConnectionInit,
}),
);

await client.waitForMessage(({ data }) => {
expect(parseMessage(data).type).toBe(MessageType.ConnectionAck);
client.ws.send(
stringifyMessage<MessageType.Subscribe>({
id: '1',
type: MessageType.Subscribe,
payload: {
operationName: 'Greetings',
query: `subscription Greetings {
greetings
}`,
variables: {},
},
}),
);
});
});
});

describe('Disconnect/close', () => {
Expand Down
4 changes: 4 additions & 0 deletions src/server.ts
Expand Up @@ -824,6 +824,10 @@ export function makeServer<
// completed the subscription, he doesnt need to be reminded
await emit.complete(id in ctx.subscriptions);
} finally {
// before delete the subcription, we should call `return` of asyncIterator to prevent it from hanging
const sub = ctx.subscriptions[id];
if (isAsyncGenerator(sub)) await sub.return(undefined);

// whatever happens to the subscription, we finally want to get rid of the reservation
delete ctx.subscriptions[id];
}
Expand Down