Skip to content

Commit

Permalink
Better types
Browse files Browse the repository at this point in the history
  • Loading branch information
timfish committed Jul 31, 2024
1 parent 4037f04 commit ab99d51
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions packages/nextjs/src/server/cache-instrumentation.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { startSpan } from '@sentry/node';
// We need to import `* as` due to Rollup cjs interop issues
import * as iitm from 'import-in-the-middle';
import type { HookFn } from 'import-in-the-middle';

type CacheHandlerClass = {
new (options: unknown): CacheHandlerClass;
Expand All @@ -10,18 +9,28 @@ type CacheHandlerClass = {
revalidateTag(tag: string): Promise<void>;
};

function looksLikeCacheHandlerClass(obj: unknown): obj is CacheHandlerClass {
return (
typeof obj === 'function' && typeof obj.prototype === 'object' && 'get' in obj.prototype && 'set' in obj.prototype
);
}

/**
* Hooks the loading of the cache handler module at the `cacheHandlerPath` and wraps the class to add cache spans around
* the get and set methods.
*/
export function enableCacheInstrumentation(cacheHandlerPath: string): void {
// We only hook the specific path of the cache handler module
new iitm.Hook([cacheHandlerPath], ((exports: { default: CacheHandlerClass }) => {
new iitm.Hook([cacheHandlerPath], exports => {
if (!looksLikeCacheHandlerClass(exports.default)) {
return;
}

// Grab the existing default export which should be the user defined cache handler
const UserCache = exports.default;

// Define a new class that extends the user defined cache handler
class CacheHandler extends UserCache {
class SentryCacheHandlerWrapper extends UserCache {
public constructor(options: unknown) {
super(options);
}
Expand Down Expand Up @@ -56,6 +65,6 @@ export function enableCacheInstrumentation(cacheHandlerPath: string): void {
}

// Overwrite the default export with the new CacheHandler class
exports.default = CacheHandler;
}) as unknown as HookFn);
exports.default = SentryCacheHandlerWrapper;
});
}

0 comments on commit ab99d51

Please sign in to comment.