Skip to content

Commit

Permalink
fix(aws-amplify): destroyAmplifyServerContext may not be called
Browse files Browse the repository at this point in the history
  • Loading branch information
HuiSF committed Nov 22, 2023
1 parent b877493 commit b1552f6
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ describe('runWithAmplifyServerContext', () => {
mockCreateAmplifyServerContext.mockReturnValueOnce(mockContextSpec);
});

afterEach(() => {
mockDestroyAmplifyServerContext.mockReset();
});

it('should run the operation with the context', () => {
const mockOperation = jest.fn();
runWithAmplifyServerContext(
Expand All @@ -45,7 +49,7 @@ describe('runWithAmplifyServerContext', () => {
expect(mockOperation).toHaveBeenCalledWith(mockContextSpec);
});

it('should destroy the context after the operation', async () => {
it('should destroy the context after the operation completed', async () => {
const mockOperation = jest.fn();
await runWithAmplifyServerContext(
mockAmplifyConfig,
Expand All @@ -63,6 +67,29 @@ describe('runWithAmplifyServerContext', () => {
);
});

it('should destroy the context when the operation throws', async () => {
const testError = new Error('some error');
const mockOperation = jest.fn();
mockOperation.mockRejectedValueOnce(testError);

await expect(
runWithAmplifyServerContext(
mockAmplifyConfig,
{
Auth: {
tokenProvider: mockTokenProvider,
credentialsProvider: mockCredentialAndIdentityProvider,
},
},
mockOperation
)
).rejects.toThrow(testError);

expect(mockDestroyAmplifyServerContext).toHaveBeenCalledWith(
mockContextSpec
);
});

it('should return the result returned by the operation callback function', async () => {
const mockResultValue = {
url: 'http://123.com',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,12 @@ export const runWithAmplifyServerContext: AmplifyServer.RunOperationWithContext
);

// run the operation with injecting the context
const result = await operation(contextSpec);
try {
const result = await operation(contextSpec);

destroyAmplifyServerContext(contextSpec);

return result;
return result;
} finally {
// ensures destroy the context regardless whether the operation succeeded or failed
destroyAmplifyServerContext(contextSpec);
}
};

0 comments on commit b1552f6

Please sign in to comment.