Search code examples
node.jsexpressmicroservices

How to Send a Response Using Seneca and Express


I'm using Seneca to route API calls and express to serve my files. The problem is I can't seem to find a way to send a response back to the client after getting my data from the API. With express, I would just use res.send, but since I'm in the Seneca context I can't. Haven't found any reference to this issue in the documentation.

"use strict"; 
const bodyParser  = require('body-parser');
const express = require('express');
const jsonp = require('jsonp-express');
const Promise = require('bluebird');
const path = require('path');
const seneca = require('seneca')();
const app = express();

module.exports = (function server( options ) {   

    seneca.add('role:api,cmd:getData', getData);

    seneca.act('role:web',{use:{
        prefix: '/api',
        pin: {role:'api',cmd:'*'},
        map:{
            getData: {GET:true}          // explicitly accepting GETs
        }
     }});

     app.use( seneca.export('web') )

     app.use(express.static(path.join(__dirname, '../../dist/js')))
     app.use(express.static(path.join(__dirname, '../../dist/public')))

     app.listen(3002, function () {
         console.log('listening on port 3002');
     });

    function getData(arg, done){
        //Getting data from somewhere....

        //Here I would like to send back a response to the client.            
     }
 }())    

Solution

  • Looks like the 'web' related functionality is now moved into module 'seneca-web' along with separate adapter for express. I got the below modified version to work.

    "use strict";
    
    const express = require('express');
    const app = express();
    const seneca = require('seneca')({ log: 'silent' });
    const web = require('seneca-web');
    
    let routes = [{
      prefix: '/api',
      pin: 'role:api,cmd:*',
      map: {
        getData: {
          GET: true
        }
      }
    }];
    
    let config = {
      context: app,
      routes: routes,
      adapter: require('seneca-web-adapter-express')
    };
    
    seneca.add('role:api,cmd:getData', getData);
    seneca.use(web, config);
    
    function getData(arg, done){
        done(null, {foo: 'bar'});
    }
    
    seneca.ready(() => {
      app.listen(3002, () => {
        console.log('listening on port 3002');
      });
    });