Skip to content

Commit

Permalink
add create and destroy to v1/collections
Browse files Browse the repository at this point in the history
  • Loading branch information
Nicholas Newberry committed Jul 18, 2024
1 parent 1a05cc3 commit cf55a10
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 5 deletions.
34 changes: 34 additions & 0 deletions app/controllers/v1/collections_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,46 @@ def search
render json: { hits: Api::Search.new(@collection, base_url: request.base_url).search(query) }
end

def create
collection = Collection.new(**create_params)
collection.update!(embedding_model: Setting.embedding_model)
collection.generate_slug
collection.save!

render json: { collection: collection.attributes.slice!(*render_attributes) }
end

def destroy
collection = Collection.find(params[:id])

return render json: { error: "User cannot delete collection." } unless user_can_access_collection?(
@client.user,
collection
)

collection.destroy!

render json: { collection: }, status: :ok
end

private

def user_can_access_collection?(user, collection)
user.collections.include?(collection)
end

def set_collection!
@collection = Collection.find_by(id: params[:id])

render json: { error: "Collection not found" }, status: :not_found if @collection.nil?
end

def create_params
params.slice(:name).permit!
end

def render_attributes
[:id, :name, :slug]
end
end
end
22 changes: 20 additions & 2 deletions bin/request
Original file line number Diff line number Diff line change
@@ -1,10 +1,28 @@
#!/usr/bin/env ruby

if ARGV.first == '-p'
method = :post
ARGV.shift
if ARGV.first == '-'
body = $stdin.read
else
body = ARGV.shift
end
elsif ARGV.first == "-d"
method = :delete
ARGV.shift
body = nil
end
if method.nil?
method = :get
body = nil
end

params = ARGV[1..-1].map do |arg|
name, value = arg.split('=')

if name.nil? || value.nil?
stderr.puts "Invalid argument: #{arg}"
$stderr.puts "Invalid argument: #{arg}"
exit(1)
end

Expand All @@ -26,7 +44,7 @@ headers = {
'X-Client-Id' => "#{ENV['DEFAULT_CLIENT_ID']}",
}

response = HTTParty.get(url, headers: headers)
response = HTTParty.send(method, url, headers: headers, body: body)

if response.success?
puts JSON.pretty_generate(response.parsed_response)
Expand Down
4 changes: 1 addition & 3 deletions config/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,7 @@
# API
namespace :v1 do
resources :documents, only: [:index, :show]
resources :collections do
get "list", on: :collection, to: "collections#list"
get "get", on: :member, to: "collections#get"
resources :collections, only: %i[create destroy index show] do
get "search", on: :member, to: "collections#search"
end
resources :chunks do
Expand Down

0 comments on commit cf55a10

Please sign in to comment.