【发布时间】:2021-09-27 04:43:27
【问题描述】:
我正在为一个 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
为了在同一个类中获得不同的命名空间,最佳实践是什么?
【问题讨论】:
-
不幸的是,它看起来不像我遇到的问题:(
-
这是同一个问题。类是构造函数。在构造函数中绑定正确的 this 版本。另一个有用的问题stackoverflow.com/questions/68235237/…
-
是的,你是对的,谢谢。
-
很高兴它有帮助!
标签: javascript class namespaces