[overlays] Add helper function to render template strings

Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
Knut Ahlers 2022-02-20 13:52:40 +01:00
parent ddc52d8920
commit 5f5f96a35e
Signed by: luzifer
GPG Key ID: 0066F03ED215AD7D
2 changed files with 26 additions and 3 deletions

View File

@ -71,7 +71,7 @@
},
mounted() {
new EventClient({
window.botClient = new EventClient({
handlers: {
_: (evt, data, time, live) => {
this.events = [

View File

@ -36,6 +36,15 @@ export default class EventClient {
this.connect()
}
/**
* Returns the API base URL without trailing slash
*
* @returns {string} API base URL
*/
apiBase() {
return window.location.href.substr(0, window.location.href.indexOf('/overlays/'))
}
/**
* Connects the EventClient to the socket
*
@ -104,6 +113,21 @@ export default class EventClient {
return this.params.get(key) || this.options[key] || fallback
}
/**
* Renders a given template using the bots msgformat API (supports all templating you can use in bot messages)
*
* @params {string} template The template to render
* @returns {Promise} Promise resolving to the rendered output of the template
*/
renderTemplate(template) {
return fetch(`${this.apiBase()}/msgformat/format?template=${encodeURIComponent(template)}`, {
headers: {
authorization: this.paramOptionFallback('token'),
},
})
.then(resp => resp.text())
}
/**
* Modifies the overlay address to the websocket address the bot listens to
*
@ -111,7 +135,6 @@ export default class EventClient {
* @returns {string} Websocket address in form ws://... or wss://...
*/
socketAddr() {
const base = window.location.href.substr(0, window.location.href.indexOf('/overlays/') + '/overlays/'.length)
return `${base.replace(/^http/, 'ws')}events.sock`
return `${this.apiBase().replace(/^http/, 'ws')}/overlays/events.sock`
}
}