Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 54 additions & 2 deletions src/thing-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
13 changes: 13 additions & 0 deletions src/thing.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
66 changes: 66 additions & 0 deletions test/thing-server.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
25 changes: 25 additions & 0 deletions test/thing.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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' },
],
});
Expand All @@ -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', () => {
Expand Down
Loading