Open
Description
What I hope to achieve
Have routes mapped to namespaced controllers (Api::V1::NotesController
) much like the one below:
Attempted solution:
- Create new rails app:
rails new sample-graphiti-api --api -m https://www.graphiti.dev/template
- Press
<ENTER>
if asked for the namespace (default is/api/v1
) rails generate model Note content:string
rails generate graphiti:resource note content:string created_at:datetime
(rails generate graphiti:resource api/v1/note content:string created_at:datetime
doesn't work so we do it manually)- Move
app/resources/note_resource.rb
toapp/resources/api/v1/note_resource.rb
and changeNoteResource
toApi::V1::NoteResource
class Api::V1::NoteResource < ApplicationResource
attribute :content, :string
attribute :created_at, :datetime, writable: false
end
- Move
app/controllers/notes_controller.rb
toapp/controllers/api/v1/note_resource.rb
and changeNotesController
toApi::V1::NotesController
. Also, change all occurrences ofNoteResource
toApi::V1::NoteResource
. File should look like this:
class Api::V1::NotesController < ApplicationController
def index
notes = Api::V1::NoteResource.all(params)
respond_with(notes)
end
def show
note = Api::V1::NoteResource.find(params)
respond_with(note)
end
def create
note = Api::V1::NoteResource.build(params)
if note.save
render jsonapi: note, status: 201
else
render jsonapi_errors: note
end
end
def update
note = Api::V1::NoteResource.find(params)
if note.update_attributes
render jsonapi: note
else
render jsonapi_errors: note
end
end
def destroy
note = Api::V1::NoteResource.find(params)
if note.destroy
render jsonapi: { meta: {} }, status: 200
else
render jsonapi_errors: note
end
end
end
- Change the routes to:
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :notes, defaults: { format: :jsonapi }
end
end
end
- Run the migrations and start the server
- Do a
GET /api/v1/notes
. An error occurs:
Graphiti::Errors::InvalidEndpoint ( Api::V1::NoteResource cannot be called directly from endpoint /api/v1/notes#index!
Either set a primary endpoint for this resource:
primary_endpoint '/my/url', [:index, :show, :create]
Or whitelist a secondary endpoint:
secondary_endpoint '/my_url', [:index, :update]
The current endpoints allowed for this resource are: [{:path=>:"/api/v1/notes", :full_path=>:"/api/v1/api/v1/notes", :url=>:"http://localhost:3000/api/v1/api/v1/notes", :actions=>[:index, :show, :create, :update, :destroy]}]
):
Metadata
Metadata
Assignees
Labels
No labels