Skip to content

Commit

Permalink
Fix property definition
Browse files Browse the repository at this point in the history
  • Loading branch information
timokoessler committed Dec 2, 2024
1 parent 3641448 commit 7b86177
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 14 deletions.
16 changes: 13 additions & 3 deletions library/helpers/wrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,19 @@ export function createWrappedFunction(
// .inspect("realpath", (args) => {...})
// We don't want to lose the original function's properties.
// Most of the functions we're wrapping don't have any properties, so this is a rare case.
for (const prop in original) {
if (original.hasOwnProperty(prop)) {
defineProperty(wrapped, prop, original[prop as keyof Function]);
// Inspired by https://github.com/DataDog/dd-trace-js/blob/master/packages/datadog-shimmer/src/shimmer.js#L8

Object.setPrototypeOf(wrapped, original);

const props = Object.getOwnPropertyDescriptors(original);
const keys = Reflect.ownKeys(props);

for (const key of keys) {
try {
// Define the property on the wrapped function, keeping the original property's attributes.
Object.defineProperty(wrapped, key as any, props[key as any]);
} catch (e) {
//

Check warning on line 54 in library/helpers/wrap.ts

View check run for this annotation

Codecov / codecov/patch

library/helpers/wrap.ts#L54

Added line #L54 was not covered by tests
}
}

Expand Down
23 changes: 12 additions & 11 deletions library/sources/express/wrapRequestHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,22 @@
import type { RequestHandler } from "express";
import { runWithContext } from "../../agent/Context";
import { contextFromRequest } from "./contextFromRequest";
import { createWrappedFunction } from "../../helpers/wrap";

export function wrapRequestHandler(handler: RequestHandler): RequestHandler {
const fn = function wrap(this: RequestHandler) {
if (arguments.length === 0) {
// @ts-expect-error Type of this
return handler.apply(this);
}
const fn = createWrappedFunction(handler, function wrap(handler) {
return function wrap(this: RequestHandler) {
if (arguments.length === 0) {
return handler.apply(this);
}

const context = contextFromRequest(arguments[0]);
const context = contextFromRequest(arguments[0]);

return runWithContext(context, () => {
// @ts-expect-error Type of arguments
return handler.apply(this, arguments);
});
};
return runWithContext(context, () => {
return handler.apply(this, arguments);
});
};
}) as RequestHandler;

// Some libraries/apps have properties on the handler functions that are not copied by our createWrappedFunction function
// (createWrappedFunction only copies properties when hasOwnProperty is true)
Expand Down

0 comments on commit 7b86177

Please sign in to comment.