I'm building a client for a RESTful API, and in the API there are some modules with the same functions, for example GetVersion
will return the version of the specific module.
https://example.com/core/GetVersion -> 1.1
https://example.com/auth/GetVersion -> 1.8
there are multiple modules with the same function/endpoint.
I was wondering how I can implement it into the API class I'm building, I tried entering all the functions of a module into a namespace but then the functions cannot access methods and properties outside the namespace.
class API {
constructor(config) {
this.user_id = config.user_id
this.password = config.password
this.basePath = `https://${config.server}/`
this.instance = axios.create({
httpsAgent: new https.Agent({
rejectUnauthorized: false
})
});
this.authToken = undefined
}
/******************/
/* Helper Methods */
/******************/
request(endpoint, body, config) {
const url = this.basePath + endpoint
config.headers = {
"Accept": "application/json"
}
// all requests are POST requests
return this.instance.post(url, body, config)
.then(res => {
return res.data
})
.catch(function (error) {
console.error(error);
});
}
/*****************/
/* Core Services */
/*****************/
core = {
getVersion() {
return this.request('core-service/getVersion', {}, {}).then(res => {
console.log(res)
})
}
}
/*****************/
/* Auth Services */
/*****************/
auth = {
getVersion() {
return this.request('auth-service/getVersion', {}, {}).then(res => {
console.log(res)
})
}
}
}
const api_client = new API({
user_id: 'admin',
password: 'admin',
server: 'example.com'
})
api_client.core.getVersion()
api_client.auth.getVersion()
But I get the error
return this.request('core-service/getVersion', {}, {}).then(res => {
^
TypeError: this.request is not a function
What is the best practice to use in order to get different namespaces inside the same class?