Skip to content

Commit 68e39e9

Browse files
KrivtsovKrivtsov
authored andcommitted
finished flow covering
1 parent c56fba2 commit 68e39e9

File tree

10 files changed

+131
-83
lines changed

10 files changed

+131
-83
lines changed

.babelrc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
{
22
"presets": ["es2015", "stage-0"],
3-
"plugins": ["add-module-exports"]
3+
"plugins": ["add-module-exports", "syntax-flow", "transform-flow-strip-types"]
44
}

README.md

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@ It allows you to move your API to GraphQL with nearly zero afford and maintain b
55

66
<a href="https://medium.com/@raxwunter/moving-existing-api-from-rest-to-graphql-205bab22c184">Why?</a>
77

8-
## Usage
8+
# Usage
9+
10+
## Basic server
911

1012
```js
1113
const express = require('express');
@@ -32,3 +34,22 @@ graphQLSchema('./petstore.json').then(schema => {
3234
throw e;
3335
});
3436
```
37+
38+
## CLI convertion
39+
40+
```
41+
npm i -g swagger-to-graphql
42+
swagger-to-graphql --swagger=/path/to/swagger_schema.json > ./types.graphql
43+
```
44+
## Authorization
45+
46+
```
47+
...
48+
context: {
49+
GQLProxyBaseUrl: API_BASE_URL,
50+
BearerToken: req.get('authorization')
51+
},
52+
...
53+
```
54+
55+
<a href="https://github.com/yarax/swagger-to-graphql/blob/master/src/types.js#L3"> All context options </a>

lib/index.js

Lines changed: 37 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
'use strict';
22

3-
Object.defineProperty(exports, '__esModule', {
3+
Object.defineProperty(exports, "__esModule", {
44
value: true
55
});
66

@@ -16,9 +16,8 @@ var _typeMap = require('./typeMap');
1616

1717
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
1818

19-
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step('next', value); }, function (err) { step('throw', err); }); } } return step('next'); }); }; }
19+
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
2020

21-
// @flow
2221
require('babel-polyfill');
2322

2423

@@ -62,30 +61,28 @@ var schemaFromEndpoints = function schemaFromEndpoints(endpoints) {
6261
};
6362

6463
var resolver = function resolver(endpoint) {
65-
return (function () {
64+
return function () {
6665
var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee(_, args, opts) {
6766
var req, res;
6867
return regeneratorRuntime.wrap(function _callee$(_context) {
6968
while (1) {
7069
switch (_context.prev = _context.next) {
71-
case 0:
72-
req = endpoint.request(args, {
73-
baseUrl: opts.GQLProxyBaseUrl
74-
});
70+
case 0:
71+
req = endpoint.request(args, opts.GQLProxyBaseUrl);
7572

76-
if (opts.BearerToken) {
77-
req.headers.Authorization = opts.BearerToken;
78-
}
79-
_context.next = 4;
80-
return (0, _requestPromise2.default)(req);
73+
if (opts.BearerToken) {
74+
req.headers.Authorization = opts.BearerToken;
75+
}
76+
_context.next = 4;
77+
return (0, _requestPromise2.default)(req);
8178

82-
case 4:
83-
res = _context.sent;
84-
return _context.abrupt('return', JSON.parse(res));
79+
case 4:
80+
res = _context.sent;
81+
return _context.abrupt('return', JSON.parse(res));
8582

86-
case 6:
87-
case 'end':
88-
return _context.stop();
83+
case 6:
84+
case 'end':
85+
return _context.stop();
8986
}
9087
}
9188
}, _callee, undefined);
@@ -94,44 +91,45 @@ var resolver = function resolver(endpoint) {
9491
return function (_x, _x2, _x3) {
9592
return _ref.apply(this, arguments);
9693
};
97-
}());
94+
}();
9895
};
9996

10097
var getQueriesFields = function getQueriesFields(endpoints, isMutation) {
10198
return Object.keys(endpoints).filter(function (typeName) {
10299
return !!endpoints[typeName].mutation === !!isMutation;
103100
}).reduce(function (result, typeName) {
104101
var endpoint = endpoints[typeName];
105-
var type = (0, _typeMap.createGQLObject)(endpoint.response, typeName, endpoint.location);
106-
result[typeName] = {
102+
var type = (0, _typeMap.createGQLObject)(endpoint.response, typeName, false);
103+
var gType = {
107104
type: type,
108105
description: endpoint.description,
109-
args: (0, _typeMap.mapParametersToFields)(endpoint.parameters, endpoint.location, typeName),
106+
args: (0, _typeMap.mapParametersToFields)(endpoint.parameters, typeName),
110107
resolve: resolver(endpoint)
111108
};
109+
result[typeName] = gType;
112110
return result;
113111
}, {});
114112
};
115113

116-
var build = (function () {
114+
var build = function () {
117115
var _ref2 = _asyncToGenerator(regeneratorRuntime.mark(function _callee2(swaggerPath) {
118116
var swaggerSchema, endpoints, schema;
119117
return regeneratorRuntime.wrap(function _callee2$(_context2) {
120118
while (1) {
121119
switch (_context2.prev = _context2.next) {
122-
case 0:
123-
_context2.next = 2;
124-
return (0, _swagger.loadSchema)(swaggerPath);
125-
126-
case 2:
127-
swaggerSchema = _context2.sent;
128-
endpoints = (0, _swagger.getAllEndPoints)(swaggerSchema);
129-
schema = schemaFromEndpoints(endpoints);
130-
return _context2.abrupt('return', schema);
131-
132-
case 6:
133-
case 'end':
134-
return _context2.stop();
120+
case 0:
121+
_context2.next = 2;
122+
return (0, _swagger.loadSchema)(swaggerPath);
123+
124+
case 2:
125+
swaggerSchema = _context2.sent;
126+
endpoints = (0, _swagger.getAllEndPoints)(swaggerSchema);
127+
schema = schemaFromEndpoints(endpoints);
128+
return _context2.abrupt('return', schema);
129+
130+
case 6:
131+
case 'end':
132+
return _context2.stop();
135133
}
136134
}
137135
}, _callee2, undefined);
@@ -140,7 +138,7 @@ var build = (function () {
140138
return function build(_x4) {
141139
return _ref2.apply(this, arguments);
142140
};
143-
}());
141+
}();
144142

145143
exports.default = build;
146-
module.exports = exports.default;
144+
module.exports = exports['default'];

lib/swagger.js

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
'use strict';
22

3-
Object.defineProperty(exports, '__esModule', {
3+
Object.defineProperty(exports, "__esModule", {
44
value: true
55
});
66
exports.getAllEndPoints = exports.loadSchema = exports.getSchema = undefined;
@@ -15,10 +15,7 @@ var _nodeRequestBySwagger2 = _interopRequireDefault(_nodeRequestBySwagger);
1515

1616
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
1717

18-
// @flow
19-
2018
var __schema = void 0;
21-
2219
var getSchema = exports.getSchema = function getSchema() {
2320
if (!__schema || !Object.keys(__schema).length) {
2421
throw new Error('Schema was not loaded');
@@ -56,7 +53,6 @@ var replaceOddChars = function replaceOddChars(str) {
5653

5754
/**
5855
* Going throw schema and grab routes
59-
* @returns Promise<T>
6056
*/
6157
var getAllEndPoints = exports.getAllEndPoints = function getAllEndPoints(schema) {
6258
var allTypes = {};
@@ -70,12 +66,12 @@ var getAllEndPoints = exports.getAllEndPoints = function getAllEndPoints(schema)
7066
var type = param.type;
7167
return { name: replaceOddChars(param.name), type: type, jsonSchema: param };
7268
}) : [];
73-
allTypes[typeName] = {
69+
var endpoint = {
7470
parameters: parameters,
7571
description: obj.description,
7672
response: getSuccessResponse(obj.responses),
77-
request: function request(args, server) {
78-
var url = '' + server.baseUrl + path;
73+
request: function request(args, baseUrl) {
74+
var url = '' + baseUrl + path;
7975
return (0, _nodeRequestBySwagger2.default)(obj, {
8076
request: args,
8177
url: url,
@@ -84,6 +80,7 @@ var getAllEndPoints = exports.getAllEndPoints = function getAllEndPoints(schema)
8480
},
8581
mutation: isMutation
8682
};
83+
allTypes[typeName] = endpoint;
8784
});
8885
});
8986
return allTypes;

lib/typeMap.js

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
'use strict';
22

3-
Object.defineProperty(exports, '__esModule', {
3+
Object.defineProperty(exports, "__esModule", {
44
value: true
55
});
66
exports.mapParametersToFields = exports.getTypeFields = exports.createGQLObject = undefined;
@@ -15,13 +15,11 @@ var graphql = _interopRequireWildcard(_graphql);
1515

1616
var _swagger = require('./swagger');
1717

18-
var _swagger2 = _interopRequireDefault(_swagger);
19-
20-
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; }
18+
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
2119

2220
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2321

24-
var __allTypes = {}; // @flow
22+
var __allTypes = {};
2523

2624
var primitiveTypes = {
2725
string: graphql.GraphQLString,
@@ -42,13 +40,13 @@ var getTypeNameFromRef = function getTypeNameFromRef(ref) {
4240

4341
var getExistingType = function getExistingType(ref, isInputType) {
4442
var typeName = getTypeNameFromRef(ref);
45-
var allSchema = _swagger2.default.getSchema();
43+
var allSchema = (0, _swagger.getSchema)();
4644
if (!__allTypes[typeName]) {
4745
var schema = allSchema.definitions[typeName];
4846
if (!schema) {
4947
throw new Error('Definition ' + typeName + ' was not found in schema');
5048
}
51-
__allTypes[typeName] = createGQLObject(schema, typeName, ref, isInputType);
49+
__allTypes[typeName] = createGQLObject(schema, typeName, isInputType);
5250
}
5351
return __allTypes[typeName];
5452
};
@@ -59,9 +57,11 @@ var getRefProp = function getRefProp(jsonSchema) {
5957

6058
var createGQLObject = exports.createGQLObject = function createGQLObject(jsonSchema, title, isInputType) {
6159
if (!jsonSchema) {
62-
jsonSchema = {
60+
jsonSchema = { // eslint-disable-line no-param-reassign
6361
type: 'object',
64-
properties: {}
62+
properties: {},
63+
description: '',
64+
title: ''
6565
};
6666
}
6767

@@ -78,14 +78,20 @@ var createGQLObject = exports.createGQLObject = function createGQLObject(jsonSch
7878
return new graphql.GraphQLList(getPrimitiveTypes(jsonSchema.items));
7979
}
8080

81-
title = title || jsonSchema.title;
82-
83-
var objectType = isInputType ? 'GraphQLInputObjectType' : 'GraphQLObjectType';
84-
85-
return new graphql[objectType]({
81+
title = title || jsonSchema.title; // eslint-disable-line no-param-reassign
82+
var description = jsonSchema.description;
83+
var fields = getTypeFields(jsonSchema, title, isInputType);
84+
if (isInputType) {
85+
return new graphql.GraphQLInputObjectType({
86+
name: title,
87+
description: description,
88+
fields: fields
89+
});
90+
}
91+
return new graphql.GraphQLObjectType({
8692
name: title,
87-
description: jsonSchema.description,
88-
fields: getTypeFields(jsonSchema, title, isInputType)
93+
description: description,
94+
fields: fields
8995
});
9096
};
9197

@@ -128,7 +134,7 @@ var getPrimitiveTypes = function getPrimitiveTypes(jsonSchema) {
128134
return type;
129135
};
130136

131-
var mapParametersToFields = exports.mapParametersToFields = function mapParametersToFields(parameters, endpointLocation, typeName) {
137+
var mapParametersToFields = exports.mapParametersToFields = function mapParametersToFields(parameters, typeName) {
132138
return parameters.reduce(function (res, param) {
133139
var type = jsonSchemaTypeToGraphQL('param_' + typeName, param.jsonSchema, param.name, true);
134140
res[param.name] = {

lib/types.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
'use strict';

package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020
"babel-core": "^6.24.1",
2121
"babel-eslint": "^7.2.3",
2222
"babel-plugin-add-module-exports": "^0.2.1",
23+
"babel-plugin-syntax-flow": "^6.18.0",
24+
"babel-plugin-transform-flow-strip-types": "^6.22.0",
2325
"babel-preset-es2015": "^6.24.1",
2426
"babel-preset-stage-0": "^6.24.1",
2527
"eslint": "^3.19.0",

src/index.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// @flow
22
require('babel-polyfill');
3-
import type {GraphQLParameters, Endpoint, GraphQLType} from './types';
3+
import type {GraphQLParameters, Endpoint, GraphQLType, RootGraphQLSchema, SwaggerToGraphQLOptions} from './types';
44
import rp from 'request-promise';
55
import { GraphQLSchema, GraphQLObjectType } from 'graphql';
66
import { getAllEndPoints, loadSchema } from './swagger';
@@ -28,7 +28,7 @@ const schemaFromEndpoints = (endpoints: Endpoints) => {
2828
})
2929
});
3030

31-
const graphQLSchema = {
31+
const graphQLSchema: RootGraphQLSchema = {
3232
query: rootType
3333
};
3434

@@ -44,7 +44,7 @@ const schemaFromEndpoints = (endpoints: Endpoints) => {
4444
};
4545

4646
const resolver = (endpoint: Endpoint) =>
47-
async (_, args: GraphQLParameters, opts) => {
47+
async (_, args: GraphQLParameters, opts: SwaggerToGraphQLOptions) => {
4848
const req = endpoint.request(args, opts.GQLProxyBaseUrl);
4949
if (opts.BearerToken) {
5050
req.headers.Authorization = opts.BearerToken;
@@ -58,7 +58,7 @@ const getQueriesFields = (endpoints: Endpoints, isMutation: boolean): {[string]:
5858
return !!endpoints[typeName].mutation === !!isMutation;
5959
}).reduce((result, typeName) => {
6060
const endpoint = endpoints[typeName];
61-
const type = createGQLObject(endpoint.response, typeName, endpoint.location);
61+
const type = createGQLObject(endpoint.response, typeName, false);
6262
const gType: GraphQLType = {
6363
type,
6464
description: endpoint.description,

0 commit comments

Comments
 (0)