When working on my side project, I decided to implement a friend request system using NestJS + TypeORM for the backend. However, I encountered a peculiar issue where every time I tried to associate a Friend
entity with a specific user, the target
field of that Friend
entity would unexpectedly change to the user I was associating it with. Here's an example:
Before binding the Friend
entity to any user object, its initial state looked like this:
Friend {
id: '31466acb-749e-43f0-be82-4ec4c08d8ff5',
createdAt: 2023-03-04T04:35:23.576Z,
target: User {
id: 3,
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4132202f2534012e34352d2e2e2a6f222e2c">[email protected]</a>',
password: '$2a$10$/bVbxCmyFEfkPsqOvN0efePNLKYZjrFwfGJm1yTU3bICAS8q2MlcO',
username: 'sandu',
lastLoginAt: 2023-03-04T03:48:48.369Z,
socketId: null,
online: false
}
}
However, after linking it to the user samzhangjy
, the entity transformed into:
Friend {
id: '31466acb-749e-43f0-be82-4ec4c08d8ff5',
createdAt: 2023-03-04T04:35:23.576Z,
target: User {
id: 1,
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="295a4844534148474e435069465c5d45464642074a4644">[email protected]</a>',
password: '$2a$10$ibwq2hCq3pbzrEitlhEHjeP0H5wklkEmsjtQ.0ZMO3jLWOR4RhxXC',
username: 'samzhangjy',
lastLoginAt: 2023-02-25T04:28:29.079Z,
socketId: 'CDWGfFWCskfH-J3RAAAD',
online: true
}
}
This unexpected behavior led to incorrect results when querying the friend lists of users.
The code snippet below showcases my service logic for adding friends:
// Service code here
// ...
I attempted to utilize both QueryBuilder
and the .save
method as shown in the code, but unfortunately, neither approach resolved the issue.
For reference, here is the structure of the Friend
entity:
@Entity()
export class Friend {
// Entity properties and relationships
}
And here is the structure of the User
entity:
@Entity()
export class User {
// Entity properties and relationships
}
Aside from this perplexing error involving the Friend.target
property, everything else appears to be functioning correctly.
If anyone has insights or suggestions on how to address this issue, I would greatly appreciate the assistance. Thank you in advance!