Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow the Promise implementation used to be customized #137

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Expand Up @@ -66,6 +66,10 @@ In addition to the common options listed below, `getCustomCode()` *requires* a `
imports:
type: array
description: Typescript definition files to be imported.
promise:
type: string
description: Promise implementation to use [any-promise, native, q, bluebird, ...]
default: any-promise
swagger:
type: object
required: true
Expand All @@ -90,6 +94,9 @@ moduleName:
className:
type: string
description: Provided by your options field
promise:
type: string
description: Expression that will return the chosen Promise implementation
domain:
type: string
description: If all options defined: swagger.schemes[0] + '://' + swagger.host + swagger.basePath
Expand Down
14 changes: 14 additions & 0 deletions lib/codegen.js
Expand Up @@ -30,6 +30,18 @@ var getPathToMethodName = function(opts, m, path){
return m.toLowerCase() + result[0].toUpperCase() + result.substring(1);
};

var getPromiseImplementation = function(opts) {
var promise = opts.promise || 'any-promise';

if ( promise === 'native' ) {
return 'Promise';
} else if ( promise === 'q' ) {
return 'require(\'q\').Promise';
} else {
return 'require(\'' + promise + '\')';
}
};

var getViewForSwagger2 = function(opts, type){
var swagger = opts.swagger;
var authorizedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'COPY', 'HEAD', 'OPTIONS', 'LINK', 'UNLIK', 'PURGE', 'LOCK', 'UNLOCK', 'PROPFIND'];
Expand All @@ -40,6 +52,7 @@ var getViewForSwagger2 = function(opts, type){
moduleName: opts.moduleName,
className: opts.className,
imports: opts.imports,
promise: getPromiseImplementation(opts),
domain: (swagger.schemes && swagger.schemes.length > 0 && swagger.host && swagger.basePath) ? swagger.schemes[0] + '://' + swagger.host + swagger.basePath.replace(/\/+$/g,'') : '',
methods: []
};
Expand Down Expand Up @@ -144,6 +157,7 @@ var getViewForSwagger1 = function(opts, type){
description: swagger.description,
moduleName: opts.moduleName,
className: opts.className,
promise: getPromiseImplementation(opts),
domain: swagger.basePath ? swagger.basePath : '',
methods: []
};
Expand Down
11 changes: 6 additions & 5 deletions package.json
Expand Up @@ -36,14 +36,15 @@
"mustache": "^2.0.0"
},
"devDependencies": {
"any-promise": "^1.3.0",
"final-fs": "~1.6.0",
"grunt": "~0.4.4",
"grunt-contrib-jshint": "~0.9.2",
"grunt-jsonlint": "~1.0.4",
"grunt-vows": "~0.4.1",
"q": "~1.0.1",
"final-fs": "~1.6.0",
"matchdep": "~0.3.0",
"vows": "~0.7.0",
"grunt-jsonlint": "~1.0.4",
"request": "~2.40.0"
"q": "~1.0.1",
"request": "~2.40.0",
"vows": "~0.7.0"
}
}
33 changes: 18 additions & 15 deletions templates/angular-class.mustache
@@ -1,7 +1,7 @@
/*jshint -W069 */
/*global angular:false */
angular.module('{{&moduleName}}', [])
.factory('{{&className}}', ['$q', '$http', '$rootScope', function($q, $http, $rootScope){
.factory('{{&className}}', ['$q', '$http', '$rootScope', function(P, $http, $rootScope){
'use strict';

/**
Expand All @@ -27,7 +27,7 @@ angular.module('{{&moduleName}}', [])
{{/isSecure}}
}

{{&className}}.prototype.request = function(method, url, parameters, body, headers, queryParameters, form, deferred){
{{&className}}.prototype.request = function(method, url, parameters, body, headers, queryParameters, form){
{{#isGET}}
var cached = parameters.$cache && parameters.$cache.get(url);
if(cached !== undefined && parameters.$refresh !== true) {
Expand All @@ -48,19 +48,22 @@ angular.module('{{&moduleName}}', [])
options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
options.transformRequest = {{&className}}.transformRequest;
}
$http(options)
.success(function(data, status, headers, config){
deferred.resolve(data);
if(parameters.$cache !== undefined) {
parameters.$cache.put(url, data, parameters.$cacheItemOpts ? parameters.$cacheItemOpts : {});
}
})
.error(function(data, status, headers, config){
deferred.reject({
status: status,
headers: headers,
config: config,
body: data

return new P(function(resolve, reject) {
$http(options)
.success(function(data, status, headers, config){
resolve(data);
if(parameters.$cache !== undefined) {
parameters.$cache.put(url, data, parameters.$cacheItemOpts ? parameters.$cacheItemOpts : {});
}
})
.error(function(data, status, headers, config){
reject({
status: status,
headers: headers,
config: config,
body: data
});
});
});

Expand Down
12 changes: 4 additions & 8 deletions templates/method.mustache
Expand Up @@ -11,8 +11,7 @@
if(parameters === undefined) {
parameters = {};
}
var deferred = {{#isNode}}Q{{/isNode}}{{^isNode}}$q{{/isNode}}.defer();


var domain = this.domain;
var path = '{{&path}}';

Expand All @@ -25,7 +24,7 @@
if (this.token.isQuery) {
queryParameters[this.token.headerOrQueryName] = this.token.value;
} else if (this.token.headerOrQueryName) {
headers[this.token.headerOrQueryName] = this.token.value;
headers[this.token.headerOrQueryName] = this.token.value;
} else {
headers['Authorization'] = 'Bearer ' + this.token.value;
}
Expand Down Expand Up @@ -91,8 +90,7 @@

{{#required}}
if(parameters['{{&camelCaseName}}'] === undefined){
deferred.reject(new Error('Missing required {{&paramType}} parameter: {{&camelCaseName}}'));
return deferred.promise;
return P.reject(new Error('Missing required {{&paramType}} parameter: {{&camelCaseName}}'));
}
{{/required}}

Expand All @@ -106,7 +104,5 @@
});
}

this.request('{{method}}', domain + path, parameters, body, headers, queryParameters, form, deferred);

return deferred.promise;
return this.request('{{method}}', domain + path, parameters, body, headers, queryParameters, form);
};
37 changes: 20 additions & 17 deletions templates/node-class.mustache
Expand Up @@ -10,7 +10,7 @@ var {{&className}} = (function(){
'use strict';

var request = require('request');
var Q = require('q');
var P = {{&promise}};

function {{&className}}(options){
var domain = (typeof options === 'object') ? options.domain : options;
Expand All @@ -23,7 +23,7 @@ var {{&className}} = (function(){
{{/isSecure}}
}

{{&className}}.prototype.request = function(method, url, parameters, body, headers, queryParameters, form, deferred){
{{&className}}.prototype.request = function(method, url, parameters, body, headers, queryParameters, form){
var req = {
method: method,
uri: url,
Expand All @@ -37,23 +37,26 @@ var {{&className}} = (function(){
if(typeof(body) === 'object' && !(body instanceof Buffer)) {
req.json = true;
}
request(req, function(error, response, body){
if(error) {
deferred.reject(error);
} else {
if(/^application\/(.*\\+)?json/.test(response.headers['content-type'])) {
try {
body = JSON.parse(body);
} catch(e) {}
}
if(response.statusCode === 204) {
deferred.resolve({ response: response });
} else if(response.statusCode >= 200 && response.statusCode <= 299) {
deferred.resolve({ response: response, body: body });

return new P(function(resolve, reject) {
request(req, function(error, response, body){
if(error) {
reject(error);
} else {
deferred.reject({ response: response, body: body });
if(/^application\/(.*\\+)?json/.test(response.headers['content-type'])) {
try {
body = JSON.parse(body);
} catch(e) {}
}
if(response.statusCode === 204) {
resolve({ response: response });
} else if(response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject({ response: response, body: body });
}
}
}
});
});
};

Expand Down