graphiti-api / graphiti

Stylish Graph APIs
https://www.graphiti.dev/
MIT License
974 stars 139 forks source link

my_resource.data raises Graphiti::Errors::RecordNotFound in #create action after Graphiti::Resource#build(params) when the table is empty #458

Open dima4p opened 10 months ago

dima4p commented 10 months ago

`When the table has no record returns @scope.resolve an empty Array. In my controller there is

# POST /user_absences
def create
  @user_absence = UserAbsenceResource.build(params)
  authorize @user_absence.data

  if @user_absence.save
    render jsonapi: @user_absence, status: 201
  else
    render jsonapi_errors: @user_absence
  end
end

and I get

 Graphiti::Errors::RecordNotFound:
   Specified Record Not Found

in the case.

dima4p commented 10 months ago

Additionally is my_resource.data always nil after Graphiti::Resource#build. Of course in the case I set raise_on_missing: false here

factyy commented 10 months ago

@dima4p , from our experience I can tell that it's not a good way to rely on resource.data when the model is not yet saved. If you need to check authorization on the model instance creation step, there is a separate gem for it (assuming you are using ActionPolicy).

dima4p commented 10 months ago

@dima4p , from our experience I can tell that it's not a good way to rely on resource.data when the model is not yet saved. If you need to check authorization on the model instance creation step, there is a separate gem for it (assuming you are using ActionPolicy).

We are using Pundit. I think, that it is important to have the ability to use Graphiti::Resource#build#data to use the new model for authorization. Now I have to keep in controller the method "#{singular_table_name}_params" and create an additional instance of Model with #new in order to be able to authorize it.

factyy commented 10 months ago

@dima4p , if you are using Graphiti under the hood, you can hook into model creation via the before_save callback where you will have full access to the newly-built (but not yet saved) model

factyy commented 10 months ago

@dima4p , one more thing: keep in mind that with JSON:API you have the ability to sidepost multiple resources in one request and thus you will have to either parse the whole resource tree yourself or rely on Graphiti with the approach I mentioned above