Refactoring an FQL function for deleting items by nested field

Hello all! :wave: I’m quite new to FQL and I tried to write a FQL function for deleting items based on the nested field. I have following types:

type User {
  name: String
  email: String! @unique
  hashedPassword: String
  role: String!
}

type Token {
  hashedToken: String!
  type: String!
  expiresAt: Time!
  sentTo: String!
  user: User! @relation
}

And I would like to create a FQL function for deleting Tokens by ID of the user. I want the GraphQL mutation that would use this function as a resolver to have this signature:

type Mutation {
  deleteTokensByUserId(userId: ID!): [Token] @resolver(name: "delete_tokens_by_user_id")
}

After some try and error I came up with the following solution:

CreateIndex({
  name: "all_tokens_by_user_id",
  source: Collection("Token"),
  terms: [
    { field: ["data", "user", "id"] }
  ]
})

CreateFunction({
  name: "delete_tokens_by_user_id",
  body: Query(
    Lambda(
      ["userId"],
      Let(
        {
          tokenDoc: Map(
            Paginate(Match(Index("all_tokens_by_user_id"), Var("userId"))),
            Lambda("tokenRef", Delete(Var("tokenRef")))
          )
        },
        Select(["data"], Var("tokenDoc"))
      )
    )
  )
})

The function works and returns correct data type, but I have a gut feeling, that it can be written in a smarter, more concise way.

Could you point me in some direction? Thanks in advance!

Hi @KajetanSw ,

That’s a pretty concise function as it is. The only thing I can think of is to remove the Let() wrapper, as the return will be a data object comprising the tokens that were just deleted, anyway. It’ll look a little different so it might take some adjustments in your app to process the return. Here’s an example:

Call("delete_tokens_by_user_id_v2", "304747382108586562")

{
  data: [
    {
      ref: Ref(Collection("Token"), "304747981227164224"),
      ts: 1626889172702000,
      data: {
        expiresAt: Time("2021-08-01T00:00:00Z"),
        type: "basic",
        hashedToken: "dlslsos32",
        sentTo: "no one",
        user: Ref(Collection("User"), "304747382108586562")
      }
    },
    {
      ref: Ref(Collection("Token"), "304747984736748096"),
      ts: 1626889176050000,
      data: {
        expiresAt: Time("2021-08-01T00:00:00Z"),
        type: "basic",
        hashedToken: "dlsls22os32",
        sentTo: "no one",
        user: Ref(Collection("User"), "304747382108586562")
      }
    },
    {
      ref: Ref(Collection("Token"), "304747988683588160"),
      ts: 1626889179820000,
      data: {
        expiresAt: Time("2021-08-01T00:00:00Z"),
        type: "basic",
        hashedToken: "gewewrteer",
        sentTo: "no one",
        user: Ref(Collection("User"), "304747382108586562")
      }
    }
  ]
}

Cory