Last active
August 29, 2015 14:21
-
-
Save laser/049570d7d304448feb23 to your computer and use it in GitHub Desktop.
swagger client wrapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var client = require("swagger-client"); | |
var Promise = require("bluebird"); | |
var _ = require('lodash'); | |
function ServiceClient(url) { | |
this.swagger = new Promise(function (resolve, reject) { | |
var c = new client({ | |
url: url + '/swagger.json', | |
success: function() { | |
var iface = _.reduce(c.apis, function(acc, v, k) { | |
return _.extend({}, acc, _.pick(v, _.keys(v.operations))); | |
}, {}); | |
resolve(iface); | |
} | |
}); | |
c.fail = reject; | |
}); | |
} | |
ServiceClient.prototype.exec = function exec(operationId, params, callback) { | |
function onExecSuccess(o) { | |
var data, err; | |
try { | |
data = JSON.parse(o.data); | |
} | |
catch (thrown) { | |
err = new Error('Error parsing response body-JSON'); | |
} | |
callback(err || null, data); | |
} | |
function onExecFailure(o) { | |
var err; | |
if (o.status === 404) { | |
err = null; | |
} | |
else if (!_.isEmpty(o.data)) { | |
try { | |
err = new Error((JSON.parse(o.data)).message); | |
} catch (thrown) { | |
err = new Error('Error parsing response body-JSON'); | |
} | |
} | |
else { | |
err = new Error('Error calling service method ' + operationId); | |
} | |
callback(err, null); | |
} | |
this.swagger.then(function(iface) { | |
iface[operationId].call(null, params, onExecSuccess, onExecFailure); | |
}); | |
} | |
/////////////////////////////////// | |
// usage | |
//////// | |
var video = new ServiceClient('http://localhost:3000'); | |
video.exec('getVideoById', { videoId: 335817795531 }, function(err, video) { | |
console.log('\nerr: ', err, ' payload: ', video); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment