Collection name as a new Module in tagged templates not working

Trying to update all code base to FQL10 I found very difficult to rebuild a simple function called getByRef accepting a collectionName and ID, which is currently used by hundred of routes and functions in the app. The collectionName is never defined by the user, so no security issues are involved related to potential extraction of data from unintended collections. Not having that function would require rewriting almost all routes requiring specific documents and repeating al the fql query too much times.
Following the fixes in some posts here I found the use of new Module as a workaround, but it still does not work. The passed collection name is “invoicing”.

_.getByRef = async function (collection, ref) {
    const mod = new Module(collection)
    const query = fql`
      let coll = ${mod}
      coll.byId(${ref})
    `
    const resp = await client.query(query)
    return resp.data
}

The error obtained is:

httpStatus: 400,
  code: 'invalid_query',
  queryInfo: {
    txn_ts: 1722574494812618,
    summary: 'error: Type `invoicingCollection` does not have field `byId`\n' +
      'at *query*:3:12\n' +
      '  |\n' +
      '3 |       coll.byId(<value>)\n' +
      '  |            ^^^^\n' +
      '  |\n' +
      'hint: Type `invoicingCollection` inferred here\n' +
      'at *query*:2:18\n' +
      '  |\n' +
      '2 |       let coll = <value>\n' +
      '  |                  ^^^^^^^\n' +
      '  |'
}

Why does it add “Collection” to the end of the collection name and yet is not working.

Hi @sdevelopsdesign and welcome!! :wave:

We have a known issue when typechecking queries using Module as arguments.

That said, we introduced an easier way to make dynamic queries with collection names. You can call Collection as a function, providing the collection name.

example from docs:

// FQL
let produce = Category.byName("produce").first()


Collection("Product").create({
  name: "zebra pinata",
  description: "Giant Zebra Pinata",
  price: 23.99,
  stock: 0,
  category: produce
})

so in your JS script you should be able to do this

// JS
_.getByRef = async function (collection, ref) {=
    const query = fql`
      Collection(${collection}).byId(${ref})
    `
    const resp = await client.query(query)
    return resp.data
}
1 Like

Thank you very much, issue fixed, more logical and intuitive way.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.