Merge pull request #2312 from xhh/js-object

[JavaScript] Handle arbitrary object in JavaScript client
This commit is contained in:
wing328
2016-03-06 22:43:14 +08:00
12 changed files with 439 additions and 184 deletions

View File

@@ -315,7 +315,10 @@
case 'Date':
return this.parseDate(String(data));
default:
if (typeof type === 'function') {
if (type === Object) {
// generic object, return directly
return data;
} else if (typeof type === 'function') {
// for model type like: User
var model = type.constructFromObject(data);
return model;

View File

@@ -6,7 +6,7 @@
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('./ApiClient'){{#models}}, require('./model/{{importPath}}'){{/models}}{{#apiInfo}}{{#apis}}, require('./api/{{importPath}}'){{/apis}}{{/apiInfo}});
}
}(function(ApiClient{{#models}}, {{importPath}}{{/models}}{{#apiInfo}}{{#apis}}, {{importPath}}{{/apis}}{{/apiInfo}}) {
}(function(ApiClient{{#models}}{{#model}}, {{classFilename}}{{/model}}{{/models}}{{#apiInfo}}{{#apis}}, {{importPath}}{{/apis}}{{/apiInfo}}) {
'use strict';
return {

View File

@@ -306,7 +306,10 @@
case 'Date':
return this.parseDate(String(data));
default:
if (typeof type === 'function') {
if (type === Object) {
// generic object, return directly
return data;
} else if (typeof type === 'function') {
// for model type like: User
var model = type.constructFromObject(data);
return model;

View File

@@ -1,18 +1,18 @@
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['../ApiClient', '../model/Pet'], factory);
define(['../ApiClient', '../model/Pet', '../model/InlineResponse200'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'), require('../model/Pet'));
module.exports = factory(require('../ApiClient'), require('../model/Pet'), require('../model/InlineResponse200'));
} else {
// Browser globals (root is window)
if (!root.SwaggerPetstore) {
root.SwaggerPetstore = {};
}
root.SwaggerPetstore.PetApi = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Pet);
root.SwaggerPetstore.PetApi = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.Pet, root.SwaggerPetstore.InlineResponse200);
}
}(this, function(ApiClient, Pet) {
}(this, function(ApiClient, Pet, InlineResponse200) {
'use strict';
var PetApi = function PetApi(apiClient) {
@@ -323,6 +323,45 @@
}
/**
* Fake endpoint to test inline arbitrary object return by 'Find pet by ID'
* Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
* @param {Integer} petId ID of pet that needs to be fetched
* @param {function} callback the callback function, accepting three arguments: error, data, response
* data is of type: InlineResponse200
*/
self.getPetByIdInObject = function(petId, callback) {
var postBody = null;
// verify the required parameter 'petId' is set
if (petId == null) {
throw "Missing the required parameter 'petId' when calling getPetByIdInObject";
}
var pathParams = {
'petId': petId
};
var queryParams = {
};
var headerParams = {
};
var formParams = {
};
var authNames = ['petstore_auth', 'api_key'];
var contentTypes = [];
var accepts = ['application/json', 'application/xml'];
var returnType = InlineResponse200;
return this.apiClient.callApi(
'/pet/{petId}?response=inline_arbitrary_object', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType, callback
);
}
/**
* Fake endpoint to test byte array return by 'Find pet by ID'
* Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions

View File

@@ -88,6 +88,38 @@
}
/**
* Fake endpoint to test arbitrary object return by 'Get inventory'
* Returns an arbitrary object which is actually a map of status codes to quantities
* @param {function} callback the callback function, accepting three arguments: error, data, response
* data is of type: Object
*/
self.getInventoryInObject = function(callback) {
var postBody = null;
var pathParams = {
};
var queryParams = {
};
var headerParams = {
};
var formParams = {
};
var authNames = ['api_key'];
var contentTypes = [];
var accepts = ['application/json', 'application/xml'];
var returnType = Object;
return this.apiClient.callApi(
'/store/inventory?response=arbitrary_object', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType, callback
);
}
/**
* Place an order for a pet
*

View File

@@ -1,19 +1,22 @@
(function(factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['./ApiClient', './model/Order', './model/User', './model/Category', './model/Tag', './model/Pet', './api/UserApi', './api/StoreApi', './api/PetApi'], factory);
define(['./ApiClient', './model/Order', './model/SpecialModelName', './model/User', './model/Category', './model/ObjectReturn', './model/InlineResponse200', './model/Tag', './model/Pet', './api/UserApi', './api/StoreApi', './api/PetApi'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('./ApiClient'), require('./model/Order'), require('./model/User'), require('./model/Category'), require('./model/Tag'), require('./model/Pet'), require('./api/UserApi'), require('./api/StoreApi'), require('./api/PetApi'));
module.exports = factory(require('./ApiClient'), require('./model/Order'), require('./model/SpecialModelName'), require('./model/User'), require('./model/Category'), require('./model/ObjectReturn'), require('./model/InlineResponse200'), require('./model/Tag'), require('./model/Pet'), require('./api/UserApi'), require('./api/StoreApi'), require('./api/PetApi'));
}
}(function(ApiClient, Order, User, Category, Tag, Pet, UserApi, StoreApi, PetApi) {
}(function(ApiClient, Order, SpecialModelName, User, Category, ObjectReturn, InlineResponse200, Tag, Pet, UserApi, StoreApi, PetApi) {
'use strict';
return {
ApiClient: ApiClient,
Order: Order,
SpecialModelName: SpecialModelName,
User: User,
Category: Category,
ObjectReturn: ObjectReturn,
InlineResponse200: InlineResponse200,
Tag: Tag,
Pet: Pet,
UserApi: UserApi,

View File

@@ -0,0 +1,104 @@
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([undefined, '../ApiClient'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(undefined, require('../ApiClient'));
} else {
// Browser globals (root is window)
if (!root.SwaggerPetstore) {
root.SwaggerPetstore = {};
}
factory(root.SwaggerPetstore, root.SwaggerPetstore.ApiClient);
}
}(this, function(module, ApiClient) {
'use strict';
var InlineResponse200 = function InlineResponse200(id) {
/**
* datatype: Integer
* required
**/
this['id'] = id;
};
InlineResponse200.constructFromObject = function(data) {
if (!data) {
return null;
}
var _this = new InlineResponse200();
if (data['name']) {
_this['name'] = ApiClient.convertToType(data['name'], 'String');
}
if (data['id']) {
_this['id'] = ApiClient.convertToType(data['id'], 'Integer');
}
if (data['category']) {
_this['category'] = ApiClient.convertToType(data['category'], Object);
}
return _this;
}
/**
* @return {String}
**/
InlineResponse200.prototype.getName = function() {
return this['name'];
}
/**
* @param {String} name
**/
InlineResponse200.prototype.setName = function(name) {
this['name'] = name;
}
/**
* @return {Integer}
**/
InlineResponse200.prototype.getId = function() {
return this['id'];
}
/**
* @param {Integer} id
**/
InlineResponse200.prototype.setId = function(id) {
this['id'] = id;
}
/**
* @return {Object}
**/
InlineResponse200.prototype.getCategory = function() {
return this['category'];
}
/**
* @param {Object} category
**/
InlineResponse200.prototype.setCategory = function(category) {
this['category'] = category;
}
if (module) {
module.InlineResponse200 = InlineResponse200;
}
return InlineResponse200;
}));

View File

@@ -0,0 +1,63 @@
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([undefined, '../ApiClient'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(undefined, require('../ApiClient'));
} else {
// Browser globals (root is window)
if (!root.SwaggerPetstore) {
root.SwaggerPetstore = {};
}
factory(root.SwaggerPetstore, root.SwaggerPetstore.ApiClient);
}
}(this, function(module, ApiClient) {
'use strict';
var ObjectReturn = function ObjectReturn() {
};
ObjectReturn.constructFromObject = function(data) {
if (!data) {
return null;
}
var _this = new ObjectReturn();
if (data['return']) {
_this['return'] = ApiClient.convertToType(data['return'], 'Integer');
}
return _this;
}
/**
* @return {Integer}
**/
ObjectReturn.prototype.getReturn = function() {
return this['return'];
}
/**
* @param {Integer} _return
**/
ObjectReturn.prototype.setReturn = function(_return) {
this['return'] = _return;
}
if (module) {
module.ObjectReturn = ObjectReturn;
}
return ObjectReturn;
}));

View File

@@ -0,0 +1,63 @@
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([undefined, '../ApiClient'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(undefined, require('../ApiClient'));
} else {
// Browser globals (root is window)
if (!root.SwaggerPetstore) {
root.SwaggerPetstore = {};
}
factory(root.SwaggerPetstore, root.SwaggerPetstore.ApiClient);
}
}(this, function(module, ApiClient) {
'use strict';
var SpecialModelName = function SpecialModelName() {
};
SpecialModelName.constructFromObject = function(data) {
if (!data) {
return null;
}
var _this = new SpecialModelName();
if (data['$special[property.name]']) {
_this['$special[property.name]'] = ApiClient.convertToType(data['$special[property.name]'], 'Integer');
}
return _this;
}
/**
* @return {Integer}
**/
SpecialModelName.prototype.getSpecialPropertyName = function() {
return this['$special[property.name]'];
}
/**
* @param {Integer} specialPropertyName
**/
SpecialModelName.prototype.setSpecialPropertyName = function(specialPropertyName) {
this['$special[property.name]'] = specialPropertyName;
}
if (module) {
module.SpecialModelName = SpecialModelName;
}
return SpecialModelName;
}));

View File

@@ -1,188 +1,88 @@
if (typeof module === 'object' && module.exports) {
var expect = require('expect.js');
var SwaggerPetstore = require('../../src/index');
}
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD.
define(['expect.js', '../../src/index'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
factory(require('expect.js'), require('../../src/index'));
} else {
// Browser globals (root is window)
factory(root.expect, root.SwaggerPetstore);
}
}(this, function(expect, SwaggerPetstore) {
'use strict';
var api;
var api;
beforeEach(function() {
api = new SwaggerPetstore.PetApi();
});
beforeEach(function() {
api = new SwaggerPetstore.PetApi();
});
var createRandomPet = function() {
var id = new Date().getTime();
var pet = new SwaggerPetstore.Pet();
pet.setId(id);
pet.setName("gorilla" + id);
var createRandomPet = function() {
var id = new Date().getTime();
var pet = new SwaggerPetstore.Pet();
pet.setId(id);
pet.setName("pet" + id);
var category = new SwaggerPetstore.Category();
category.setName("really-happy");
pet.setCategory(category);
var category = new SwaggerPetstore.Category();
category.setId(id);
category.setName("category" + id);
pet.setCategory(category);
pet.setStatus('available');
var photos = ["http://foo.bar.com/1", "http://foo.bar.com/2"];
pet.setPhotoUrls(photos);
pet.setStatus('available');
var photos = ["http://foo.bar.com/1", "http://foo.bar.com/2"];
pet.setPhotoUrls(photos);
return pet;
};
return pet;
};
describe('PetApi', function() {
it('should create and get pet', function(done) {
var pet = createRandomPet();
api.addPet({body: pet}, function(error) {
if (error) throw error;
api.getPetById(pet.id, function(error, fetched, response) {
describe('PetApi', function() {
it('should create and get pet', function(done) {
var pet = createRandomPet();
api.addPet({body: pet}, function(error) {
if (error) throw error;
expect(response.status).to.be(200);
expect(response.ok).to.be(true);
expect(response.get('Content-Type')).to.be('application/json');
expect(fetched).to.be.ok();
expect(fetched.id).to.be(pet.id);
expect(fetched.getPhotoUrls()).to.eql(pet.getPhotoUrls());
expect(fetched.getCategory()).to.be.ok();
expect(fetched.getCategory().getName()).to.be(pet.getCategory().getName());
api.getPetById(pet.id, function(error, fetched, response) {
if (error) throw error;
expect(response.status).to.be(200);
expect(response.ok).to.be(true);
expect(response.get('Content-Type')).to.be('application/json');
api.deletePet(pet.id);
done();
expect(fetched).to.be.a(SwaggerPetstore.Pet);
expect(fetched.id).to.be(pet.id);
expect(fetched.getPhotoUrls()).to.eql(pet.getPhotoUrls());
expect(fetched.getCategory()).to.be.a(SwaggerPetstore.Category);
expect(fetched.getCategory().getName()).to.be(pet.getCategory().getName());
api.deletePet(pet.id);
done();
});
});
});
it('getPetByIdInObject', function(done) {
var pet = createRandomPet();
api.addPet({body: pet}, function(error) {
if (error) throw error;
api.getPetByIdInObject(pet.id, function(error, fetched) {
if (error) throw error;
expect(fetched).to.be.a(SwaggerPetstore.InlineResponse200);
expect(fetched.id).to.be(pet.id);
expect(fetched.name).to.be(pet.name);
var categoryObj = fetched.category;
expect(categoryObj).to.be.a(Object);
expect(categoryObj).not.to.be.a(SwaggerPetstore.Category);
expect(categoryObj.id).to.be(pet.getCategory().getId());
expect(categoryObj.name).to.be(pet.getCategory().getName());
api.deletePet(pet.id);
done();
});
});
});
});
});
/*
@Test
public void testUpdatePet() throws Exception {
Pet pet = createRandomPet();
pet.setName("programmer");
api.updatePet(pet);
Pet fetched = api.getPetById(pet.getId());
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
}
@Test
public void testFindPetsByStatus() throws Exception {
Pet pet = createRandomPet();
pet.setName("programmer");
pet.setStatus(Pet.StatusEnum.AVAILABLE);
api.updatePet(pet);
List<Pet> pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"}));
assertNotNull(pets);
boolean found = false;
for (Pet fetched : pets) {
if (fetched.getId().equals(pet.getId())) {
found = true;
break;
}
}
assertTrue(found);
}
@Test
public void testFindPetsByTags() throws Exception {
Pet pet = createRandomPet();
pet.setName("monster");
pet.setStatus(Pet.StatusEnum.AVAILABLE);
List<Tag> tags = new ArrayList<Tag>();
Tag tag1 = new Tag();
tag1.setName("friendly");
tags.add(tag1);
pet.setTags(tags);
api.updatePet(pet);
List<Pet> pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"}));
assertNotNull(pets);
boolean found = false;
for (Pet fetched : pets) {
if (fetched.getId().equals(pet.getId())) {
found = true;
break;
}
}
assertTrue(found);
}
@Test
public void testUpdatePetWithForm() throws Exception {
Pet pet = createRandomPet();
pet.setName("frank");
api.addPet(pet);
Pet fetched = api.getPetById(pet.getId());
api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null);
Pet updated = api.getPetById(fetched.getId());
assertEquals(updated.getName(), "furt");
}
@Test
public void testDeletePet() throws Exception {
Pet pet = createRandomPet();
api.addPet(pet);
Pet fetched = api.getPetById(pet.getId());
api.deletePet(fetched.getId(), null);
try {
fetched = api.getPetById(fetched.getId());
fail("expected an error");
} catch (ApiException e) {
assertEquals(404, e.getCode());
}
}
@Test
public void testUploadFile() throws Exception {
Pet pet = createRandomPet();
api.addPet(pet);
File file = new File("hello.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("Hello world!");
writer.close();
api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath()));
}
@Test
public void testEqualsAndHashCode() {
Pet pet1 = new Pet();
Pet pet2 = new Pet();
assertTrue(pet1.equals(pet2));
assertTrue(pet2.equals(pet1));
assertTrue(pet1.hashCode() == pet2.hashCode());
assertTrue(pet1.equals(pet1));
assertTrue(pet1.hashCode() == pet1.hashCode());
pet2.setName("really-happy");
pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}));
assertFalse(pet1.equals(pet2));
assertFalse(pet2.equals(pet1));
assertFalse(pet1.hashCode() == (pet2.hashCode()));
assertTrue(pet2.equals(pet2));
assertTrue(pet2.hashCode() == pet2.hashCode());
pet1.setName("really-happy");
pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}));
assertTrue(pet1.equals(pet2));
assertTrue(pet2.equals(pet1));
assertTrue(pet1.hashCode() == pet2.hashCode());
assertTrue(pet1.equals(pet1));
assertTrue(pet1.hashCode() == pet1.hashCode());
}
}
*/
}));

View File

@@ -0,0 +1,41 @@
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD.
define(['expect.js', '../../src/index'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
factory(require('expect.js'), require('../../src/index'));
} else {
// Browser globals (root is window)
factory(root.expect, root.SwaggerPetstore);
}
}(this, function(expect, SwaggerPetstore) {
'use strict';
var api;
beforeEach(function() {
api = new SwaggerPetstore.StoreApi();
});
describe('StoreApi', function() {
it('getInventoryInObject', function(done) {
api.getInventoryInObject(function(error, obj) {
if (error) throw error;
expect(obj).to.be.a(Object);
var hasKey = false;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
hasKey = true;
expect(obj[key]).to.be.a('number');
}
}
expect(hasKey).to.be(true);
done();
});
});
});
}));

View File

@@ -24,13 +24,17 @@
<script src="../src/model/Category.js"></script>
<script src="../src/model/Tag.js"></script>
<script src="../src/model/InlineResponse200.js"></script>
<script src="../src/model/Pet.js"></script>
<script src="../src/model/Order.js"></script>
<script src="../src/model/User.js"></script>
<script src="../src/api/PetApi.js"></script>
<script src="../src/api/StoreApi.js"></script>
<script src="ApiClientTest.js"></script>
<script src="api/PetApiTest.js"></script>
<script src="api/StoreApiTest.js"></script>
<script>
mocha.checkLeaks();