Added basic ui update via sse
continuous-integration/drone/push Build is passing Details

This commit is contained in:
kolaente 2019-09-03 22:57:17 +02:00
parent c2c703711a
commit 639665ff7e
Signed by: konrad
GPG Key ID: F40E70337AB24C9B
3 changed files with 64 additions and 6 deletions

View File

@ -1,7 +1,61 @@
const source = new EventSource('/events');
source.onmessage = function(e) {
console.log(e)
};
if(typeof(EventSource) !== "undefined") {
console.log('SSE supported');
const tableName = '#konfis'
const table = $( tableName )
let source = new EventSource('/events');
source.onmessage = e => {
console.debug('unsupported event!', e)
};
source.addEventListener('init', e => {
console.debug('init', e)
const data = JSON.parse(e.data)
table.html('');
$.each( data, (i, item) => {
if (item.gemeinde !== undefined) {
table.append('<tr data-id="' + item.id + '"> ' +
'<td>' + item.name + '</td> ' +
'<td>' + item.gemeinde + '</td> ' +
'<td>' + item.kcoins + '</td>' +
'</tr>');
} else {
table.append('<tr data-id="' + item.id + '"> ' +
'<td>' + item.name + '</td> ' +
'<td>' + item.kcoins + '</td>' +
'<td>' + (item.coins_quota).toFixed(2) + '</td> ' +
'</tr>');
}
});
})
source.addEventListener('update', e => {
console.debug('update', e)
const data = JSON.parse(e.data)
$(tableName + ` tr`).each((i, tr) => {
if(tr.dataset.id == data.id) {
tr.innerHTML = '<td>' + data.name + '</td> ' +
'<td>' + data.kcoins + '</td>' +
'<td>' + (data.coins_quota).toFixed(2) + '</td> '
}
})
})
source.addEventListener('create', e => {
console.debug('create', e)
const data = JSON.parse(e.data)
})
source.addEventListener('delete', e => {
console.debug('delete', e)
const data = JSON.parse(e.data)
})
source.onopen = evt => {
console.debug('SSE opened', evt)
}
source.onerror = evt => {
console.debug('SSE Error', evt)
}
} else {
console.log('SSE not supported!');
}
/*
setInterval(function() {

View File

@ -28,6 +28,8 @@ func NewEcho() *echo.Echo {
Format: "${time_rfc3339}: ${remote_ip} ${method} ${status} ${uri} - ${user_agent}\n",
}))
//log.SetLevel(log.DEBUG)
// Session middleware
e.Use(session.Middleware(sessions.NewCookieStore([]byte("secret"))))

View File

@ -179,12 +179,14 @@ func (b *Broker) Serve(c echo.Context) error {
}
func sendJSONMessage(m *Message, f http.Flusher, rw http.ResponseWriter) {
jsonMessage, err := json.Marshal(m)
jsonMessage, err := json.Marshal(m.Data)
if err != nil {
log.Errorf("Error serializing json: %s", err)
}
_, err = fmt.Fprintf(rw, "%s\n\n", string(jsonMessage))
// The format is defined and has to be like this.
// This makes it however possible to register different event handlers for each event kind
_, err = fmt.Fprintf(rw, "event:%s\ndata: %s\n\n", m.Kind, string(jsonMessage))
if err != nil {
log.Errorf("Error sending message to client: %s", err)
}