fix(metadata): keep a subclass's decorators off its base class (GitHub #44)
record in params.ts read the argument map with Reflect.getMetadata, which walks the prototype chain, then pushed into the list it got back and defined that same object on the subclass. On a subclass with no metadata of its own, that object was the base class's, so a @query on Child.list also showed up in getArgs(Base, 'list'). routeDecorator in metadata.ts had the same pattern with the routes array, so a @Get on a subclass was also served by the base controller. It is the same bug in the same shape, so it is fixed here too. Both now write a copy onto the decorated class: a shallow copy of the map and a new list for the method in params.ts, a new array in metadata.ts. getMetadata returns the class's own metadata once it has some, so later decorators on that class copy its own data, not the base's. A subclass still starts from what it inherits, as before. The other decorators in metadata.ts (@Provider, @Step, @Route, @Module, @Transformer, @Html) define a fresh value per class or per method and never mutate what they read, so they are unaffected. Refs: GitHub #44 Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
5 files changed
+51
-5
No files matched your search
+2
-1
@@ -124,7 +124,8 @@ export type RouteDecorator = (
|
||||
function routeDecorator(method: HttpMethod, transport: Transport): RouteDecorator {
|
||||
return (path, opts) => (target, propertyKey) => {
|
||||
const ctor = target.constructor;
|
||||
const routes = (Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? [];
|
||||
// A copy, as in `record` (params.ts): the inherited array belongs to the base class (GitHub #44).
|
||||
const routes = [...((Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? [])];
|
||||
routes.push({
|
||||
method,
|
||||
path,
|
||||
|
||||
+4
-4
@@ -31,10 +31,10 @@ const ARGS = Symbol('gt:args');
|
||||
function record(target: object, methodKey: string | symbol | undefined, spec: ArgSpec): void {
|
||||
if (methodKey === undefined) return; // constructor params not supported
|
||||
const ctor = target.constructor as Ctor;
|
||||
const map: Record<string, ArgSpec[]> = Reflect.getMetadata(ARGS, ctor) ?? {};
|
||||
const list = map[String(methodKey)] ?? [];
|
||||
list.push(spec);
|
||||
map[String(methodKey)] = list;
|
||||
// Copy, never mutate (GitHub #44): `getMetadata` walks the prototype chain, so on a subclass the
|
||||
// map and list it returns are the base class's, and pushing into them decorated the base too.
|
||||
const map: Record<string, ArgSpec[]> = { ...(Reflect.getMetadata(ARGS, ctor) ?? {}) };
|
||||
map[String(methodKey)] = [...(map[String(methodKey)] ?? []), spec];
|
||||
Reflect.defineMetadata(ARGS, map, ctor);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user