This question is about best practices and design patterns; I'm sure i can go with any option depending on app, but i want to develop the backend up to best practices regardless of front app/client current needs are.
what is best practice to follow during API development when a certain resource has a one-many/many-many relation with another resource, is it okay to add columns from one resource into other to represent important column that i'm sure its mandatory needed ?
#Example Database may look like:-
Event{
id: 1,
user_id: 1
}
User:{
id: 1,
name: 'Momen',
}
Now to respond to GET /Post/1
## Option 1
Event{
id:1,
user_id:1,
user:{
id:1,
name: momen,
}
}
## Option 2
Events{
1: Event{
id:1,
user_id:1,
user_name: 'momen',// i will not include User object unless client request it.. but i will inject user_name because it's a data i'm sure that Post will always need
}
}
the User object in above example can be huge, and i don't want the whole user object, -unless app needs more info about the user- yet i still need his name to display in the list of Events. so is it okay to add this name to Event object as a fallback, so if client dont have access to User:1 in his memory, he can display this column while fetching User.
Q1 Is this acceptable or i'm polluting Object and introducing anomily bugs ?
in another case of Many-to-Many relation; I have a flag I want to set, should I set it on parent Entity or I have to include relation object as well.
EventUser{
event_id: 1,
user_id: 1,
}
Adding EventUsers
Link table which represents a one-many relation,
Q2. I want to set a flag next event that indicates if the user who is querying those events is going to this event or not.
so in a restful-API, to respond to GET /events/1
request i can
## option 1:
Event{
id:1,
name: 'Event 1',
is_going: true
}
## option 2
{
events:{ 1:{id:1, name:'Event 1'} },
EventUser:{1:{ event_id: 1, user_id: 1},} // or {} if not going
}
its clear that option1 is easier to implement and easier to deal with.. but this mean that again i'm introducing columns to Event Model that does not exists. plus if the client is going to cache such results for offline-first usage, and user changes then this data is simply wrong.