Skip to content

Commit

Permalink
fix: id can only be applied once
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanhaticus committed Nov 7, 2024
1 parent 6a7fda7 commit 282713e
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
18 changes: 18 additions & 0 deletions __tests__/decorators/id.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,24 @@ describe('`Id`', () => {
[idSymbol]: key,
});
});

it('should throw an error if the id symbol is already set in the metadata', () => {
const key = chance.string();
const metadata = {
[idSymbol]: chance.string(),
};

try {
Id()(undefined, {
name: key,
metadata,
} as ClassFieldDecoratorContext);
} catch (error) {
expect(error.message).toBe(
`Id() can only be applied once per class. Unable to denote ${key} as an id because ${metadata[idSymbol]} is already an id.`,
);
}
});
});

describe('when the given key is not valid', () => {
Expand Down
8 changes: 7 additions & 1 deletion src/decorators/id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,11 @@ export const Id =
return;
}

metadata[idSymbol] ??= name;
if (metadata[idSymbol] !== undefined) {
throw new Error(
`Id() can only be applied once per class. Unable to denote ${name} as an id because ${metadata[idSymbol]} is already an id.`,
);
}

metadata[idSymbol] = name;
};

0 comments on commit 282713e

Please sign in to comment.