Skip to content

Commit 1fdf9d3

Browse files
committed
flow
1 parent de8a9d6 commit 1fdf9d3

File tree

10 files changed

+90
-88
lines changed

10 files changed

+90
-88
lines changed

.flowconfig

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
[ignore]
2-
2+
node_modules
3+
test
4+
lib
35
[include]
46

57
[libs]

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
# Swagger2graphQL
22

3-
Swagger2graphQL wraps your existing Swagger schema to GraphQL types where resolvers perform HTTP requests to certain real endpoints.
3+
Swagger2graphQL converts your existing Swagger schema to GraphQL types where resolvers perform HTTP calls to certain real endpoints.
44
It allows you to move your API to GraphQL with nearly zero afford and maintain both: REST and GraphQL APIs.
55

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

78
## Usage
89

lib/index.js

Lines changed: 35 additions & 35 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,7 +16,7 @@ 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

2121
// @flow
2222
require('babel-polyfill');
@@ -62,30 +62,30 @@ var schemaFromEndpoints = function schemaFromEndpoints(endpoints) {
6262
};
6363

6464
var resolver = function resolver(endpoint) {
65-
return function () {
65+
return (function () {
6666
var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee(_, args, opts) {
6767
var req, res;
6868
return regeneratorRuntime.wrap(function _callee$(_context) {
6969
while (1) {
7070
switch (_context.prev = _context.next) {
71-
case 0:
72-
req = endpoint.request(args, {
73-
baseUrl: opts.GQLProxyBaseUrl
74-
});
71+
case 0:
72+
req = endpoint.request(args, {
73+
baseUrl: opts.GQLProxyBaseUrl
74+
});
7575

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

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

86-
case 6:
87-
case 'end':
88-
return _context.stop();
86+
case 6:
87+
case 'end':
88+
return _context.stop();
8989
}
9090
}
9191
}, _callee, undefined);
@@ -94,7 +94,7 @@ var resolver = function resolver(endpoint) {
9494
return function (_x, _x2, _x3) {
9595
return _ref.apply(this, arguments);
9696
};
97-
}();
97+
}());
9898
};
9999

100100
var getQueriesFields = function getQueriesFields(endpoints, isMutation) {
@@ -113,25 +113,25 @@ var getQueriesFields = function getQueriesFields(endpoints, isMutation) {
113113
}, {});
114114
};
115115

116-
var build = function () {
116+
var build = (function () {
117117
var _ref2 = _asyncToGenerator(regeneratorRuntime.mark(function _callee2(swaggerPath) {
118118
var swaggerSchema, endpoints, schema;
119119
return regeneratorRuntime.wrap(function _callee2$(_context2) {
120120
while (1) {
121121
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();
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();
135135
}
136136
}
137137
}, _callee2, undefined);
@@ -140,7 +140,7 @@ var build = function () {
140140
return function build(_x4) {
141141
return _ref2.apply(this, arguments);
142142
};
143-
}();
143+
}());
144144

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

lib/swagger.js

Lines changed: 1 addition & 1 deletion
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;

lib/typeMap.js

Lines changed: 5 additions & 7 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;
@@ -17,7 +17,7 @@ var _swagger = require('./swagger');
1717

1818
var _swagger2 = _interopRequireDefault(_swagger);
1919

20-
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; } }
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; }
2121

2222
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2323

@@ -32,7 +32,7 @@ var primitiveTypes = {
3232
};
3333

3434
var isObjectType = function isObjectType(jsonSchema) {
35-
return jsonSchema.properties || jsonSchema.type === 'object' || jsonSchema.type === "array" || jsonSchema.schema;
35+
return jsonSchema.properties || jsonSchema.type === 'object' || jsonSchema.type === 'array' || jsonSchema.schema;
3636
};
3737

3838
var getTypeNameFromRef = function getTypeNameFromRef(ref) {
@@ -74,9 +74,8 @@ var createGQLObject = exports.createGQLObject = function createGQLObject(jsonSch
7474
if (jsonSchema.type === 'array') {
7575
if (isObjectType(jsonSchema.items)) {
7676
return new graphql.GraphQLList(createGQLObject(jsonSchema.items, title + '_items', isInputType));
77-
} else {
78-
return new graphql.GraphQLList(getPrimitiveTypes(jsonSchema.items));
7977
}
78+
return new graphql.GraphQLList(getPrimitiveTypes(jsonSchema.items));
8079
}
8180

8281
title = title || jsonSchema.title;
@@ -112,9 +111,8 @@ var jsonSchemaTypeToGraphQL = function jsonSchemaTypeToGraphQL(title, jsonSchema
112111
return createGQLObject(jsonSchema, title + '_' + schemaName, isInputType);
113112
} else if (jsonSchema.type) {
114113
return getPrimitiveTypes(jsonSchema);
115-
} else {
116-
throw new Error("Don't know how to handle schema " + JSON.stringify(jsonSchema) + " without type and schema");
117114
}
115+
throw new Error("Don't know how to handle schema " + JSON.stringify(jsonSchema) + ' without type and schema');
118116
};
119117

120118
var getPrimitiveTypes = function getPrimitiveTypes(jsonSchema) {

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
"babel-plugin-add-module-exports": "^0.2.1",
2323
"babel-preset-es2015": "^6.24.1",
2424
"babel-preset-stage-0": "^6.24.1",
25-
"eslint": "^3.9.1",
25+
"eslint": "^3.19.0",
2626
"eslint-config-airbnb-es5": "^1.1.0",
2727
"eslint-plugin-react": "^6.5.0",
2828
"express": "^4.15.3",

src/index.js

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
// @flow
22
require('babel-polyfill');
3+
import type {GraphQLParameters, Endpoint, GraphQLType} from './types';
34
import rp from 'request-promise';
4-
import { GraphQLSchema, GraphQLObjectType, printSchema } from 'graphql';
5+
import { GraphQLSchema, GraphQLObjectType } from 'graphql';
56
import { getAllEndPoints, loadSchema } from './swagger';
67
import { createGQLObject, mapParametersToFields } from './typeMap';
78

8-
const schemaFromEndpoints = (endpoints) => {
9+
type Endpoints ={[string]: Endpoint};
10+
11+
const schemaFromEndpoints = (endpoints: Endpoints) => {
912
const rootType = new GraphQLObjectType({
1013
name: 'Query',
1114
fields: () => ({
@@ -40,35 +43,34 @@ const schemaFromEndpoints = (endpoints) => {
4043
return new GraphQLSchema(graphQLSchema);
4144
};
4245

43-
const resolver = (endpoint) =>
44-
async (_, args, opts) => {
45-
const req = endpoint.request(args, {
46-
baseUrl: opts.GQLProxyBaseUrl
47-
});
46+
const resolver = (endpoint: Endpoint) =>
47+
async (_, args: GraphQLParameters, opts) => {
48+
const req = endpoint.request(args, opts.GQLProxyBaseUrl);
4849
if (opts.BearerToken) {
4950
req.headers.Authorization = opts.BearerToken;
5051
}
5152
const res = await rp(req);
5253
return JSON.parse(res);
5354
};
5455

55-
const getQueriesFields = (endpoints, isMutation) => {
56-
return Object.keys(endpoints).filter((typeName) => {
56+
const getQueriesFields = (endpoints: Endpoints, isMutation: boolean): {[string]: GraphQLType} => {
57+
return Object.keys(endpoints).filter((typeName: string) => {
5758
return !!endpoints[typeName].mutation === !!isMutation;
5859
}).reduce((result, typeName) => {
5960
const endpoint = endpoints[typeName];
6061
const type = createGQLObject(endpoint.response, typeName, endpoint.location);
61-
result[typeName] = {
62+
const gType: GraphQLType = {
6263
type,
6364
description: endpoint.description,
64-
args: mapParametersToFields(endpoint.parameters, endpoint.location, typeName),
65+
args: mapParametersToFields(endpoint.parameters, typeName),
6566
resolve: resolver(endpoint)
6667
};
68+
result[typeName] = gType;
6769
return result;
6870
}, {});
6971
};
7072

71-
const build = async (swaggerPath) => {
73+
const build = async (swaggerPath: string) => {
7274
const swaggerSchema = await loadSchema(swaggerPath);
7375
const endpoints = getAllEndPoints(swaggerSchema);
7476
const schema = schemaFromEndpoints(endpoints);

src/swagger.js

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// @flow
2-
2+
import type {SwaggerSchema, Endpoint, Responses} from './types';
33
import refParser from 'json-schema-ref-parser';
4+
import type {GraphQLParameters} from './types';
45
import getRequestOptions from 'node-request-by-swagger';
56
let __schema;
67

@@ -11,12 +12,12 @@ export const getSchema = () => {
1112
return __schema;
1213
};
1314

14-
const getGQLTypeNameFromURL = (method, url) => {
15+
const getGQLTypeNameFromURL = (method: string, url: string) => {
1516
const fromUrl = url.replace(/[\{\}]+/g, '').replace(/[^a-zA-Z0-9_]+/g, '_');
1617
return `${method}${fromUrl}`;
1718
};
1819

19-
const getSuccessResponse = (responses) => {
20+
const getSuccessResponse = (responses: Responses) => {
2021
let resp;
2122

2223
if (!responses) return null;
@@ -29,7 +30,7 @@ const getSuccessResponse = (responses) => {
2930
return resp && resp.schema;
3031
};
3132

32-
export const loadSchema = (pathToSchema) => {
33+
export const loadSchema = (pathToSchema: string) => {
3334
const schema = refParser.dereference(pathToSchema);
3435
__schema = schema;
3536
return schema;
@@ -39,9 +40,8 @@ const replaceOddChars = (str) => str.replace(/[^_a-zA-Z0-9]/g, '_');
3940

4041
/**
4142
* Going throw schema and grab routes
42-
* @returns Promise<T>
4343
*/
44-
export const getAllEndPoints = (schema) => {
44+
export const getAllEndPoints = (schema: SwaggerSchema): {[string]: Endpoint} => {
4545
const allTypes = {};
4646
Object.keys(schema.paths).forEach(path => {
4747
const route = schema.paths[path];
@@ -53,20 +53,21 @@ export const getAllEndPoints = (schema) => {
5353
const type = param.type;
5454
return {name: replaceOddChars(param.name), type, jsonSchema: param};
5555
}) : [];
56-
allTypes[typeName] = {
56+
const endpoint: Endpoint = {
5757
parameters,
5858
description: obj.description,
5959
response: getSuccessResponse(obj.responses),
60-
request: (args, server) => {
61-
const url = `${server.baseUrl}${path}`;
60+
request: (args: GraphQLParameters, baseUrl: string) => {
61+
const url = `${baseUrl}${path}`;
6262
return getRequestOptions(obj, {
6363
request: args,
6464
url,
6565
method: method
66-
}, '')
66+
}, '');
6767
},
6868
mutation: isMutation
69-
}
69+
};
70+
allTypes[typeName] = endpoint;
7071
});
7172
});
7273
return allTypes;

0 commit comments

Comments
 (0)