Server API Middleware

This is the Server API Middleware section.

 

Server API Middleware

When you run the Caesar.js server this will expose an extended API to the req and res object of your routes.

Consider the following example:

const server = require('caesarjs').server;
const client = require('caesarjs').client;
const encryptorKey = '33a24560-a43b-44cc-b2bc-9cc0de14a093';
new server(3000, {encryptorKey}).add(
{role: 'calculator', operation: 'sum'},
(req, res) => {
let n1 = req.data.n1;
let n2 = req.data.n2;
let sum = (n1 + n2);
res.caesarJson({sum});
})
.add(
{role: 'calculator', operation: 'subtraction'},
(req, res) => {
let n1 = req.data.n1;
let n2 = req.data.n2;
let subtraction = (n1 - n2);
req.pino.logger.info('Abd the subtraction is:', subtraction);
res.caesarJson({subtraction});
})
.listen();

As you can see from the above service endpoints in the call-back express function the req & res objects extends some extra methods and objects i.e. res.caesarJson and req.data

Let’s go through the documentation as following:

req.data

req.data is an object of un-encrypted data received by the client and made available to you in your route call back function.

req.caesar

req.caesar is an object consisting of the following keys:

req.caesar = {
events,
options
};

events

Events is the instance of an internal events system operating within the Caesar.js server.

Currently 2 events are emitted when the server receives data from the client and when it sends it. These can be listened in the following way.

Receiving data from client:

req.caesar.events.receiveData(function (data) {
console.log('data received by the client', data);
});

Sending data to client:

req.caesar.events.sendData(function (data) {
console.log('data sent from client', data);
});

options

The options object simply returns the options you have supplied to the server at instantiation level. For example:

console.log(req.caesar.options)
// outputs the options provided to server

req.logger

req.logger contains an instance of the npm Pino logger. For example:

req.logger.info('some info here!');

res.caesarJson( dataObject: Object )

If you want to send encrypted data back to the client you must use res.caesarJson( dataObject ) instead of res.json

Leave a Reply

Required fields are marked*

*