Skip to content

Commit 1162a41

Browse files
author
Phil Hess
committed
Update models
1 parent a54fc70 commit 1162a41

File tree

2 files changed

+32
-11
lines changed

2 files changed

+32
-11
lines changed

index.js

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
(function() {
22
var client = require('swagger-client'),
3+
util = require('util'),
34
config = {
45
fileOutput: null,
56
filePath: null,
@@ -39,30 +40,50 @@
3940
model,
4041
modelName,
4142
property,
42-
script;
43+
script,
44+
scriptModel,
45+
scriptValidation;
46+
script = [];
4347
if (swagger.ready === true) {
44-
script = [
45-
'(function () {'
46-
];
4748
for (apiName in swagger.apis) {
4849
api = swagger.apis[apiName];
4950
for (modelName in api.models) {
5051
model = api.models[modelName];
51-
script.push.apply(script, [
52-
' var ' + model.name + ' = Backbone.Model.extend({',
53-
' defaults: {'
54-
]);
52+
scriptModel = [];
53+
scriptValidation = [];
5554
for (var _i = 0, _len = model.properties.length; _i < _len; _i++) {
5655
property = model.properties[_i];
57-
script.push(' ' + property.name + ': ' + property.defaultValue);
56+
if (scriptModel.length > 0) {
57+
scriptModel[scriptModel.length - 1] += ',';
58+
}
59+
if (property.defaultValue !== null) {
60+
property.defaultValue = util.format('\'%s\'', property.defaultValue);
61+
}
62+
scriptModel.push(util.format(' %s: %s', property.name, property.defaultValue));
63+
if (property.required) {
64+
scriptValidation.push.apply(scriptValidation, [
65+
util.format(' if (!attrs.%s) {', property.name),
66+
util.format(' return \'Please fill %s field.\';', property.name),
67+
' }'
68+
]);
69+
}
5870
}
5971
script.push.apply(script, [
72+
' var ' + model.name + ' = Backbone.Model.extend({',
73+
' urlRoot: \'' + api.basePath + '/' + api.path + '\',',
74+
' url: function() {',
75+
' return this.urlRoot + \'/\' + this.id;',
76+
' },',
77+
' defaults: {',
78+
scriptModel.join('\n'),
79+
' },',
80+
' validate: function (attrs) {',
81+
scriptValidation.join('\n'),
6082
' }',
6183
' });'
6284
]);
6385
}
6486
}
65-
script.push('})();');
6687
return reply(script.join('\n')).type('application/javascript');
6788
}
6889
},

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "hapi-swagger-models",
3-
"version": "0.1.1",
3+
"version": "0.1.2",
44
"description": "Generate Backbone Models from a Swagger API",
55
"main": "index.js",
66
"scripts": {

0 commit comments

Comments
 (0)