diff --git a/src/thing-server.js b/src/thing-server.js index 9075833..8198939 100644 --- a/src/thing-server.js +++ b/src/thing-server.js @@ -156,10 +156,62 @@ class ThingServer { /** * Read All Properties * - * @param {Request} _request + * @param {Request} request * @param {Response} response */ - async (_request, response) => { + async (request, response) => { + const requestedEventStream = + request.accepts('text/event-stream') && + !request.accepts('application/json'); + + if (requestedEventStream) { + if (this.thing.properties.size === 0) { + response.status(404).send(); + return; + } + + const observableProperties = new Set( + [...this.thing.properties] + .filter( + ([, property]) => + property.observable === true && property.writeOnly !== true, + ) + .map(([name]) => name), + ); + if (observableProperties.size === 0) { + response.status(406).send(); + return; + } + + response.status(200); + response.set({ + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + Connection: 'keep-alive', + }); + + /** + * @param {string} name The name of the Property that changed. + * @param {any} value The new value of the changed Property. + * @param {string} eventId Event ID in date-time format. + */ + const onPropertyChanged = (name, value, eventId) => { + if (!observableProperties.has(name) || response.writableEnded) { + return; + } + response.write( + `event: ${name}\ndata: ${JSON.stringify(value)}\nid: ${eventId}\n\n`, + ); + }; + + this.thing.on('propertyChanged', onPropertyChanged); + response.on('close', () => { + this.thing.off('propertyChanged', onPropertyChanged); + }); + response.flushHeaders(); + return; + } + if (this.thing.properties.size === 0) { response.status(404).send(); return; diff --git a/src/thing.js b/src/thing.js index 58fc351..18bd17e 100644 --- a/src/thing.js +++ b/src/thing.js @@ -362,6 +362,19 @@ class Thing extends EventEmitter { propertyOperations.push('writemultipleproperties'); } thingDescription.forms = [{ href: 'properties', op: propertyOperations }]; + if ( + [...this.properties.values()].some( + (property) => + property.observable === true && property.writeOnly !== true, + ) + ) { + thingDescription.forms.push({ + href: 'properties', + op: ['observeallproperties', 'unobserveallproperties'], + contentType: 'application/json', + subprotocol: 'sse', + }); + } } // If actions are defined then add an actions member if (Object.keys(actions).length > 0) { diff --git a/test/thing-server.test.js b/test/thing-server.test.js index b3517fe..05475fa 100644 --- a/test/thing-server.test.js +++ b/test/thing-server.test.js @@ -164,6 +164,72 @@ describe('ThingServer', () => { }); }); + describe('GET /properties (SSE)', () => { + it('should stream changes to all observable properties as named JSON events', async () => { + const response = await fetch(baseUrl + '/properties', { + headers: { Accept: 'text/event-stream' }, + }); + + assert.equal(response.status, 200); + assert.match(response.headers.get('content-type'), /^text\/event-stream/); + assert.equal(response.headers.get('cache-control'), 'no-cache'); + + const reader = response.body.getReader(); + const nextEvent = reader.read(); + await server.thing.emitPropertyChange('on', false); + + const { value, done } = await nextEvent; + assert.equal(done, false); + const event = new TextDecoder().decode(value); + assert.match(event, /^event: on\ndata: false\nid: .+\n\n$/); + await reader.cancel(); + }); + + it('should return 406 when no readable property is observable', async () => { + const unobservableServer = new ThingServer( + new Thing({ + title: 'Unobservable Thing', + properties: { + status: { type: 'string' }, + token: { type: 'string', writeOnly: true, observable: true }, + }, + }), + ); + await new Promise((resolve) => { + unobservableServer.server = unobservableServer.app.listen(0, resolve); + }); + + try { + const response = await fetch( + `http://localhost:${unobservableServer.server.address().port}/properties`, + { headers: { Accept: 'text/event-stream' } }, + ); + assert.equal(response.status, 406); + } finally { + unobservableServer.stop(); + } + }); + + it('should return 404 when the Thing has no properties', async () => { + const emptyServer = new ThingServer( + new Thing({ title: 'No Properties' }), + ); + await new Promise((resolve) => { + emptyServer.server = emptyServer.app.listen(0, resolve); + }); + + try { + const response = await fetch( + `http://localhost:${emptyServer.server.address().port}/properties`, + { headers: { Accept: 'text/event-stream' } }, + ); + assert.equal(response.status, 404); + } finally { + emptyServer.stop(); + } + }); + }); + describe('GET /properties/:invalidname', () => { it('should return 404 for an invalid property name', async () => { const response = await fetch(baseUrl + '/properties/foo'); diff --git a/test/thing.test.js b/test/thing.test.js index 2506e07..debcb81 100644 --- a/test/thing.test.js +++ b/test/thing.test.js @@ -83,6 +83,12 @@ describe('Thing', () => { href: 'properties', op: ['readallproperties', 'writemultipleproperties'], }, + { + href: 'properties', + op: ['observeallproperties', 'unobserveallproperties'], + contentType: 'application/json', + subprotocol: 'sse', + }, { href: 'actions', op: 'queryallactions' }, ], }); @@ -99,6 +105,25 @@ describe('Thing', () => { { href: 'properties', op: ['readallproperties'] }, ]); }); + + it('should omit observeallproperties when no readable property is observable', () => { + const thing = new Thing({ + title: 'Unobservable Thing', + properties: { + status: { type: 'string' }, + token: { type: 'string', writeOnly: true, observable: true }, + }, + }); + + const td = thing.getThingDescription(); + assert.equal( + td.forms.some( + (form) => + Array.isArray(form.op) && form.op.includes('observeallproperties'), + ), + false, + ); + }); }); describe('setPropertyReadHandler', () => {