-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathindex.js
More file actions
105 lines (100 loc) · 5.33 KB
/
index.js
File metadata and controls
105 lines (100 loc) · 5.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
(function() {
var client = require('swagger-client'),
util = require('util'),
config = {
fileOutput: null,
filePath: null,
api: null,
format: 'backbone'
}
exports.register = function(plugin, options, next) {
Object.keys(options).forEach(function(k) {
if (config[k] !== undefined) {
config[k] = options[k];
}
});
if (!config.api) {
console.error('API Url Endpoint Required');
return next();
}
if (config.fileOutput) {
console.log('File Writing not yet supported');
return next();
}
if (config.filePath) {
if (config.format === 'backbone') {
plugin.route({
method: 'GET',
path: config.filePath,
config: {
handler: function(request, reply) {
var swagger = new client.SwaggerApi({
url: config.api,
success: function() {
var api,
apiName,
model,
modelName,
property,
script,
scriptModel,
scriptValidation;
script = [];
if (swagger.ready === true) {
for (apiName in swagger.apis) {
api = swagger.apis[apiName];
for (modelName in api.models) {
model = api.models[modelName];
scriptModel = [];
scriptValidation = [];
for (var _i = 0, _len = model.properties.length; _i < _len; _i++) {
property = model.properties[_i];
if (scriptModel.length > 0) {
scriptModel[scriptModel.length - 1] += ',';
}
if (property.defaultValue !== null) {
property.defaultValue = util.format('\'%s\'', property.defaultValue);
}
scriptModel.push(util.format(' %s: %s', property.name, property.defaultValue));
if (property.required) {
scriptValidation.push.apply(scriptValidation, [
util.format(' if (!attrs.%s) {', property.name),
util.format(' return \'Please fill %s field.\';', property.name),
' }'
]);
}
}
script.push.apply(script, [
' var ' + model.name + ' = Backbone.Model.extend({',
' urlRoot: \'' + api.basePath + '/' + api.path + '\',',
' url: function() {',
' return this.urlRoot + \'/\' + this.id;',
' },',
' defaults: {',
scriptModel.join('\n'),
' },',
' validate: function (attrs) {',
scriptValidation.join('\n'),
' }',
' });'
]);
}
}
return reply(script.join('\n')).type('application/javascript');
}
},
failure: function() {
console.log('Swagger API Call failed');
return reply('');
}
});
}
}
})
}
}
}
exports.register.attributes = {
pkg: require('./package')
};
})();