Currently I got his in my Controller:
@Crud({
model: {
type: Broker
},
query: {
join: {
user: {
eager: true,
exclude: ['password']
}
}
}
})
@Controller('broker')
@UseGuards(AuthGuard('jwt'))
export class BrokerController {
constructor(public service: BrokerService) {}
}
There is a one to many
relation between user and broker. I am authenticating the users by a jwt token and I need to filter the data on the id of the user. Is there any way to do this through the Crud configuration?
In my case Broker entity is plant, so in Plant controller I have the following in order to get current user related entities and to get associated automatically on creation:
@CrudAuth({
property: 'user',
filter: (user) => ({ owner: user.userId }),
persist: (user) => ({ owner: user.userId }),
})
Enabling TypeORM debug i can see that while POST works perfectly, when retrieving data seems it adds a .id
to the underlying query performed by crud library:
SELECT `Plant`.`createdAt` AS `Plant_createdAt`, `Plant`.`updatedAt` AS
`Plant_updatedAt`, `Plant`.`id` AS `Plant_id`, `Plant`.`name` AS
`Plant_name`, `Plant`.`location` AS `Plant_location`, `Plant`.`power` AS
`Plant_power`, `Plant`.`ownerId` FROM `plant` `Plant` WHERE
(`Plant`.`ownerId.id` = '5605c0f6-4817-4ae1-9364-e341140b5182')
^
^
The insert query has not appended that ".id". Why is doing that at select time??
I also add those entities definition to give more clues about my case:
Plant:
@Entity()
export class Plant extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column({
nullable: true,
default: 0,
})
power: number;
@ManyToOne((type) => User, (user) => user.plants)
owner: User;
}
User
@Entity()
export class User extends BaseEntity {
@PrimaryColumn()
id: string; //id comes from external authentication platform
@Column()
firstName: string;
@Column()
lastName: string;
@Column({ default: true })
isActive: boolean;
@OneToMany((type) => Plant, (plant) => plant.owner)
plants: Plant[];
}
As responded before by @ilker:
@CrudAuth({
property: 'user',
filter: (user) => ({
userid: user.userid,
})
})
This will get the "user" from the JWT token, and you can use it to filter the entities.
@nestsjx/crud is very great library.
Regards
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With