Get a user object by username or id javascript

Is there any way to get a user object by username or id via javascript?

It is difficult to answer without some more context. You can always do this: (try it in the dev tools for Meta)

Discourse.User.findByUsername("David_Taylor").then(function(user){
   console.log("User Found", user);
});

But that will result in an additional request to the server, which may not be necessary.

What are you trying to achieve?

6 Likes

Thanks very much. I am trying to get a list of usersnames with certain custom field attributes. As you correctly pointed out, it will result in many additional calls from the API.

Is it possible to achieve what I intend more gracefully?

If this is just for administrators, you might be able to utilise the data-explorer plugin. If you wanted this to work for all users, you would probably need to create a plugin which adds a new HTTP endpoint.

5 Likes

I’m working on one of the bugs related to events plugin where the current implementation was relying on usernames. Even though its an edge case, the usernames can change which creates the need to be able to get a user by their id.

I think there should be a similar method in core to find a user by id.

Interested to know your thoughts on this.

Your plugin should be able to either update the username references when a username changes or add the necessary routes and serializers you need to fetch the data.

4 Likes

I’ll check to see if it’s possible to do this in the current scenario.

Yeah. I’ll need to add a method to UsersController to find a user by id and add a method in the ember side User model to call this new controller method.