简体   繁体   中英

Access nodejs static method using a string variable

I have imported a few classes in Adonis

const User = use('App/Models/User')
const Orders = use('App/Models/Orders')

I want to be able to access one of the above classes dynamically. By that I mean a variable will hold the class I want to access. The variable will be populated by via an API call from the user.

let className = 'Orders'

How to I use the className variable to access the Orders class.

I have tried

[className].query().where('orderNumber','123').fetch()

However that does not seem to work.

Create a name -> class map:

const classes = {
  __proto__: null, // to avoid people being able to pass something like `toString`
  Users,
  Orders,
};
// or if you don't want to use __proto__
const classes = Object.assign(
  Object.create(null),
  {Users, Orders}
);

and access the right class with classes[className] . Of course verify whether the class exists or not.


I have tried

 [className].query().where('orderNumber','123').fetch() 

However that does not seem to work.

In this context, [...] denotes an array literal, so [className] just creates an array containing className (which is a string in your example) as only element.

Avoid converting the variable to a string at all. Just use:

let className = Orders;
className.query().where('orderNumber','123').fetch()

If the class is being instantiated by an API call, use a simple switch statement:

let class;
switch (apiCall.name) {
    case 'orders':
        class = Orders;
        break;
    case 'users':
        class = Users;
        break;
    default:
        throw 'Invalid API Call';
}

class.query().where('orderNumber','123').fetch()

最简单的方法是eval(className).query().where('orderNumber','123').fetch() ,但是如果您想将值作为实际类检查是否存在,则可能应该实现开关或-else-if检查并分配className,仅在实际存在时调用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM