Ok, so currently I have User’s and Chat’s as well as a Subscription schema that joins them.
Then when I’m querying in this case chats, I can add extra info like this (I’m getting the user_id
out of the context
):
query
|> add_current_user_is_subscribed(user_id)
...
Here’s what those functions look like:
def add_current_user_is_subscribed(%Ecto.Query{from: %{source: {_, Chat}}} = q, nil), do: q
def add_current_user_is_subscribed(%Ecto.Query{from: %{source: {_, Chat}}} = q, user_id) do
from(c in q,
left_join: cs in Subscription,
on: cs.chat_id == c.id and cs.user_id == ^user_id,
select_merge: %{
current_user_is_subscribed: not is_nil(cs.id)
}
)
end
This works fine if I’m directly querying Chats, but if I’m querying a User, and getting their associated subscribed_chats. It doesn’t work. Because Chat
is no longer the source.
query CurrentUser {
currentUser {
..
subscribedChats {
currentUserIsSubscribed <- my add_current_user_is_subscribed function no longer works here, because the soure of the query is now User, not Chat.
}
}
}
since currentUserIsSubscribed
is a virtual field, and never gets populated in this case, it just returns nil. Yes, I’m aware this is a contrived example, because by default a user would be subscribed to everything present in subscribed_chats
, but I’d still like that correct bool there, because it’s being used on the front-end to change wording/display/etc.
My next line of thinking was to have dataloader handle doing this querying, but I can’t figure out how to pass the user_id
from context
down to dataloader.
If this was the only place it was an issue, I could probably deal with it, but I have quite a few things like this: userLiked, userReported, userSaved, userHid, etc. so I’d like the most elegant solution to populating this data accurately and efficiently.
Any advice?