Delete record only if user id matches

Hello,

I would like to delete a record (Project) only if it belongs to the logged in user
I have the Project _id but I want to check the user too

Record examples

{
    "user": "111",
    "name": "My Project"
}
{
    "user": "111",
    "name": "My New Project"
}
{
    "user": "222",
    "name": "My New Project"
}

Here’s what I tried
Schema

type Project {
    user: String
    name: String!
}

type Query {
    projectsByUser(user: String!): [Project!]!
}

type Mutation {
    deleteUserProject( id: ID!, user: String!): ID! @resolver(name: "delete_user_project")
}

Maybe I’m already wrong about something here, please bare with me

Next, I tried creating a FQL query in the shell which uses the id and the user conditions to delete the record but I got stuck
Here’s what I tried

Delete(
  Select([0], 
   Paginate(
    Intersection(
     Match(Index("projectsByUser"), "111"),
     Ref(Collect("Project"), "XXXXXXXXXXXX") <- supposed to be the id check
    )
   )
  )
)

This doesn’t work, I don’t know how to match both the user and the id
Any idea is appreciated

Edit: I found a solution which is to add the ref to the Index terms

Paginate(
    Match(Index("projectsByUser"), ["111", Ref(Collection("Project"), "288999786778984961")]),
)

Looks a bit weird but it works!

Thank you

So basically you want to delete a single project (using its id) if the current logged in user has it ?

Let(
 {
   project: Ref(Collect("Project"), "XXXXXXXXXXXX"),
   userProjects: Select('data',
      Paginate(
         Match(Index("projectsByUser"), "111")
      )
   )
 },
 If(
   ContainsValue(Var("project"), q.Var('userProjects')),
   Delete(Var('project')),
   Abort('Project is not from current user')
 )
)

But the easiest way would be to have an other index :

CreateIndex({
   name: "findUserProject",
   source: Collection("Project"),
   terms: [
      { field: ["ref"] },
      { field: ["data", "user"] },
   ]
})

Then use it like :

Let({
   project: Ref(Collection("Project"), "XXXXXXXXXXXX")
},
If(
  Exists(
    Match(
      Index('findUserProject'),
      [Var('project'), "111"]
    )
  ),
  Delete(Var('project')),
  Abort('Project is not from current user')
)

Or even simpler :

// this will abort if match doesn't exist :) So you try/catch
Delete(
  Get(
    Match(
      Index('findUserProject'),
      [Ref(Collection("Project"), "XXXXXXXXXXXX"), "111"]
    )
  )
)
1 Like

Wow thank you, I will learn a lot from this
I wanted to do it in a single graphql request and this is the way to do it

It works this way for me

Delete(
 Select('ref',
  Get(
    Match(
      Index('findUserProject'),
      [Ref(Collection("Project"), projectID), Ref(Collection("users"), userID)]
    )
  )
 )
)