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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
113 changes: 73 additions & 40 deletions src/thing-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
/**
Expand Down Expand Up @@ -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',
/**
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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());
},
);
}

/**
Expand Down
93 changes: 65 additions & 28 deletions src/thing.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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<any>} handler An async function to handle action invocations.
Expand Down Expand Up @@ -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<void>} 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.
*
Expand All @@ -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<void>} A Promise that resolves once the property has been
* @param {Record<string, any>} values The property values keyed by property name.
* @returns {Promise<void>} 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);
}

/**
Expand Down Expand Up @@ -510,20 +547,6 @@ class Thing {
return status;
}

/**
* Get the statuses of all action requests, grouped by action name.
*
* @returns {Record<string, Array<ActionStatus>>} The current statuses.
*/
queryAllActions() {
/** @type {Record<string, Array<ActionStatus>>} */
const statuses = {};
for (const [name, action] of this.actions) {
statuses[name] = action.queryAll();
}
return statuses;
}

/**
* Cancel an action request.
*
Expand All @@ -538,6 +561,20 @@ class Thing {
}
action.cancelAction(actionID);
}

/**
* Get the statuses of all action requests, grouped by action name.
*
* @returns {Record<string, Array<ActionStatus>>} The current statuses.
*/
queryAllActions() {
/** @type {Record<string, Array<ActionStatus>>} */
const statuses = {};
for (const [name, action] of this.actions) {
statuses[name] = action.queryAll();
}
return statuses;
}
}

export default Thing;
63 changes: 63 additions & 0 deletions test/thing-server.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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' },
});
Expand Down Expand Up @@ -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 };
Expand Down
Loading
Loading