Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion packages/gitbook/openNext/customWorkers/middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,37 @@ export { DOQueueHandler } from '../../.open-next/.build/durable-objects/queue.js

export { DOShardedTagCache } from '../../.open-next/.build/durable-objects/sharded-tag-cache.js';

//Format used by the tail logger
const formatLog = (requestDuration, responseCode, responseCache, responseRoute) =>
`%${JSON.stringify({ requestDuration, responseCode, responseCache, responseRoute })}%[main] Response Done`;

const getResolvedRoute = (reqOrResp, defaultValue) => {
try {
const resolvedRoutes = JSON.parse(
reqOrResp.headers.get('x-opennext-resolved-routes') ?? ''
)[0].route;
return resolvedRoutes ?? defaultValue;
} catch {
return defaultValue;
}
};

export default class extends WorkerEntrypoint {
async fetch(request) {
return runWithCloudflareRequestContext(request, this.env, this.ctx, async () => {
const startTime = Date.now();
// - `Request`s are handled by the Next server
const reqOrResp = await middlewareHandler(request, this.env, this.ctx);
if (reqOrResp instanceof Response) {
const duration = Date.now() - startTime;
const logMessage = formatLog(
duration,
reqOrResp.status,
reqOrResp.headers.get('x-opennext-cache') ?? 'MISS',
getResolvedRoute(reqOrResp, 'middleware')
);
// biome-ignore lint/suspicious/noConsole: <explanation>
console.log(logMessage);
return reqOrResp;
}

Expand All @@ -22,12 +47,22 @@ export default class extends WorkerEntrypoint {
'Cloudflare-Workers-Version-Overrides',
`gitbook-open-v2-${this.env.STAGE}="${this.env.WORKER_VERSION_ID}"`
);
return this.env.DEFAULT_WORKER?.fetch(reqOrResp, {
const response = await this.env.DEFAULT_WORKER?.fetch(reqOrResp, {
redirect: 'manual',
cf: {
cacheEverything: false,
},
});
const formatedLog = formatLog(
Date.now() - startTime,
response.status,
`SERVER-${response.headers.get('x-nextjs-cache') ?? 'MISS'}`,
getResolvedRoute(reqOrResp, 'unresolved')
);
// biome-ignore lint/suspicious/noConsole: <explanation>
console.log(formatedLog);

return response;
}
// If we are in preview mode, we need to send the request to the preview URL
const modifiedUrl = new URL(reqOrResp.url);
Expand Down