Skip to content

Commit

Permalink
Add APIClass
Browse files Browse the repository at this point in the history
  • Loading branch information
DVitaliy committed Jan 9, 2022
1 parent 61b3ef3 commit 32e2e3f
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 3 deletions.
75 changes: 74 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1 +1,74 @@
alert(11)
class EventObserver {
constructor() {
this.observers = []
}
subscribe(fn) {
if (!this.observers.some((obj) => obj === fn)) this.observers.push(fn)
}
unsubscribe(fn) {
this.observers = this.observers.filter((obj) => obj !== fn)
}
broadcast(...rest) {
this.observers.forEach((fn) => fn(...rest))
}
}

class APIClass {
constructor({ host, getTokenCallBack }) {
this.host = host
this.getTokenCallBack = getTokenCallBack
this.observer = new EventObserver()
this.gRPCServices = {}
}
async getToken() {
try {
return await this.getTokenCallBack()
} catch (err) {
// continue regardless of error
}
}
subscribeResponse(fn) {
this.observer.subscribe(fn)
}
unsubscribeResponse(fn) {
this.observer.unsubscribe(fn)
}
addgRPCService(name, Client, message) {
if (!(name in this.gRPCServices)) {
this.gRPCServices[name] = {
client: this.proxygRPCService(Client),
message
}
}
}
proxygRPCService(Client) {
let self = this
return new Proxy(new Client(this.host), {
get(target, name) {
if (name in target.__proto__) {
return async (...args) => {
try {
const response = await target[name].apply(target, [
...args,
{
Authorization: `Bearer ${await self.getToken()}`
}
])
return Promise.resolve(response)
} catch (err) {
self.observer.broadcast(err)

return Promise.reject(err)
}
}
} else {
return Reflect.get(...arguments)
}
}
})
}
getgRPCService(name) {
return this.gRPCServices[name]
}
}
export default APIClass
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "@DVitaliy/grpcprovider",
"name": "@dvitaliy/grpcprovider",
"version": "1.0.0",
"description": "",
"main": "index.js",
Expand All @@ -10,7 +10,7 @@
"type": "git",
"url": "git+https://github.com/DVitaliy/grpcprovider.git"
},
"author": "",
"author": "Dynnik Vitaly",
"license": "ISC",
"bugs": {
"url": "https://github.com/DVitaliy/grpcprovider/issues"
Expand Down

0 comments on commit 32e2e3f

Please sign in to comment.