Git Product home page Git Product logo

swagger-to-graphql's Introduction

Build Status

Swagger-to-GraphQL

Swagger-to-GraphQL converts your existing Swagger schema to an executable GraphQL schema where resolvers perform HTTP calls to certain real endpoints. It allows you to move your API to GraphQL with nearly zero effort and maintain both REST and GraphQL APIs. Our CLI tool also allows you get the GraphQL schema in Schema Definition Language.

Try it online! You can paste in the url to your own Swagger schema. There are also public OpenAPI schemas available in the APIs.guru OpenAPI directory.

Features

  • Swagger (OpenAPI 2) and OpenAPI 3 support
  • Bring you own HTTP client
  • Typescript types included
  • Runs in the browser
  • Formdata request body
  • Custom request headers

Usage

Basic server

This library will fetch your swagger schema, convert it to a GraphQL schema and convert GraphQL parameters to REST parameters. From there you are control of making the actual REST call. This means you can reuse your existing HTTP client, use existing authentication schemes and override any part of the REST call. You can override the REST host, proxy incoming request headers along to your REST backend, add caching etc.

import express, { Request } from 'express';
import graphqlHTTP from 'express-graphql';
import { createSchema, CallBackendArguments } from 'swagger-to-graphql';

const app = express();

// Define your own http client here
async function callBackend({
  context,
  requestOptions,
}: CallBackendArguments<Request>) {
  return 'Not implemented';
}

createSchema({
  swaggerSchema: `./petstore.yaml`,
  callBackend,
})
  .then(schema => {
    app.use(
      '/graphql',
      graphqlHTTP(() => {
        return {
          schema,
          graphiql: true,
        };
      }),
    );

    app.listen(3009, 'localhost', () => {
      console.info('http://localhost:3009/graphql');
    });
  })
  .catch(e => {
    console.log(e);
  });

Constructor (graphQLSchema) arguments:

export interface Options<TContext> {
  swaggerSchema: string | JSONSchema;
  callBackend: (args: CallBackendArguments<TContext>) => Promise<any>;
}
  • swaggerUrl (string) is a path or URL to your swagger schema file. required
  • callBackend (async function) is called with all parameters needed to make a REST call as well as the GraphQL context.

CLI usage

You can use the library just to convert schemas without actually running server

npx swagger-to-graphql --swagger-schema=/path/to/swagger_schema.json > ./types.graphql

Apollo federation support can be added by using graphql-transform-federation. You can extend your swagger-to-graphql schema with other federated schemas or the other way around. See the demo with a transformed schema for a working example.

Defining your HTTP client

This repository has:

To get started install node-fetch and copy the node-fetch example into your server.

npm install node-fetch --save

Implementing your own HTTP client

There a unit test for our HTTP client example, it might be useful when implementing your own client as well.

The function callBackend is called with 2 parameters:

  • context is your GraphQL context. For express-graphql this is the incoming request object by default. Read more. Use this if you want to proxy headers like authorization. For example const authorizationHeader = context.get('authorization').
  • requestOptions includes everything you need to make a REST call.
export interface CallBackendArguments<TContext> {
  context: TContext;
  requestOptions: RequestOptions;
}

RequestOptions

export interface RequestOptions {
  baseUrl?: string;
  path: string;
  method: string;
  headers?: {
    [key: string]: string;
  };
  query?: {
    [key: string]: string | string[];
  };
  body?: any;
  bodyType: 'json' | 'formData';
}
  • baseUrl like defined in your swagger schema: http://my-backend/v2
  • path the next part of the url: /widgets
  • method HTTP verb: get
  • headers HTTP headers which are filled using GraphQL parameters: { api_key: 'xxxx-xxxx' }. Note these are not the http headers sent to the GraphQL server itself. Those will be on the context parameter
  • query Query parameters for this calls: { id: 123 }. Note this can be an array. You can find some examples on how to deal with arrays in query parameters in the qs documentation.
  • body the request payload to send with this REST call.
  • bodyType how to encode your request payload. When the bodyType is formData the request should be URL encoded form data. Ensure your HTTP client sends the right Content-Type headers.

Resources

swagger-to-graphql's People

Contributors

0xr avatar artomal avatar cheggil avatar kamilchm avatar kbrandwijk avatar kirill-konshin avatar marla-singer avatar ofersadgat avatar puneetar avatar raxpost avatar sartaj avatar saumitrab avatar sibelius avatar stvvt avatar swcho avatar thejibz avatar tiberiuzuld avatar timsusa avatar wtgtybhertgeghgtwtg avatar zacanger avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swagger-to-graphql's Issues

Parameters mapping

Make possible to map swagger parameters names to some custom ones to work around graphql names limitations

Getting a RangeError: Maximum call stack size exceeded

When I try to start a server with a rather big swagger file, the application throws this error
RangeError: Maximum call stack size exceeded
at isPrototype (/Users/macuser/Documents/Apps/server/swagger2grahpql/node_modules/lodash/lodash.js:6415:25)
at baseKeys (/Users/macuser/Documents/Apps/server/swagger2grahpql/node_modules/lodash/lodash.js:3494:12)
at keys (/Users/macuser/Documents/Apps/server/swagger2grahpql/node_modules/lodash/lodash.js:13285:60)
at /Users/macuser/Documents/Apps/server/swagger2grahpql/node_modules/lodash/lodash.js:4939:21
at baseForOwn (/Users/macuser/Documents/Apps/server/swagger2grahpql/node_modules/lodash/lodash.js:3001:24)
at Function.mapValues (/Users/macuser/Documents/Apps/server/swagger2grahpql/node_modules/lodash/lodash.js:13378:7)
at getTypeFields (/Users/macuser/Documents/Apps/server/swagger2grahpql/node_modules/swagger-to-graphql/lib/typeMap.js:107:33)
at createGQLObject (/Users/macuser/Documents/Apps/server/swagger2grahpql/node_modules/swagger-to-graphql/lib/typeMap.js:91:16)
at jsonSchemaTypeToGraphQL (/Users/macuser/Documents/Apps/server/swagger2grahpql/node_modules/swagger-to-graphql/lib/typeMap.js:125:12)
at /Users/macuser/Documents/Apps/server/swagger2grahpql/node_modules/swagger-to-graphql/lib/typeMap.js:110:13
at /Users/macuser/Documents/Apps/server/swagger2grahpql/node_modules/lodash/lodash.js:13379:38
at /Users/macuser/Documents/Apps/server/swagger2grahpql/node_modules/lodash/lodash.js:4944:15
at baseForOwn (/Users/macuser/Documents/Apps/server/swagger2grahpql/node_modules/lodash/lodash.js:3001:24)
at Function.mapValues (/Users/macuser/Documents/Apps/server/swagger2grahpql/node_modules/lodash/lodash.js:13378:7)
at getTypeFields (/Users/macuser/Documents/Apps/server/swagger2grahpql/node_modules/swagger-to-graphql/lib/typeMap.js:107:33)
at createGQLObject (/Users/macuser/Documents/Apps/server/swagger2grahpql/node_modules/swagger-to-graphql/lib/typeMap.js:91:16)
at jsonSchemaTypeToGraphQL (/Users/macuser/Documents/Apps/server/swagger2grahpql/node_modules/swagger-to-graphql/lib/typeMap.js:125:12)
at /Users/macuser/Documents/Apps/server/swagger2grahpql/node_modules/swagger-to-graphql/lib/typeMap.js:110:13
at /Users/macuser/Documents/Apps/server/swagger2grahpql/node_modules/lodash/lodash.js:13379:38
at /Users/macuser/Documents/Apps/server/swagger2grahpql/node_modules/lodash/lodash.js:4944:15
at baseForOwn (/Users/macuser/Documents/Apps/server/swagger2grahpql/node_modules/lodash/lodash.js:3001:24)
at Function.mapValues (/Users/macuser/Documents/Apps/server/swagger2grahpql/node_modules/lodash/lodash.js:13378:7)

swagger-to-graphql nestjs example

Is swagger-to-graphql compatible with nestjs?

Motivation: I want to cover the legacy REST-API with the definitions from inside the swagger.json using swagger-to-graphql and additionally offer other definitions on top of it, like subscriptions, edges, etc. (extending the schema) using other modules in the application.

graphQLSchema('./swagger2.json')
    .then(schema => {
        app.use('/graphql', graphqlHTTP(() => {
            return {
                schema,
                context: {
                    GQLProxyBaseUrl: API_BASE_URL,
                    headers: {
                        Authorization: 'Basic YWRkOmJhc2ljQXV0aA=='
                    }
                },
                pretty: true,
                graphiql: true
            };
        }));
    })
    .catch(e => {
        throw e;
    });

Any hint is very much apreciated.

Ps.: Nestjs uses the apollo-server-express implementation.

RangeError: Maximum call stack size exceeded

With larger files, swagger-to-graphql seems to reach the max stack size.

(node:29124) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): RangeError: Maximum call stack size exceeded
(node:29124) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

[Feature request] Support `deprecationReason` GraphQL property

GraphQL allows enum types and object types to be marked as deprecated with deprecationReason.

OpenAPI 2.0/3.0 allow operation to be marked as deprecated. OpenAPI 3.0 allow parameters and response properties to be marked as deprecated.

It would be nice if the later one could translate into the first one.

Polymorphism issue

Hi,
On my swagger file i use the property allOf to do Polymorphism (see : https://swagger.io/specification/#models-with-composition-108) in one of my definition.

Here a sample:

Payment:
  title: Payment
  description: Payment transaction
  allOf:
    - $ref: '#/NewPayment'
    - type: object
      required:
        - paymentId
      properties:
        paymentId:
          type: number
          example: 42
          description: The unique identifier of a payment transaction on the system

I believe that the case is not managed i got an error

[Error: Cannot build primitive type "undefined"]

its working fine when i remove it.

BTW, Amazing project/idea !

Support for basic auth

Hello there and thank you for this really helpfull lib!

Is there a way of setting the basic auth through the api?
Is it planed to support basic auth authorization?

  1. Setting the header information through the api does not work:
[...]
graphQLSchema('./swagger.json').then(schema => {
    app.use('/graphql', graphqlHTTP((req) => {
        req.headers['Authorization'] = 'Basic: YWRkOmJhc2ljQXV0aA==';
        req.headers['X-Custom'] = 'custom-payload-xyz';
        return {
            schema,
[...]
  1. Setting the header in the resolver function does work:
    https://github.com/yarax/swagger-to-graphql/blob/master/lib/index.js#L80
[...]
var resolver = function resolver(endpoint) {
  return function () {
    var _ref = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee(_, args, opts) {
      var req, res;
      return _regenerator2.default.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              req = endpoint.request(args, opts.GQLProxyBaseUrl);

              req.headers['Authorization'] = 'Basic: YWRkOmJhc2ljQXV0aA==';
              if (opts.BearerToken) {
                req.headers.Authorization = opts.BearerToken;
              }
              _context.next = 4;
              return (0, _requestPromise2.default)(req);
[...]

path item parameters not supported by the swagger parser

I'm seeing this error when using Path Item Object parameters in a swagger schema (attached below). It seems the parser code assumes there cannot be any parameters under a path, but only methods (http verbs). The swagger spec allows parameters as fixed fields under Path Item:

A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there.

Is this a built-in assumption meant to simplify the parser ?

  1) api schema converting:
     TypeError: Cannot convert undefined or null to object
      at getSuccessResponse (lib/swagger.js:21:10)
      at Object.keys.forEach.method (lib/swagger.js:58:19)
      at Array.forEach (native)
      at Object.keys.forEach.path (lib/swagger.js:47:24)
      at Array.forEach (native)
      at getAllEndPoints (lib/swagger.js:45:29)
      at loadSchema.then.swaggerSchema (lib/index.js:9:23)

api-spec.json

error running on same port

if you start the GraphQl server then try to reopen the server again on the same port it displays an error message it should warn you about the server is already is running and you should be able to stop the server.

events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE 127.0.0.1:3009
    at Object.exports._errnoException (util.js:1026:11)
    at exports._exceptionWithHostPort (util.js:1049:20)
    at Server._listen2 (net.js:1253:14)
    at listen (net.js:1289:10)
    at net.js:1399:9
    at GetAddrInfoReqWrap.asyncCallback [as callback] (dns.js:65:16)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:84:10)

Error: Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/

I'm trying to run against this schema from Musixmatch SDK

but I get

$ node app.js 
Error: Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "get_album.tracks.get_message_header" does not.
    at invariant (/tools/swagger-to-graphql/node_modules/graphql/jsutils/invariant.js:19:11)
    at assertValidName (/tools/swagger-to-graphql/node_modules/graphql/utilities/assertValidName.js:28:27)
    at new GraphQLObjectType (/tools/swagger-to-graphql/node_modules/graphql/type/definition.js:224:42)
    at createGQLObject (/tools/swagger-to-graphql/lib/type_map.js:68:10)
    at jsonSchemaTypeToGraphQL (/tools/swagger-to-graphql/lib/type_map.js:94:12)
    at _.mapValues (/tools/swagger-to-graphql/lib/type_map.js:79:13)
    at /tools/swagger-to-graphql/node_modules/lodash/lodash.js:13303:38
    at /tools/swagger-to-graphql/node_modules/lodash/lodash.js:4917:15
    at baseForOwn (/tools/swagger-to-graphql/node_modules/lodash/lodash.js:2979:24)
    at Function.mapValues (/tools/swagger-to-graphql/node_modules/lodash/lodash.js:13302:7)
    at getTypeFields (/tools/swagger-to-graphql/lib/type_map.js:76:20)
    at createGQLObject (/tools/swagger-to-graphql/lib/type_map.js:71:13)
    at jsonSchemaTypeToGraphQL (/tools/swagger-to-graphql/lib/type_map.js:94:12)
    at _.mapValues (/tools/swagger-to-graphql/lib/type_map.js:79:13)
    at /tools/swagger-to-graphql/node_modules/lodash/lodash.js:13303:38
    at /tools/swagger-to-graphql/node_modules/lodash/lodash.js:4917:15
    at baseForOwn (/tools/swagger-to-graphql/node_modules/lodash/lodash.js:2979:24)
    at Function.mapValues (/tools/swagger-to-graphql/node_modules/lodash/lodash.js:13302:7)
    at getTypeFields (/tools/swagger-to-graphql/lib/type_map.js:76:20)
    at createGQLObject (/tools/swagger-to-graphql/lib/type_map.js:71:13)
    at Object.keys.filter.reduce (/tools/swagger-to-graphql/lib/index.js:59:18)
    at Array.reduce (native)

Thank you.

Error generating graphql

When I use custom headers the tool fails to create the GraphQL schema

Error: Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "X-SitTEST-Proposition" does not.
    at invariant (~/swagger-to-graphql/node_modules/graphql/jsutils/invariant.js:19:11)
    at assertValidName (~/swagger-to-graphql/node_modules/graphql/utilities/assertValidName.js:28:27)
    at ~/swagger-to-graphql/node_modules/graphql/type/definition.js:287:46
    at Array.map (native)
    at ~/swagger-to-graphql/node_modules/graphql/type/definition.js:286:44
    at Array.forEach (native)
    at defineFieldMap (~/swagger-to-graphql/node_modules/graphql/type/definition.js:272:14)
    at GraphQLObjectType.getFields (~/swagger-to-graphql/node_modules/graphql/type/definition.js:235:44)
    at ~/swagger-to-graphql/node_modules/graphql/type/schema.js:207:27
    at typeMapReducer (~/swagger-to-graphql/node_modules/graphql/type/schema.js:219:7)
    at ~/swagger-to-graphql/node_modules/graphql/type/schema.js:217:22
    at Array.forEach (native)
    at ~/swagger-to-graphql/node_modules/graphql/type/schema.js:208:29
    at typeMapReducer (~/swagger-to-graphql/node_modules/graphql/type/schema.js:219:7)
    at Array.reduce (native)
    at new GraphQLSchema (~/swagger-to-graphql/node_modules/graphql/type/schema.js:95:34)
    at loadSchema.then.swaggerSchema (~/swagger-to-graphql/lib/index.js:40:12)
    at run (/usr/local/lib/node_modules/babel-cli/node_modules/core-js/modules/es6.promise.js:87:22)
    at /usr/local/lib/node_modules/babel-cli/node_modules/core-js/modules/es6.promise.js:100:28
    at flush (/usr/local/lib/node_modules/babel-cli/node_modules/core-js/modules/_microtask.js:18:9)
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickDomainCallback (internal/process/next_tick.js:122:9)

Getting error: Don't know how to handle schema ...

I'm doing a little late afternoon R&D to determine the viability of moving some or all of our ~50 endpoints API from REST to GraphQL. I came across swagger2GraphQL and thought it might be a great tool to help. I have converted my swagger.yaml to a swagger.json but when I run

swagger-to-graphql --swagger=./api/swagger/swagger.json I receive

Error: Don't know how to handle schema {"description":"The total amount to be submitted to Stripe including subTotal, rylliFee and stripeFee"} without type and schema

Followed by a stack dump. My swagger.json is 3125 lines and the swagger.yaml version is running our API nicely. Since this is just a quick R&D exercise during some downtime I can't invest too heavily.

Any suggestion where I might start to debug this issue.

FWIW: Swagger version 2 and it does verify with swagger project verify.

Error: Cannot build primitive type "Object"

I used the command line swagger-to-graphql --swagger=./swagger.json > out.graphql
I cannot share the swagger.json as it is internal APIs. I could share a snippet if you could point me to where the issue maybe. The swagger loads fine in the usual viewer. Thanks

Getting this error:

Error: Cannot build primitive type "Object"
    at getPrimitiveTypes (/usr/local/lib/node_modules/swagger-to-graphql/lib/typeMap.js:140:11)
    at jsonSchemaTypeToGraphQL (/usr/local/lib/node_modules/swagger-to-graphql/lib/typeMap.js:127:12)
    at /usr/local/lib/node_modules/swagger-to-graphql/lib/typeMap.js:110:13
    at /usr/local/lib/node_modules/swagger-to-graphql/node_modules/lodash/lodash.js:13392:38
    at /usr/local/lib/node_modules/swagger-to-graphql/node_modules/lodash/lodash.js:4917:15
    at baseForOwn (/usr/local/lib/node_modules/swagger-to-graphql/node_modules/lodash/lodash.js:3002:24)
    at Function.mapValues (/usr/local/lib/node_modules/swagger-to-graphql/node_modules/lodash/lodash.js:13391:7)
    at getTypeFields (/usr/local/lib/node_modules/swagger-to-graphql/lib/typeMap.js:107:33)
    at createGQLObject (/usr/local/lib/node_modules/swagger-to-graphql/lib/typeMap.js:91:16)
    at createGQLObject (/usr/local/lib/node_modules/swagger-to-graphql/lib/typeMap.js:84:38)
    at /usr/local/lib/node_modules/swagger-to-graphql/lib/index.js:117:45
    at Array.reduce (<anonymous>)
    at getQueriesFields (/usr/local/lib/node_modules/swagger-to-graphql/lib/index.js:115:6)
    at fields (/usr/local/lib/node_modules/swagger-to-graphql/lib/index.js:46:33)
    at resolveThunk (/usr/local/lib/node_modules/swagger-to-graphql/node_modules/graphql/type/definition.js:304:40)
    at defineFieldMap (/usr/local/lib/node_modules/swagger-to-graphql/node_modules/graphql/type/definition.js:466:18)
    at GraphQLObjectType.getFields (/usr/local/lib/node_modules/swagger-to-graphql/node_modules/graphql/type/definition.js:440:44)
    at typeMapReducer (/usr/local/lib/node_modules/swagger-to-graphql/node_modules/graphql/type/schema.js:213:25)
    at /usr/local/lib/node_modules/swagger-to-graphql/node_modules/graphql/type/schema.js:223:20
    at Array.forEach (<anonymous>)
    at typeMapReducer (/usr/local/lib/node_modules/swagger-to-graphql/node_modules/graphql/type/schema.js:214:27)
    at Array.reduce (<anonymous>)

graphiql generating weird requests

If I use the following code:

const express = require('express');
const app = express();
var graphqlHTTP = require('express-graphql');
var graphql = require('graphql');
var graphQLSchema = require('swagger-to-graphql');

graphQLSchema('https://rata-beta.digitraffic.fi/swagger/swagger.json').then(schema => {
  app.use('/graphql', graphqlHTTP(() => {
    return {
      schema,
      context: {
        GQLProxyBaseUrl: 'https://rata-beta.digitraffic.fi'
      },
      graphiql: true
    };
  }));

  app.listen(3009, 'localhost', () => {
    console.info(`API is here localhost:3009/graphql`);
  });
}).catch(e => {
  throw e;
});

And then run this query:

{ viewer {  getAllTrainsUsingGET(version:"15223") {
  cancelled
  commuterLineID
  deleted
  departureDate
  operatorShortCode
  operatorUICCode
  runningCurrently
  timetableAcceptanceDate
  timetableType
  trainCategory
  trainNumber
  trainType
  version
} } }

It returns an http error 400 and the requests looks like this: /api/v1/all-trains%7B?version%7D=&amp;version=1523

When it should be like this: api/v1/all-trains?version=1523. The parameters can be found two times in the url along with some url escapes.

I suspect it has something to do with the api having urls like this:

  • /api/v1/live-trains/{train_number}{?departure_date,version}
  • /api/v1/live-trains{?version}

But the all-trains url that I'm testing only has that one optional parameter called version.

Any idea what's wrong?

Error messages

Hi,

I ran the following: swagger-to-graphql --swagger=../../openapi/schema.yaml > ./types.graphql
It ran for >5min, but at the end types.graphql was empty. No error messages (or other messages) were printed.

It might be nice to print error messages.

Thanks!

Http headers

@yarax Would it be possible to ignore HTTP headers when generating the GraphQL schema since they can be added via the network request.

[Feature request] Support `discriminator` and GraphQL interfaces

GraphQL supports polymorphism using GraphQLInterfaceType. OpenAPI supports it with the discriminator property (which has a different syntax in 2.0 and 3.0). It would be nice to bring the two together.

This feature request might represent quite lots of work for something I'm not sure people would use, but I thought I'd still submit to see what you think.

Passing in the endpoint URL

I am trying to integrate this library in a concept for graphql bindings. The issue I am facing is that the endpoint URL context variable name is hardcoded, so I can't use it with multiple bindings. Would it be possible to come up with an alternative way to specify the endpoint URL, preferable by passing it into the constructor, instead of having to specify it on the context?

This is really blocking me from integrating your library.

I would propose an optional parameter on the build() method, that gets passed in to schemaFromEndpoints. Preferably the endpoint itself, or a function if you want to specify it on the context, so:

build('./swagger.json', ctx => ctx.myEndpoint) or build('./swagger,json', 'http://my.endpoint.com')

petstore getInventory returns null through garphiql

Is this a known issue, or is there any hint what am I missing in getting the same results through graphiql vs. direct REST call ?

swagger-to-graphql alexp$ npm start
> [email protected] start /Users/alexp/ws/swagger-to-graphql
> node app.js
http://localhost:3009/graphql

screen shot 2017-04-28 at 18 38 25

A similar attempt directly through the PetStore endpoint:

$ curl -X GET "http://petstore.swagger.io/v2/store/inventory" -H  "accept: application/json"
{"New":1,"Done":1,"placed":3,"unavailable":4,"stud":1,"jxl.read.biff.LabelSSTRecord@75a2fef0":1,"available":3325,"availablxxxxe":1,"delivered":3,"有效的":1,"Unavailable":2,"confused":3,"availabl123e":1,"approved":1,"no more":1,"asdf":4,"Available":1,"aa":2,"yolo":1,"ad":1,"test":3,"Dead":1,"testtt":6,"I am doing good":1,"testing":1,"available15556":1,"sint":1,"adad":1,"jxl.read.biff.LabelSSTRecord@62a289c0":1,"whatever":1,"undesirable":1,"1":4,"reprehenderit Excepteur ut dolor":1,"Active":1,"200":2,"123":1,"notavaillable":2,"4":1,"true":1,"availabltryrtyrtyye":1,"available}":3,"hello":1,"aveeeailable":1,"dog":1,"a1ailable":1," Not available":2,"jxl.read.biff.LabelSSTRecord@3fbdd262":1,"string":2145,"sed ullamco":1,"Adopted":1,"pending":135,"foo":1,"dangerous":1,"asdasd":1,"dead":3,"adulto":3,"565656566":2,"availaaaaable":3,"ave":1,"availablee":1,"world":1,"jxl.read.biff.LabelSSTRecord@7aa59195":1,"busy":2,"mort":2,"not available":1,"cuty":1,"avaijlable":1,"adds":1,"availabl2e":4,"sold":1041,"available,pending":2,"available1":9,"aaaa":1,"dfgdsfg":1,"AVAILABLE":162,"dsds":1,"TG":2,"fds":1,"unavaiable":37,"Single":1,"disable":4,"magna ipsum in id":1,"fatima3":1,"fake":1,"Good":1,"fgghfgh":2,"jxl.read.biff.LabelSSTRecord@5cc91926":2,"available123":2}

Error returning Data

When I try to use the demo pet store example via GraphQL it fails to return any data even thou swagger API it returns the data
http://petstore.swagger.io/#!/store/getOrderById
curl -X GET --header 'Accept: application/json' 'http://petstore.swagger.io/v2/store/order/7'

GraphQl

{
  viewer {
    get_store_order_orderId(orderId: 7) {
      id
      petId
      shipDate
    }
  }
}

return data

{
  "data": {
    "viewer": null
  }
}

"Schema must be an instance of GraphQLSchema"

When running the example with the following package.json:

{
  "name": "swagger-to-graphql-test",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "express": "^4.15.2",
    "express-graphql": "^0.6.3",
    "graphql": "^0.9.1",
    "swagger-to-graphql": "^1.0.4"
  }
}

I get the following in /graphql:

{
  "errors": [
    {
      "message": "Schema must be an instance of GraphQLSchema. Also ensure that there are not multiple versions of GraphQL installed in your node_modules directory."
    }
  ]
}

[Feature request] Support OpenAPI 3.0

Great project!

Is there any plan to support OpenAPI 3.0 in the future?

I've noted the following incompatibilities between OpenAPI 2.0 / Swagger and OpenAPI 3.0:

  • response.schema is not available in OpenAPI 3.0 anymore. Instead response.contents.MIME.schema is used.
  • parameters are quite different in OpenAPI 3.0
  • consumes and produces are not available anymore in OpenAPI 3.0. Instead Content-Type and Accept HTTP headers should be used. Also several properties now specify the MIME type.
  • although the rest follows OpenAPI 2.0, this project already follows OpenAPI 3.0 when it comes to the servers property. However OpenAPI 3.0 also allow path definitions to override the servers property.
  • OpenAPI 3.0 renames the definitions property to schemas

RequestError: Error: Invalid URI "undefined/store/inventory"

Hi there! On my road trying to get swagger-to-graphql working with another graphql-server other then graphql-express, i get the following error when trying to fire up this query:

swagger-to-graphql.yoga.js:

const {GraphQLServer} = require('graphql-yoga');
const swaggerGraphQLSchema = require('swagger-to-graphql');
const API_BASE_URL = 'http://petstore.swagger.io/v2';

swaggerGraphQLSchema('http://petstore.swagger.io/v2/swagger.json')
    .then(schema => {
        const options = {
            port: 4000,
            context: {
                GQLProxyBaseUrl: API_BASE_URL
            }
        };
        const server = new GraphQLServer({
            schema: schema
        });
        server.start(options, () => console.log('Server is running on localhost:' + options.port))
    })
    .catch(e => {
        throw e;
    });

result screenshot:

image

Query

{
  viewer {
    getInventory {
      empty
    }
  }
}

Error

"node.exe" swagger-to-graphql.yoga.js
Server is running on localhost:4000
RequestError: Error: Invalid URI "undefined/store/inventory"
    at new RequestError (node_modules\request-promise-core\lib\errors.js:14:15)
    at Request.plumbing.callback (node_modules\request-promise-core\lib\plumbing.js:87:29)
    at Request.RP$callback [as _callback] (node_modules\request-promise-core\lib\plumbing.js:46:31)
    at self.callback (node_modules\request\request.js:186:22)
    at Request.emit (events.js:159:13)
    at Request.init (node_modules\request\request.js:274:17)
    at Request.RP$initInterceptor [as init] (node_modules\request-promise-core\configure\request2.js:45:29)
    at new Request (node_modules\request\request.js:128:8)
    at request (node_modules\request\index.js:53:10)
    at _callee$ (node_modules\swagger-to-graphql\lib\index.js:89:51)
    at tryCatch (node_modules\babel-runtime\node_modules\regenerator-runtime\runtime.js:62:40)
    at Generator.invoke [as _invoke] (node_modules\babel-runtime\node_modules\regenerator-runtime\runtime.js:296:22)
    at Generator.prototype.(anonymous function) [as next] (node_modules\babel-runtime\node_modules\regenerator-runtime\runtime.js:114:21)
    at step (node_modules\babel-runtime\helpers\asyncToGenerator.js:17:30)
    at node_modules\babel-runtime\helpers\asyncToGenerator.js:35:14
    at new Promise (<anonymous>)
    at new F (node_modules\core-js\library\modules\_export.js:35:28)
    at node_modules\babel-runtime\helpers\asyncToGenerator.js:14:12
    at node_modules\swagger-to-graphql\lib\index.js:104:19
    at field.resolve (node_modules\graphql-extensions\lib\index.js:119:77)
    at resolveFieldValueOrError (node_modules\graphql\execution\execute.js:544:18)
    at resolveField (node_modules\graphql\execution\execute.js:508:16)

swagger-to-graphql generates an object whith the GraphQLSchema which all context information can be passed in order to generate the resolver functions correctly.
The schema object (working only since version 1.2.2) is being passed to yoga almost correctly, see the error.
My best guess is that the host url (GQLProxyBaseUrl: API_BASE_URL) is being resolved (meaning promise) from graphql-express but not from the graphql-apollo-server.

In my understanding it would be better to pass all required information to swagger-to-graphql before it's schema generation, so that all queries can be resolved independently from the graphql server as intended.

@yarax what do you say? What am i missing? Any quickfix for this? Do you have something in mind for this?

Also related to #46

Error: Names must match

Hi,

I have tried to convert my rest to graphql but its shows me an error and I dont know why, my swagger schema working well and is well built I think. Can you help me? I have attached my swagger.json and my types results ( renamed to txt to can be uploaded).

schema.txt
types.txt

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.