From c22f169b9f294a4634f6ff42439271be54a09615 Mon Sep 17 00:00:00 2001 From: Ben Francis Date: Tue, 24 Nov 2026 21:51:24 +0000 Subject: [PATCH] HTTP writemultipleproperties operation - closes #22 --- README.md | 4 ++ src/thing-server.js | 113 ++++++++++++++++++++++++-------------- src/thing.js | 93 +++++++++++++++++++++---------- test/thing-server.test.js | 63 +++++++++++++++++++++ test/thing.test.js | 68 ++++++++++++++++++++++- 5 files changed, 272 insertions(+), 69 deletions(-) diff --git a/README.md b/README.md index a9fa964..20e45f9 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,10 @@ thing.setPropertyReadHandler('on', async function () { thing.setPropertyReadHandler('level', async function () { return 50; }); + +thing.setPropertyWriteHandler('on', async function (value) { + // Update the lamp state. +}); ``` ### Actions diff --git a/src/thing-server.js b/src/thing-server.js index fd9910a..93f33a0 100644 --- a/src/thing-server.js +++ b/src/thing-server.js @@ -31,28 +31,6 @@ class ThingServer { }, ); - this.app.get( - '/properties', - /** - * Read All Properties - * - * @param {Request} _request - * @param {Response} response - */ - async (_request, response) => { - if (this.thing.properties.size === 0) { - response.status(404).send(); - return; - } - try { - const values = await this.thing.readAllProperties(); - response.status(200).json(values); - } catch { - response.status(500).send(); - } - }, - ); - this.app.get( '/properties/:name', /** @@ -126,6 +104,61 @@ class ThingServer { }, ); + this.app.get( + '/properties', + /** + * Read All Properties + * + * @param {Request} _request + * @param {Response} response + */ + async (_request, response) => { + if (this.thing.properties.size === 0) { + response.status(404).send(); + return; + } + try { + const values = await this.thing.readAllProperties(); + response.status(200).json(values); + } catch { + response.status(500).send(); + } + }, + ); + + this.app.put( + '/properties', + /** + * Write Multiple Properties + * + * @param {Request} request + * @param {Response} response + */ + async (request, response) => { + try { + await this.thing.writeMultipleProperties(request.body); + } catch (error) { + const errorMessage = + error instanceof Error ? error.message : 'InternalError'; + switch (errorMessage) { + case 'NotFoundError': + response.status(404).send(); + break; + case 'BadRequest': + response.status(400).send(); + break; + case 'InternalError': + response.status(500).send(); + break; + default: + response.status(500).send(); + } + return; + } + response.status(204).send(); + }, + ); + this.app.post( '/actions/:name', /** @@ -199,27 +232,10 @@ class ThingServer { }, ); - this.app.get( - '/actions', - /** - * Query All Actions - * - * @param {Request} _request - * @param {Response} response - */ - (_request, response) => { - if (this.thing.actions.size === 0) { - response.status(404).send(); - return; - } - response.status(200).json(this.thing.queryAllActions()); - }, - ); - this.app.get( '/actions/:name/:actionID', /** - * Query Action Status + * Query Action * * @param {Request} request * @param {Response} response @@ -282,6 +298,23 @@ class ThingServer { response.status(204).send(); }, ); + + this.app.get( + '/actions', + /** + * Query All Actions + * + * @param {Request} _request + * @param {Response} response + */ + (_request, response) => { + if (this.thing.actions.size === 0) { + response.status(404).send(); + return; + } + response.status(200).json(this.thing.queryAllActions()); + }, + ); } /** diff --git a/src/thing.js b/src/thing.js index f94160f..b30d603 100644 --- a/src/thing.js +++ b/src/thing.js @@ -350,9 +350,13 @@ class Thing { // If properties are defined then add a properties member if (Object.keys(properties).length > 0) { thingDescription.properties = properties; - thingDescription.forms = [ - { href: 'properties', op: ['readallproperties'] }, - ]; + const propertyOperations = ['readallproperties']; + if ( + [...this.properties.values()].some((property) => !property.readOnly) + ) { + propertyOperations.push('writemultipleproperties'); + } + thingDescription.forms = [{ href: 'properties', op: propertyOperations }]; } // If actions are defined then add an actions member if (Object.keys(actions).length > 0) { @@ -395,7 +399,7 @@ class Thing { } /** - * Set Action Handler. + * Set Action Invoke Handler. * * @param {string} name The name of the action to handle. * @param {(value: any, signal?: AbortSignal) => Promise} handler An async function to handle action invocations. @@ -424,6 +428,23 @@ class Thing { return property.read(); } + /** + * Write Property. + * + * @param {string} name The name of the property to write. + * @param {any} value The property value to write. + * @returns {Promise} A Promise that resolves once the property has been + * written successfully. + */ + async writeProperty(name, value) { + let property = this.properties.get(name); + if (!property) { + console.error(`No property called ${name} could be found`); + throw new Error('NotFoundError'); + } + return property.write(value); + } + /** * Read All Properties. * @@ -443,20 +464,36 @@ class Thing { } /** - * Write Property. + * Write Multiple Properties. * - * @param {string} name The name of the property to write. - * @param {any} value The property value to write. - * @returns {Promise} A Promise that resolves once the property has been + * @param {Record} values The property values keyed by property name. + * @returns {Promise} A Promise that resolves once all properties have been * written successfully. */ - async writeProperty(name, value) { - let property = this.properties.get(name); - if (!property) { - console.error(`No property called ${name} could be found`); - throw new Error('NotFoundError'); + async writeMultipleProperties(values) { + if ( + values === null || + typeof values !== 'object' || + Array.isArray(values) + ) { + throw new Error('BadRequest'); + } + + const entries = Object.entries(values); + for (const [name] of entries) { + const property = this.properties.get(name); + if (!property) { + console.error(`No property called ${name} could be found`); + throw new Error('NotFoundError'); + } + if (property.readOnly === true) { + throw new Error('BadRequest'); + } + } + + for (const [name, value] of entries) { + await this.writeProperty(name, value); } - return property.write(value); } /** @@ -510,20 +547,6 @@ class Thing { return status; } - /** - * Get the statuses of all action requests, grouped by action name. - * - * @returns {Record>} The current statuses. - */ - queryAllActions() { - /** @type {Record>} */ - const statuses = {}; - for (const [name, action] of this.actions) { - statuses[name] = action.queryAll(); - } - return statuses; - } - /** * Cancel an action request. * @@ -538,6 +561,20 @@ class Thing { } action.cancelAction(actionID); } + + /** + * Get the statuses of all action requests, grouped by action name. + * + * @returns {Record>} The current statuses. + */ + queryAllActions() { + /** @type {Record>} */ + const statuses = {}; + for (const [name, action] of this.actions) { + statuses[name] = action.queryAll(); + } + return statuses; + } } export default Thing; diff --git a/test/thing-server.test.js b/test/thing-server.test.js index c0383d7..c14eda6 100644 --- a/test/thing-server.test.js +++ b/test/thing-server.test.js @@ -84,6 +84,10 @@ describe('ThingServer', () => { const td = await response.json(); assert.strictEqual(td.title, 'Test Lamp'); assert.equal(td['@context'], 'https://www.w3.org/2022/wot/td/v1.1'); + assert.deepEqual(td.forms.find(({ href }) => href === 'properties').op, [ + 'readallproperties', + 'writemultipleproperties', + ]); assert.deepEqual(td.securityDefinitions, { nosec_sc: { scheme: 'nosec' }, }); @@ -242,6 +246,65 @@ describe('ThingServer', () => { }); }); + describe('PUT /properties', () => { + it('should write multiple writable properties and reject invalid requests', async () => { + const writtenValues = {}; + const multiPropertyThing = new Thing({ + title: 'Multiple Properties', + properties: { + on: { type: 'boolean' }, + level: { type: 'number' }, + locked: { type: 'boolean', readOnly: true }, + }, + }); + multiPropertyThing.setPropertyWriteHandler('on', async (value) => { + writtenValues.on = value; + }); + multiPropertyThing.setPropertyWriteHandler('level', async (value) => { + writtenValues.level = value; + }); + const multiPropertyServer = new ThingServer(multiPropertyThing); + await new Promise((resolve) => { + multiPropertyServer.server = multiPropertyServer.app.listen(0, resolve); + }); + + try { + const url = `http://localhost:${multiPropertyServer.server.address().port}/properties`; + const options = { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + }; + let response = await fetch(url, { + ...options, + body: JSON.stringify({ on: true, level: 50 }), + }); + assert.equal(response.status, 204); + assert.deepEqual(writtenValues, { on: true, level: 50 }); + + response = await fetch(url, { + ...options, + body: JSON.stringify({ on: false, missing: 1 }), + }); + assert.equal(response.status, 404); + assert.deepEqual(writtenValues, { on: true, level: 50 }); + + response = await fetch(url, { + ...options, + body: JSON.stringify({ locked: true }), + }); + assert.equal(response.status, 400); + + response = await fetch(url, { + ...options, + body: JSON.stringify([]), + }); + assert.equal(response.status, 400); + } finally { + multiPropertyServer.stop(); + } + }); + }); + describe('POST /actions/:name', () => { it('should invoke the action and return its output', async () => { const input = { duration: 3 }; diff --git a/test/thing.test.js b/test/thing.test.js index 735b9fe..63b18bc 100644 --- a/test/thing.test.js +++ b/test/thing.test.js @@ -71,11 +71,26 @@ describe('Thing', () => { }, }, forms: [ - { href: 'properties', op: ['readallproperties'] }, + { + href: 'properties', + op: ['readallproperties', 'writemultipleproperties'], + }, { href: 'actions', op: 'queryallactions' }, ], }); }); + + it('should omit the write operation when all properties are read-only', () => { + const thing = new Thing({ + title: 'Read-only Thing', + properties: { status: { type: 'string', readOnly: true } }, + }); + + const td = thing.getThingDescription(); + assert.deepEqual(td.forms, [ + { href: 'properties', op: ['readallproperties'] }, + ]); + }); }); describe('setPropertyReadHandler', () => { @@ -151,6 +166,57 @@ describe('Thing', () => { }); }); + describe('writeMultipleProperties', () => { + it('should write all requested writable properties', async () => { + const thing = new Thing({ + title: 'Writable Thing', + properties: { + on: { type: 'boolean' }, + level: { type: 'number' }, + locked: { type: 'boolean', readOnly: true }, + }, + }); + const writtenValues = {}; + thing.setPropertyWriteHandler('on', async (value) => { + writtenValues.on = value; + }); + thing.setPropertyWriteHandler('level', async (value) => { + writtenValues.level = value; + }); + + await thing.writeMultipleProperties({ on: true, level: 50 }); + assert.deepEqual(writtenValues, { on: true, level: 50 }); + }); + + it('should reject invalid input before writing any property', async () => { + const thing = new Thing({ + title: 'Writable Thing', + properties: { + on: { type: 'boolean' }, + locked: { type: 'boolean', readOnly: true }, + }, + }); + let written = false; + thing.setPropertyWriteHandler('on', async () => { + written = true; + }); + + await assert.rejects( + () => thing.writeMultipleProperties({ on: true, locked: true }), + /BadRequest/, + ); + await assert.rejects( + () => thing.writeMultipleProperties({ on: true, missing: true }), + /NotFoundError/, + ); + await assert.rejects( + () => thing.writeMultipleProperties(null), + /BadRequest/, + ); + assert.equal(written, false); + }); + }); + describe('setActionInvokeHandler', () => { it('should throw when the action does not exist', () => { const thing = new Thing(partialTD);