lighthouse icon indicating copy to clipboard operation
lighthouse copied to clipboard

@can directive should have an opt-in method for whether it fails on null

Open JasonTheAdams opened this issue 5 years ago • 5 comments

What problem does this feature proposal attempt to solve?

Presently the @can directive uses findOrFail when retrieving the model(s) to run the $model->can() method over. This means that the following does not work:

type Query {
    query widget(id: ID!): Widget
        @can(ability: 'view', find: 'id')
}

Note that the Widget return type here is nullable. So it should just return null if no widget was found with that id. However, using the @can directive means that if no Widget is found is throws an exception — failing to return null.

Which possible solutions should be considered?

Adding a simple failOnNull attribute to the @can directive would suffice. For v4 it would be best to have it true by default since that's how it works. For v5 I think it makes more sense to have it false by default, as I think that's more intuitive. I wouldn't think a gate check would cause a failure; when there's nothing to check, a policy check is merely a moot point.

JasonTheAdams avatar Dec 16 '20 21:12 JasonTheAdams

I agree with the general sentiment and your proposal.

The name failOnNull is a bit ambiguous. How about we just forego finding another term to describe the concept and just call the argument findOrFail?

spawnia avatar Dec 17 '20 16:12 spawnia

I'm perfectly fine with that. 😄

JasonTheAdams avatar Dec 17 '20 17:12 JasonTheAdams

Hm, never noticed this behavior, but your proposal totally makes sense. @JasonTheAdams would you like to make a PR?

lorado avatar Dec 17 '20 17:12 lorado

@lorado I would love to make a PR... the reality is that I'm not sure when I'll have the time. I have one or two other Issues on here I still need to get around to. I'm the Lead Developer at my job, so when I'm not solving my problems I'm solving my teammates' problems. As such my time for contributing to OSS is more sparse than I wish it was.

We recently ran into this on our project, so I figured I'd at least make an issue for this. If someone else gets to a PR first, awesome, otherwise I'll do my best to get it as I'm able.

JasonTheAdams avatar Dec 17 '20 17:12 JasonTheAdams

Ok, the change doesn't seem to be that hard. I'll try to find some time next week for a PR ;)

lorado avatar Dec 17 '20 17:12 lorado

Hello,

Has this been resolved? I'm having issues with non-existent model instances with my policies using @upsert. I'd like my policies to be able to handle null values for the instances if no id is provided/found.

Thanks

Wolfeur avatar Jun 20 '23 12:06 Wolfeur

Released with https://github.com/nuwave/lighthouse/releases/tag/v6.11.0. Please consider sponsoring.

spawnia avatar Jun 20 '23 13:06 spawnia