w3c/web-of-things-framework

[Refactor] Use URL router to decouple the API

jollen opened this issue · 0 comments

Introduction

  • Reuse of service component. Use epxress.Router() to allow WoT server to completely decouple the server API (URL routing) from it's server logic (application).
  • Easy integration. One service component (API implementation) can be integrated (mounted) to various WoT server implementations.
  • Consider examples/http_demo/sumulator.js, the refactored programming style is as the following.
var simulator = function (thing, port) {
    logger.debug("starting HTTP device simulator for " + thing.name);

    // create express instance
    var app = express();

    // keep reference to thing model
    app.model = things.model;

    // keep reference to config
    app.config = config;

    // mount thing's URL router to express application
    app.use('/', require('service'));

    // create HTTP server and listen incoming request
    var server = http.createServer(app);

    server.listen(port, function () {
        logger.info('HTTP device simulator listener for thing ' + thing.name + ' started on port ' + port);
    });
}

exports.start = function start() {
    logger.debug('Start device simulator to communicate with WoT via the HTTP protocol');
    var door_device = new simulator(door, 8890);
    door.model.properties.battery_value();
    door.model.events.bell();
}

Develops can also mount things URL router to their existing Node.js application. For example,

var app = express();

// Create my 'ParseServer' instance.
var api = new ParseServer({
  ...
});
// Mount my 'ParseServer' URL router.
app.use('/parse', api);

// Mount my WoT thing's URL router under the relative path '/wot'
app.use('/wot', require('service'));

API implementation is stored in JavaScript module file service.js, can is exported via express.Router(). For example,

// Filename: service.js
var create = function(req, res, next) {
 ...
}

router.post('/', create);

module.exports = {
  router: router
};

Implementation

zsoltpardi's comment (#65) with regards to separate demos.

The original demo "http_demo" was kept. A new demo was created "http_express_demo". The "http_express_demo" demonstrate the Express based design and implementation. And it also demonstrates of how to use Express router to decouple the API implementation from the WoT server logic. The API router can then be reused by similar device WoT servers, said "http_express_demo2".

Test

A simple CLI test case using curl:

$ curl -X POST http://localhost:8890/switch12/property_get

Response:

{"thing":"switch12"}

URI Styling

zsoltpardi's comment (#65) with regards to URI style.

The current implementation put the thing name before action. If the URI is in the syntax GET /username/status, the 'username' is considered as an instance (resource name), and 'status' is its property. It shall be more REST style.