elixirphoenix-frameworkgraphqlabsinthe

How to delete a photo from a database using Elixir and GraphQL


I gave been following the tutorial made by EQuimper the Instagram clone. I have been trying to extend the application further via the backend as the front end isn't of concern at the moment. I am trying to implement a delete photo feature but it doesn't seem to work and I can't figure out why.

mutation do
    @doc """
    deletes a photo in the database
    """
    field :photo_delete, list_of(:photo) do
        arg :id, non_null(:id)
        resolve &Resolvers.Posts.photo_delete/3
    end
end

My schema.ex contains this code under the mutations section.

def photos(_,_,_) do
    {:ok, Instagram.Posts.list_photos}
end

def photo(_, %{id: id}, _) do
    {:ok, Instagram.Posts.get_photo!(id)}
end

def photo_delete(_, %{id: id}, _) do
    photo_from_db = {:ok, Instagram.Posts.get_photo!(id)}
    {:ok, Instagram.Posts.delete_photo(photo_from_db)}
end

This is the code in the resolver.posts file which for returning a list or a single photo works.

def delete_photo(%Photo{} = photo) do
Repo.delete(photo)
end

This is the code that executes the mutation to delete the photo from the database, which takes in a photo struct and deletes it.

object :photo do
    field :id, non_null(:id)
    field :image_url, non_null(:string)
    field :caption, :string

    field :inserted_at, non_null(:string)
    field :update_at, non_null(:string)
end

This is the code that defines the photo schema.

schema "photos" do
field :caption, :string
field :image_url, :string

timestamps()

end

@doc false def changeset(%Photo{} = photo, attrs) do photo |> cast(attrs, [:image_url, :caption]) |> validate_required([:image_url]) end

this code is in the photo.ex file that handles the schema (I think)

 mutation {
  photo_delete(id: 1){
    id
 }
}

this is the mutation that I run to delete the query from the database. It returns an error saying

"no function clause matching in Instagram.Posts.delete_photo/1"

returned from the terminal. What have I done wrong? and what do I not understand about the flow of functions in this example. Link to the video series: https://www.youtube.com/watch?v=AVQQF_J3Az0&list=PLzQWIQOqeUSOu74jGJMRH06gneM3wL82Z for further clarification.


Solution

  • Found the answer

    field :delete_user, :user do
            arg :id, non_null(:id)
            resolve &Graphical.UserResolver.delete/2
        end
    

    this goes in your schema.ex file

     def delete(%{id: id}, _info) do
        Accounts.get_user!(id)
        |> Accounts.delete_user
    end
    

    this then gets called from the schema file, which will find the record at that id then pipe it to the delete method where it will be removed from the database