Implementing The Block Data Model

There are two possible ways to assign a data model to a block. One is to implement a node.js program which will run on coServ. The other is to use API services. In this chapter, we'll call the first method the local server model and focus on that model.

The local server model is to use a node.js module to serve as the data model of a block. The only function you are required to implement in a node module is the execute() function:

exports.execute = function(ctx, inData, cb)  {
    // your code here
    ...

    // when it's all done, call back to return
    cb({
        errCode: 0,
        message: 'Ok',
        value: {...}
    });
}

The execute() function will be given three arguments to help you get the job done. The first argument is ctx which is a context variable with the following properties:

  • basePath : this is the path pointing to the coServ lib directory.
  • themePath : the website theme direcory.
  • clientType : indicating what kind of device issues the client request. It can be one of the following values: "desktop", "tablet" or "mobile".
  • cookies : the http request cookies.
  • bi : block info. A bunch of information related to this block.

The ctx.bi property has the same contents as the bi variable available to the block template. You can review its content in the block info section of chapter 2 of this guide.

The inData argument is the input data to the block. For example, assuming you have a block '/book/info' which are invoked this way:

http://www.foo.com/book/info/278?showPricing=true&showComments=true

then the 'input' argument will be:

{
    showPricing: true,
    showComments: true
}

The return object

The third argument to the execute() function is the callback function which you should invoke when the job of a local server model is done. coServ would expect you to return an object in the callback with the following properties:

  • errCode : error code. If 0, it means the block server model has process the client request successfully. Any non-zero error codes indicate errors.
  • message : An additional text message to explain the execution result.
  • value : The contents or data returned from the block model.

Not opinionated

As you can see, coServ does not require developers to design data models in some particular way. It only defines a protocol (the execute() function and its return object) for coServ to work with your customized node.js module. That means there are no restrictions. You're free to design the data model any way that works best for you.

results matching ""

    No results matching ""