Reputation: 141
i am currently stuck on a problem, which i don't know how to propery solve:
In my NestJS application, I would like to make all my TypeORM Entities
extend a BaseEntity
class that provide some general features. For example, i would like to provide an additional getHashedID()
method that hashed (and therefore hides) the internal ID from my API customers.
Hashing is done by a HashIdService
, which provides an encode()
and decode()
method.
My setup looks like this (removed the Decorators for readability!):
export class User extends BaseEntity {
id: int;
email: string;
name: string;
// ...
}
export class BaseEntity {
@Inject(HashIdService) private readonly hashids: HashIdService;
getHashedId() {
return this.hashids.encode(this.id);
}
}
However, if i call the this.hashids.encode()
method, it throws an exception with:
Cannot read property 'encode' of undefined
How can i inject
a service into a entity/model
class? Is this even possible?
UPDATE #1
In particular, i would like to "inject" the HashIdService
into my Entities
. Further, the Entities
should have a getHashedId()
method that returns their hashed ID.. As i don't want to do this "over and over again", i would like to "hide" this method in the BaseEntity
as described above..
My current NestJS version is as follows:
Nest version:
+-- @nestjs/[email protected]
+-- @nestjs/[email protected]
+-- @nestjs/[email protected]
+-- @nestjs/[email protected]
+-- @nestjs/[email protected]
Thank you very much for your help!
Upvotes: 10
Views: 4140
Reputation: 789
If you don't need to inject the HashIdService
or mock it in a unit test you can simply do this:
BaseEntity.ts
import { HashIdService } from './HashIdService.ts';
export class BaseEntity {
public id: number;
public get hasedId() : string|null {
const hashIdService = new HashIdService();
return this.id ? hashIdService.encode(this.id) : null;
}
}
User.ts
export class User extends BaseEntity {
public email: string;
public name: string;
// ...
}
Then create your user:
const user = new User();
user.id = 1234;
user.name = 'Tony Stark';
user.email = '[email protected]';
console.log(user.hashedId);
//a1b2c3d4e5f6g7h8i9j0...
Upvotes: 2