I’m trying to create a JS service on WebOS 3.0 followed the official documentation.
I can send data between JS service and my application, but sometimes the JS service does not respond to the request if it’s idled for like 20 seconds. I’ve also tried to increase the timeout per this. Unfortunately, it does not seemed to be working.
Here’s my code
Application Side
const request = webOS.service.request('luna://com.myapp.service', {
method : 'fetch',
parameters : { url, method, headers, body },
onFailure : (err) => {
reject(err)
},
onSuccess : (s) => {
console.log('request success', s)
},
onComplete : (resp) => {
const isSuccess = resp.data.status >= 200 && resp.data.status < 400
var payload = {
json : () => Promise.resolve(JSON.parse(resp.data.body)),
ok : isSuccess,
headers : resp.data.headers,
status : resp.data.status,
error : isSuccess
? null
: resp.data.body
}
resolve(payload)
}
})
})
Service Side
var Service = require('webos-service')
var service = new Service('com.myapp.service')
service.register('fetch', function(message) {
var payload = message.payload
if(!payload) {
message.respond({
returnValue : true,
error : 'Message does not have a `payload`'
})
return
}
var url = payload.url,
headers = payload.headers,
method = payload.method,
body = payload.body
var request = http.request({
method : method,
hostname : URL.parse(url).hostname,
path : URL.parse(url).path,
headers : headers,
}, function(res) {
var data = ''
res.on('data', function(chunk) { data+=chunk })
res.on('end', function() {
message.respond({
returnValue : true,
data : {
status : res.statusCode,
statusText : res.statusMessage,
headers : res.headers,
body : data,
}
})
})
})
request.on('error', function(err) {
console.log(err)
message.respond({
returnValue : true,
error : err
})
})
request.end()
})
I recently wrote a JavaScript application for LG Smart-TVs and would highly recommend using socket.io for all communication between client and server. It's a bit tricky getting it to work initially, but works flawlessly.
Here's how the connection looks ...
After that, it's all a matter of processing and formatting the returned data.