Last active
March 11, 2022 10:53
-
-
Save ComradeLV/5e36d01c0554bcde4fa76af45c4cceed to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
class UserManagementConnector { | |
constructor() { | |
this.websocketName = "umWebSockets"; | |
} | |
setup(userManagementUrl, applicationName, notificationsRootElementId) { | |
this.userManagementUrl = userManagementUrl; | |
this.applicationName = applicationName; | |
this.notificationsRootElementId = notificationsRootElementId || "notificationsRootElement"; | |
this.isSetupDone = true; | |
} | |
start() { | |
if (!this.isSetupDone) { | |
console.error("Connector setup is not performed"); | |
return; | |
} | |
let sharedSrc = `${trimSlash(this.userManagementUrl, '/')}/shared.js`; | |
LoadJs(sharedSrc, () => { | |
this.ensureAccessor() | |
.then(() => { | |
let config = { | |
userManagementUrl: this.userManagementUrl, | |
applicationName: this.applicationName, | |
notifications: { | |
rootElementId: this.notificationsRootElementId, | |
listSize: 10 | |
} | |
}; | |
this.accessor.startWithConfiguration(config).then(res => { | |
if (!res) { | |
throw new Error("WebSockets start failed"); | |
} | |
}); | |
}); | |
}); | |
} | |
stop() { | |
if (this.accessor) { | |
this.accessor.stop(); | |
} | |
} | |
ensureAccessor() { | |
let attempt = 0; | |
let maxAttempts = 10; | |
const poll = (resolve) => { | |
attempt++; | |
this.accessor = window[this.websocketName]; | |
if (this.accessor) { | |
resolve(); | |
} | |
else if (attempt > maxAttempts) { | |
throw new Error(`${this.websocketName} are missing after ${attempt}`); | |
} | |
else { | |
console.log(`No ${this.websocketName} yet on attempt ${attempt}`); | |
setTimeout(() => poll(resolve), 1000); | |
} | |
}; | |
return new Promise(poll); | |
} | |
} | |
function trimSlash(inputStr) { | |
return inputStr.replace(/\/$/, ''); | |
} | |
function LoadJs(url, callback) { | |
let tag = document.createElement('script'); | |
tag.type = "text/javascript"; | |
tag.async = false; | |
if (callback) { | |
tag.onload = callback; | |
} | |
tag.src = url; | |
let body = document.getElementsByTagName('body')[0]; | |
body.appendChild(tag); | |
} | |
export default UserManagementConnector; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment