0

When I create a JsonClient in node I do the following:

var client = restify.createJsonClient({
  url: 'https://www.domain.com:4321/api'
});

Once I've done that, I make calls like so:

client.post('/service/path', { });

Which seems right. I expect that the path called would be something like https://www.domain.com:4321/api/service/path. However, what is happening is that the client is throwing away the /api base path and calling https://www.domain.com:4321/service/path.

I don't get it - I'm inserting the client URL into a config file, so that I can change hosts without any hassle; Now that I need a base path, I need to change the code as well as the config.

Bruno Brant
  • 8,226
  • 7
  • 45
  • 90
  • Ha! I just realized you never even asked a question. My folly in answering that which was never asked. – HeadCode Sep 12 '16 at 04:51
  • @headcode Really don't get this community anymore. You did answered, and I just forgot to accept it. I also did some due diligence and opened an issue on restify git, to which developers responded that, indeed, the behavior is misleading. – Bruno Brant Sep 13 '16 at 15:50

1 Answers1

0

If you put a wrapper around the restify JsonClient stuff you could do it with minimal code change and the config would, I think, work the way you want it.

Create a library file myClient.js

'use strict';
var restify = require('restify');
var jsonClient = null;

module.exports = {
    createJsonClient: function(opts){
        var opts = opts || {};
        var url = opts.url;
        var parts = url.split('/');
        var main_url = parts[0] + '//' + parts[2];
        var basePath = parts[3] ? parts[3] : '';
        jsonClient = restify.createJsonClient({url: main_url});

        return {
            get: function(path, cb){
                var adjusted_path = '/' + basePath + path;
                jsonClient.get(adjusted_path, function(err2, req2, res2, obj2){
                    return cb(err2, req2, res2, obj2);
                });
            }
        }
    }
}

Then use it like this.

var myClientWrapper = require('./lib/myClient');
var client = myClientWrapper.createJsonClient({url: 'http://localhost:8000/api'});

client.get('/service/path/one', function(err, req, res, obj){
    if(err){
        console.log(err.message);
        return;
    }
    console.log(res.body);
});

It could use some more error checking and the url parsing is a little brittle, but it does work. I tried it out. Of course, I only wrapped the get function but you can see how it would work for the others.

HeadCode
  • 2,770
  • 1
  • 14
  • 26
  • Since this happens to every restify client, I created a generic wrapper and helper construction functions for every method. – Bruno Brant Sep 13 '16 at 15:54