Skip to content

Commit

Permalink
fix tests and encoding error
Browse files Browse the repository at this point in the history
  • Loading branch information
Lms24 committed Nov 9, 2023
1 parent 32a7a04 commit 77fdc93
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
9 changes: 4 additions & 5 deletions packages/astro/src/server/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ export const handleRequest: (options?: MiddlewareOptions) => MiddlewareResponseH
},
async span => {
const originalResponse = await next();

if (span && originalResponse.status) {
span.setHttpStatus(originalResponse.status);
}
Expand All @@ -110,13 +111,11 @@ export const handleRequest: (options?: MiddlewareOptions) => MiddlewareResponseH
return originalResponse;
}

const { body, ...restOfOriginalResponse } = originalResponse;

// Type case necessary b/c the body's ReadableStream type doesn't include
// the async iterator that is actually available in Node
// We later on use the async iterator to read the body chunks
// see https://github.com/microsoft/TypeScript/issues/39051
const originalBody = body as NodeJS.ReadableStream | null;
const originalBody = originalResponse.body as NodeJS.ReadableStream | null;
if (!originalBody) {
return originalResponse;
}
Expand All @@ -126,13 +125,13 @@ export const handleRequest: (options?: MiddlewareOptions) => MiddlewareResponseH
for await (const chunk of originalBody) {
const html = typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk);
const modifiedHtml = addMetaTagToHead(html, hub, span);
controller.enqueue(modifiedHtml);
controller.enqueue(new TextEncoder().encode(modifiedHtml));
}
controller.close();
},
});

return new Response(newResponseStream, restOfOriginalResponse);
return new Response(newResponseStream, originalResponse);
},
);
return res;
Expand Down
9 changes: 7 additions & 2 deletions packages/astro/test/server/middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,15 +259,20 @@ describe('sentryMiddleware', () => {
url: new URL('https://myDomain.io/users/'),
};

const originalResponse = new Response('<p>no head</p>', {
const originalHtml = '<p>no head</p>';
const originalResponse = new Response(originalHtml, {
headers: new Headers({ 'content-type': 'text/html' }),
});
const next = vi.fn(() => Promise.resolve(originalResponse));

// @ts-expect-error, a partial ctx object is fine here
const resultFromNext = await middleware(ctx, next);

expect(resultFromNext).toBe(originalResponse);
expect(resultFromNext?.headers.get('content-type')).toEqual('text/html');

const html = await resultFromNext?.text();

expect(html).toBe(originalHtml);
});
});

Expand Down

0 comments on commit 77fdc93

Please sign in to comment.