prisma-client-go
prisma-client-go copied to clipboard
IsNull + IfPresent
Hey! Hit a use-case that doesn't seem to be covered by the API.
So I have a post model with a deletedAt
nullable date, for soft-delete/restore capabilities.
My query originally had db.Post.DeletedAt.IsNull()
in the listing query but now I want to make this optional based on an argument being passed in, so certain actors have the ability to view deleted content.
There isn't a db.Post.DeletedAt.IsNull
variant that permits optionality (i.e. if some value is true) so this became quite awkward.
My solution is a little odd but it works:
// showDeletedPosts bool - if true, show deleted posts in the result
db.Post.DeletedAt.AfterEqualsIfPresent(timeOrNil(!showDeletedPosts))
Where timeOrNil
is a function that returns either a nil timestamp or now:
func timeOrNil(x bool) *time.Time {
if x {
t := time.Now()
return &t
}
return nil
}
The idea is that if you pass true, it returns a timestamp and filters out posts by asking for posts where deletedAt
is after now (which is impossible, you can't delete posts from the future!) so it filters out deleted posts. Otherwise, the result is nil so the filter isn't applied to the query.
Is there a better way to do this? If not, would be a great one to add!
Thanks.
Thanks for the elaborate description. I don't think there is a better way to do it right now. Glad to hear that you at least found a workaround 😅
Are you suggesting to add something like DeletedAt.HasValue(true|false)
, where true would query for deleted_at IS NOT NULL
and false deleted_at IS NULL
?
Yeah pretty much that! Thanks!