forked from mycrobe/swaggerflowtypes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmakeTypes.js
More file actions
executable file
·191 lines (168 loc) · 5.78 KB
/
makeTypes.js
File metadata and controls
executable file
·191 lines (168 loc) · 5.78 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#! /usr/bin/env node
var Q = require('q');
var _ = require('underscore');
_.mixin(require('underscore.deep'));
var cliArgs = require('command-line-args');
var fs = require('fs');
var path = require('path');
var request = require('request');
var get = function(url, dataCallback) {
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
dataCallback(JSON.parse(body));
} else {
console.log(error);
}
});
};
var getAPIModels = function(apiJson) {
return Q.all(_(apiJson.definitions).mapObject(function(apiDef, apiName) {
var o = {};
o[apiName] = apiDef;
apiDef.id = apiName;
return o;
}));
};
var scalarTypeFunction = function(type) {
return function() { return type; };
};
// maps schema type to a function that takes a schema
// and returns the string type for the schema.
var jsonSchemaTypeMap = {
// 'A JSON array.'
'array': function(array, possibleImports) {
return 'Array<' + jsonSchemaToFlowObject(array.items, possibleImports) + '>';
},
// 'A JSON object.'
'object': function(object, possibleImports) {
return _(object.additionalProperties, possibleImports)
.chain()
.map(function(value, key) {
if (key === 'type') {
// special handling for string-to-value mapping
return ['[key: string]', jsonSchemaTypeMap[value]];
} else if (key === '$ref' && isModelRef(value)) {
return ['[key: string]', extractModelNameFromRef(value)];
} else {
console.error( "don't know how to handle object with additionalProperties key '" + key + "'.");
throw "don't know how to handle object with additionalProperties key '" + key + "'."
}
})
.object();
},
'boolean': scalarTypeFunction('boolean'),
'integer': scalarTypeFunction('number'),
'number': scalarTypeFunction('number'),
'null': scalarTypeFunction('void'),
'string': scalarTypeFunction('string')
};
var isModelRef = function(ref) {
return ref.startsWith('#/definitions/')
};
var extractModelNameFromRef = function(ref) {
return ref.substring(14);
};
// returns the string type for the given schema;
var jsonSchemaToFlowObject = function(schema, possibleImports) {
var typeFn, result;
// return ref if it's used and ok
if ('$ref' in schema && isModelRef(schema.$ref)) {
var modelName = extractModelNameFromRef(schema.$ref);
if (_(possibleImports).contains(modelName)) {
result = modelName;
} else {
throw new Error('invalid schema:' + JSON.stringify(schema), 'no such type available: ' + schema.$ref);
}
}
// otherwise serialize type. Default to object if schema.type is not specified.
else if ((typeFn = jsonSchemaTypeMap[schema.type || 'object'])) {
result = typeFn(schema, possibleImports);
}
else {
throw new Error('invalid schema:' + JSON.stringify(schema));
}
return result;
};
var outputAPI = function(modelSets) {
var possibleImports = _(modelSets)
.chain()
.map(function(modelSet) {
return _(modelSet).map(function(value, key) { return key; });
})
.flatten()
.value();
var counter = 0;
var models = _(modelSets)
.chain()
.map(function(modelSet) {
return _(modelSet)
.chain()
.values()
.map(function(model) {
//console.info( 'model: ', model );
// now we're dealing with the actual model
var typeObject = _(model.properties)
.chain()
.map(function(schema, key) {
return [key, jsonSchemaToFlowObject(schema, possibleImports)];
})
.object()
.value();
if (model.id == 'BettyArticle') {
console.log('now dealing with BettyArticle');
console.info( 'typeObject %d %s: ', ++counter, model.id, typeObject );
}
var classDefinition = JSON.stringify(typeObject)
.replace(/\{/, '{\n ')
.replace(/,/g, ';\n ')
.replace(/:/g, ': ')
.replace(/"/g, '')
.replace(/}$/g, ';\n}');
var imports = _(_.deepToFlat(model))
.chain()
.filter(function(value, key) {
return /\$ref$/.test(key) &&
isModelRef(value) &&
_(possibleImports).contains(extractModelNameFromRef(value));
})
.map(function(name) {
var modelName = isModelRef(name) ? extractModelNameFromRef(name) : name;
return 'var ' + modelName + " = require('./" + modelName + "');\n";
})
.unique()
.value()
.join('');
return imports + '\nclass ' + model.id + ' ' + classDefinition;
})
.value();
})
.flatten()
.each(function(typeBody) {
var typeName = typeBody.match(/class ([^ ]*) {/)[1];
var outPath = path.join(options.output, typeName + '.js');
var outputBody = '/* @flow */\n' + typeBody + '\nmodule.exports = ' + typeName + ';\n';
fs.writeFileSync(outPath, outputBody);
console.log('wrote to ' + outPath);
})
.value();
};
/* define the command-line options */
var cli = cliArgs([
{ name: 'swaggerUrl', type: String, defaultOption: true, description: 'url of your swagger api docs' },
{ name: 'output', type: String, alias: 'o', description: 'directory to place output files' },
{ name: 'help', type: Boolean, description: 'Print usage instructions' },
]);
var options = cli.parse();
if (options.help) {
var usage = cli.getUsage({
header: 'Flow type class definitions from Swagger API JSON.',
footer: 'For more information, visit https://github.com/jackphel/swaggerflowtypes'
});
console.log(usage);
} else {
get(options.swaggerUrl, function (data) {
getAPIModels(data).then(outputAPI).catch(function(err) {
console.error(err);
});
});
}