在JavaScript类中使用命名空间



我正在为RESTful API构建一个客户端,在API中有一些模块具有相同的功能,例如GetVersion将返回特定模块的版本。

https://example.com/core/GetVersion -> 1.1
https://example.com/auth/GetVersion -> 1.8

存在具有相同功能/端点的多个模块。

我想知道如何将它实现到我正在构建的API类中,我尝试将模块的所有函数输入到命名空间中,但这些函数无法访问命名空间之外的方法和属性。

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()

但是我得到错误

return this.request('core-service/getVersion', {}, {}).then(res => {
^
TypeError: this.request is not a function

为了在同一个类中获得不同的名称空间,最佳做法是什么?

我将命名空间中的方法更改为

getVersion: () => {***}

现在它起作用了。

最新更新