I am working on a small project with microservices architecture in Spring Boot. As to not make unnecessary calls to users-microservice, I have duplicated some necessary User data (id, name, summary, photo) also into the posts-microservice, by having an Entity named UserExt ('external').
The posts-microservice contains these Entities:
@Table(name = "posts")
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// the table that holds the id of the User that made the Post. Used the wording 'ext' for External, to differentiate the
// data that is not in this microservice (or database, but for simplicity I use 1 DB, even though each microservice,
// uses its own set of tables). However, since it would be inefficient to call users microservice to retrieve user data when
// building a post response, we also store some crucial user data in this ms as well.
@ManyToOne
@JoinColumn(name = "user_ext", referencedColumnName = "id", nullable = false)
private UserExt userExt;
// --- other post related fields
}
@Table(name = "user_ext")
public class UserExt {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, name = "user_id_ext")
private Long userIdExt;
@Column(nullable = false, name = "user_email_ext")
private String userEmail;
@Column(name = "first_name", nullable = false)
private String firstName;
@Column(name = "last_name", nullable = false)
private String lastName;
@Column(name = "short_summary")
private String shortSummary;
@Column(name = "profile_photo")
private String profilePhoto;
}
The issue I am facing is this:
If I chose to use POST /posts to create a new post, the client will not need to give any ID and I can get the username/email of the currently authenticated user to identify the user that the created post belongs to. However, this way, unless I make a call to users-microservice, I will not be able to get the userId. One way would be to only store the email/username of the user in the UserExt entity. However, this would be an issue with the below scenario.
Another scenario: If GET /users/userId/posts is used to get all the posts of a certain user and I only store the username/email of user in the UserExt, how would I be able to satisfy this case.
What would be the best way to handle these cases?