I'm trying to create an JavaScript API client using JavaScript classes. I kind of know how to use JavaScript, but i'm not an expert. I've been reading the developer docs, and my guess is that boxing is occurring, and i'm not sure how to get around it. Every time i try to use the users()
i get an exception staying Cannot read property 'client' of undefined
which makes me think that when i use this.client
in my users()
this
is undefined. Am I just using JavaScript the wrong way? My code structure is as follows. You can make the assumptions that all the imports required (axios) are included.
class Api {
constructor(host) {
this.host = host;
}
client() {
return axios.create({
baseURL: this.host,
timeout: process.env.API_REQUEST_TIMEOUT,
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
});
}
users() {
return new UserClient(this.client);
}
}
class UserClient {
constructor(apiClient) {
this.client = apiClient;
}
get() {
return this.client().get('/users').then(result => result);
}
}
UPDATE The way i'm use the client is as follows:
const api = new Api('localhost:3000');
api.users().get()
EDIT 2
Added the return statement in the get()
** EDIT 3 **
I kind of figured out what's going on. I'm losing the Api context when using the users()
of an Api instance. Adding a console.log(this) in Api#users()
returns UserClient
and i was expecting it to be Api
, and since UserClient
doesn't have a client function defined it's returning undefined, so I guess my question is, when i'm using the users()
of an Api instance, what's the proper way to maintain the Api context when passing this.client
while instantiating a new UserClient?