Available fields in a model


#1

Hi,

I’d like to check the available fields in model.
Is there any way/function to get an array from all visible fields in a model?


#2

Hey @4dgeek! :wave:

You cannot for the moment do this with Adonis.
You need to use a type system like Flow or TypeScript.

The next major release of Adonis will let you use TypeScript for your code. For the moment you’ll need to do some hacking to use those.

There’s some information in this issue created by @jakesyl.


#3

Hi Romain,
If I understand you correctly you mean autocomplete in my IDE. That’s not the point.
I’m building an api server where the user has the ability to define a fields he want’s to see in the response. For an example
//http://127.0.0.1:3333/api/syslogs?limit=1&fields=id,modul…

So I’d like to verify wether the fields are available or not before hitting the query.
Meaning, I’d like to evaluate the requested fields an compare them to the current resource.


#4

@4dgeek What you are trying to do is possible but not ideal.

const columns = await User.query().columnInfo()

More here https://knexjs.org/#Builder-columnInfo.

Now doing this on each API call will add unwanted overhead to your API, since you are making DB calls to get it’s structure.

There are couple of alternatives to this.

  1. Manually add an array of columns you know exists in the table.

    class User extends Model {
     static get columns() [
         return ['id', 'username']
      ]
    }
    

    And then check for array intersection to find if all columns exists.

  2. Invoke Model.query().columnInfo() on each model and store as reference of it at the time of application boot. You can make use of hooks.before.httpServer hook for same.


#5

@virk Thx for your response.

Your are right hitting the db twice is not cool.
Your first example works
The second, does not work and I don’t understand how to fix?

const cols = await Syslog.query().columnInfo();
Leads to an error : Make sure to call fetch to execute the query

const cols = await Syslog.query().columnInfo().fetch;
Leads to an error as well: rows.map is not a function

What am I missing?