Only init websocket if local API

This commit is contained in:
Lukas Martinelli 2017-01-01 15:12:46 +01:00
parent ce39ae723c
commit fa38667125
3 changed files with 34 additions and 34 deletions

View file

@ -29,8 +29,8 @@ export default class App extends React.Component {
onLocalStyleChange: mapStyle => this.onStyleChanged(mapStyle, false)
})
this.styleStore.supported(isSupported => {
if(!isSupported) {
this.styleStore.init(err => {
if(err) {
console.log('Falling back to local storage for storing styles')
this.styleStore = new StyleStore()
}

View file

@ -7,46 +7,46 @@ const port = '8000'
const localUrl = `http://${host}:${port}`
const websocketUrl = `ws://${host}:${port}/ws`
console.log(localUrl, websocketUrl)
export class ApiStyleStore {
constructor(opts) {
if(opts.onLocalStyleChange) {
this.onLocalStyleChange = opts.onLocalStyleChange || (() => {})
}
init(cb) {
request(localUrl + '/styles', (error, response, body) => {
if (!error && body && response.statusCode == 200) {
const styleIds = JSON.parse(body)
this.latestStyleId = styleIds[0]
this.notifyLocalChanges()
cb(null)
} else {
cb(new Error('Can not connect to style API'))
}
})
}
notifyLocalChanges() {
const connection = new ReconnectingWebSocket(websocketUrl)
connection.onmessage = function(e) {
if(!e.data) return
try {
console.log('Received style update from API')
const updatedStyle = style.ensureStyleValidity(JSON.parse(e.data))
opts.onLocalStyleChange(updatedStyle)
this.onLocalStyleChange(updatedStyle)
} catch(err) {
console.error('Cannot parse local file ' + e.data)
}
}
}
}
supported(cb) {
request(localUrl + '/styles', (error, response, body) => {
cb(error === null)
})
}
latestStyle(cb) {
if(this.latestStyleId) {
request(localUrl + '/styles/' + this.latestStyleId, (error, response, body) => {
cb(JSON.parse(body))
})
} else {
request(localUrl + '/styles', (error, response, body) => {
if (!error && response.statusCode == 200) {
const styleIds = JSON.parse(body);
this.latestStyleId = styleIds[0];
request(localUrl + '/styles/' + this.latestStyleId, (error, response, body) => {
cb(style.ensureStyleValidity(JSON.parse(body)))
})
}
})
} else {
throw new Error('No latest style available. You need to init the api backend first.')
}
}

View file

@ -69,8 +69,8 @@ export class StyleStore {
this.mapStyles = loadStoredStyles()
}
supported(cb) {
cb(window.localStorage !== undefined)
init(cb) {
cb(null)
}
// Delete entire style history