GithubHelp home page GithubHelp logo

graphql-community / koa-graphql Goto Github PK

View Code? Open in Web Editor NEW
839.0 839.0 70.0 2.31 MB

Create a GraphQL HTTP server with Koa.

License: MIT License

JavaScript 14.19% Shell 0.97% TypeScript 84.84%
graphql koa koa-graphql koa-middleware

koa-graphql's People

Contributors

alexsey avatar axetroy avatar chentsulin avatar clarkdo avatar dependabot[bot] avatar dios-david avatar entropitor avatar maxdesiatov avatar neighborhood999 avatar seidelmartin avatar sibelius avatar sonnypgs avatar thewillhuang avatar tornqvist avatar tryshchenko avatar tuckerconnelly avatar yanickrochon 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

koa-graphql's Issues

The types of 'astNode.loc' are incompatible between these types

I'm trying make simple server with the following code :
`
import { buildSchema } from 'graphql';

const graphqlRouter = new Router();
graphqlRouter.all(
/gql,
graphqlHTTP({
schema: buildSchema(
type Query { hello: String }
),
graphiql: false,
}),
);
`

but on line schema shows this:

Type 'import("node_modules/graphql/type/schema").GraphQLSchema' is not assignable to type 'import("node_modules/@types/koa-graphql/node_modules/graphql/type/schema").GraphQLSchema'.
The types of 'astNode.loc' are incompatible between these types.
Property 'toJSON' is missing in type 'import("node_modules/graphql/language/ast").Location' but required in type 'import("node_modules/@types/koa-graphql/node_modules/graphql/language/ast").Location'.ts(2322)

my setup includes

  • "type-graphql": "^1.0.0-rc.2",
  • "koa-graphql": "^0.8.0" & @types/koa-graphql": "^0.8.4"

Exposing graphql request?

I know that you can access the request object when you initiate the middleware but is it possible for me to get the graphql request's info also so that I can log it,
example:

graphqlHTTP((request, context) => {
       console.log(request.graphqlQuery);
       console.log(request.graphqlVariables);
})

Right now when I make a post request, I don't know what requests are hitting my server?

support fieldResolver

Latest graphql already add fieldResolver in execution, koa-graphql should keep up with it.

Input Data of a Mutation are not based on Standard JavaScript Object/ Array

If I have a mutation like this:

import { mutationWithClientMutationId } from 'graphql-relay';
export default mutationWithClientMutationId({
  name: 'BulkImportOrganizations',
  inputFields: {
    listOfOrganizations: {
      type: new GraphQLList(OrganizationType),
    },
    apiKey: {
      type: GraphQLString,
    },
  },
  mutateAndGetPayload: async({ listOfOrganizations, apiKey }) => {
    const output = {
      regStatus: [],
      error: {
        code: [],
        message: []
      }
    };

I wounder why is listOfOrganizations not an array? It seems to be a pseudo array but does not implement the corresponding methods according to the Array Prototype neither it has the Array prototype. The same goes for plain Objects.

Koa 2.x

Will need to support async await with koa 2.0:

app.use(async (ctx, next) => {
  // ...
  await next();
  // ...
});

Merge `data` and `errors` into response body instead of re-assign

Hello. This module works pretty well. I am suggesting an enhancement. After executing and resolving GraphQL, the results are assigned to the response.body https://github.com/chentsulin/koa-graphql/blob/master/src/index.js#L294-L296.

This will overwrite any other information that the server might have set. There may be additional information we want to send down that isn't part of the schema. Perhaps instead of a reassignment, it could attempt an object merge so that the developer can send down other information. I've put in PR #103 for this suggestion.

[flow] type error

I am using koa-graphql with flow, and it throw error with can not find module "express".
Because express-graphql import express with flow, we need to install express in the project. However, we use koa, not express, this is strange.

Support HEAD method for /graphql

I have multiple instances of GraphQL servers running behind a AWS ELB (elastic load balancer).

ELB recurrently checks the status of each node performing a small ping to each node. AWS default validation mode uses HEAD method (it will not use GET or POST).

Currently (as far I was able to check) koa-graphql will return a error if a HEAD request is performed. This causes ELB to assume that the node is dead and will stop to route requests.

Need HEAD to also be supported

graphiql option seems to ignore false value

I'm trying to disable GraphiQL and it doesn't seem to be working even though that I explicitly pass false value to it:

app.use(convert(graphqlHTTP(async req => {
  return {
    graphiql: false,
    schema,
    context: {
      ...
    },
    ...
  };
})));

Read response object after koa-graphql has run

I'd like to read the response object that's going to be sent back to the requestor. When I interrogate the response object that's passed when providing a function to koa-graphql, it seems it's before the final response has been composed.

i.e.

function middleware() {
 return graphqlHTTP(
    (request: Object, response: Object, params: Object): Object => {
      // read the response that will be provided to the requestor
      // the response at this point in time is incomplete, it seems. In fact, the status code will be 404.
      return {
        schema,
        graphiql: enableGraphiql || isNotProd,
        formatError: errorFormatterWithMetadata,
        pretty: prettifyJsonResponse,
        extensions: extensionWithMetadata,
        validationRules: additionalValidation,
      }
    },
  )
 }
}

async function in compiled version 0.7.0

in koa-graphql 0.7.0, the compiled version has async syntax

we are using node 6.10.0 LTS (https://github.com/nodejs/LTS)

node_modules/koa-graphql/dist/index.js:38
  return async function middleware(ctx) {
               ^^^^^^^^
SyntaxError: Unexpected token function
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:542:28)
    at Module._extensions..js (module.js:579:10)

Working with query in resolve()

I am stuck with how to work with the incoming query. I want to be able to pass the requested fields from the graphql query and pass them to my controller which ultimately down the line sends those to my mySQL find() function which does a select id, name from Company.

I need to be able to send id, name (or whatever the fields from the graph is that is requested) which I get from the graphql query that's incoming so that my find() can dynamically return requested fields per the graphql query.

I wrote this test:

it.only('returns company data', async () => {
    const stub = {
        data: {
          Company: {
            id: 1,
            name: 'Pivotal'
          }
        }
      },
      query = queryString({
        query: `{
          company { 
            id,
            name
          }
        }`
      }),
      url = `/graphql?${query}`,
      response = await request
        .get(url),
      reponseData = JSON.parse(response.text);

    expect(reponseData).to.deep.equal(stub);
  });

and it's using one of your helpers I found in your tests (I renamed it to queryString):

function queryString(urlParams?: ?{ [param: string]: mixed }) {
  let querystring
  if (urlParams) {
    querystring = stringify(urlParams);
  }
  return querystring;
}

When I run this test, I see the following being passed to superagent:

screen shot 2017-09-09 at 12 42 06 pm

On the koa service side, using koa-graphql, I have it setup like this:

import {
  graphql,
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLID,
  GraphQLString
} from 'graphql';

import Companies from '../controllers/Company';

const Company = new GraphQLObjectType({
    name: 'Company',
    fields: () => ({
      id: {
        type: GraphQLID
      },
      name: {
        type: GraphQLString
      }
    })
  }),

  Query = new GraphQLObjectType({
    name: 'Query',
    fields: () => ({
      company: {
        type: Company,
        resolve(parentValue, args, ctx) {
          //not quite sure what to do here.  I need filter to represent an array of requested fields (in this case it's id and name)  from the graphql query or something like that
          const company = async () => Companies.find(filter);
          return company;
        }
      }
    })
  }),

/*  resolve() {
  return {
    id: 1,
    name: 'Pivotal'
  };
}*/

  mySqlSchema = new GraphQLSchema({
    query: Query
  });

export default mySqlSchema;

or am I going about this the wrong way?

Q: Thoughts on debugging tools?

It would be great if we could pass an option that logs the request query and variables and the response data. Does that belong in this library or should I create like koa-graphql-logging?

How to yield in a resolver?

I'm trying to use the generator in the resolver of a graphql type? But it doesn't seem to work.

new GraphQLObjectType({
  name: 'MyType',
  fields: {
    myField: {
      type: GraphQLString,
      resolve: function *(parentValue, args, session) {
          return yield fetch("/some/api")
      }
    }
  }
});

The returned value is this

{
  "myField": ["Object generator"]
}

I guess its not possible to make resolvers synchronous using yields.

Status of this Module?

Hi, what is the status of this module, there are some upgrades due by now I think and as active user I'm a bit concerned.
BG

Impossible to access cookies within mutateAndGetPayload

Hello here

At first glance this library looks nice, unless you start working with it and end up stack with poor documentation. I have a very simple and very common use case. I want to handle auth. through session and by having LoginMutation I need to access ctx inside it so I can:

  1. set cookies
  2. access ctx.* objects

Without such information - it's completely useless.

Right now I've tried to set cookies on 2nd and 3rd argument. Nothing works.
Attempted to pass values through rootValue - same.
It's literally impossible to use that library when everything in Koa is running around ctx

It's either me not understanding something or my case is super rare

server.js

router.all(
  '/graphql',
  graphqlHTTP((request, ctx) => ({
    schema: graphqlSchema,
    graphiql: true,
    rootValue: { ctx },
    pretty: true,
  })),
)

LoginMutation.js

  mutateAndGetPayload: async ({ email, password }, ctx) => {
    ctx.cookies.set('mykEY', '123')
    console.log(`ctx.cookies.set: ${ctx.cookies.get('mykEY')}`) //nothing
}

When I do that inside middleware - it works!

server.js

app.user(mymw)

mymw.js

export default async function sessionMiddleware(ctx, next) {
  console.log(`ctx.cookies.set: ${ctx.cookies.get('mykEY')}`)
  ctx.cookies.set('mykEY', '123') // here

//2nd call and it's there

GraphQL v14 support

Right now koa-graphql supports an old version of graphql (0.13.2), but the latest one is v14.0.2. This should be fixed because GraphQL doesn't support to have multiple instances installed.

If you need any help with this update I could try to make a PR for it 👍

Flow error

I get the next flow error using this library:

node_modules/koa-graphql/dist/index.js.flow:164
164:       req.body = req.body || request.body;
               ^^^^ property `body`. Property not found in
164:       req.body = req.body || request.body;
           ^^^ http$IncomingMessage

"regeneratorRuntime is not defined"

with 5.3, I now get this:

general error:  ReferenceError: regeneratorRuntime is not defined
    at graphqlHTTP (/Users/dev/app/node_modules/koa-graphql/dist/index.js:41:10)

Session value example

In the express-graphql repo, there is an example in the Readme demonstrating session usage. How will that look like with koa-graphql? Basically, I want to access session variables and use it in my schema

Perform mutation on GET

Hello, thanks for this awesome lib.
Are there any special reasons for not allowing mutations on GET?

koa-graphql/src/index.js

Lines 229 to 249 in 4d6d9c3

// Only query operations are allowed on GET requests.
if (request.method === 'GET') {
// Determine if this GET request will perform a non-query.
const operationAST = getOperationAST(documentAST, operationName);
if (operationAST && operationAST.operation !== 'query') {
// If GraphiQL can be shown, do not perform this query, but
// provide it to GraphiQL so that the requester may perform it
// themselves if desired.
if (showGraphiQL) {
return resolve(null);
}
// Otherwise, report a 405: Method Not Allowed error.
response.set('Allow', 'POST');
throw httpError(
405,
`Can only perform a ${operationAST.operation} operation ` +
'from a POST request.',
);
}
}

Fix coverage reporting

The README badges still point to the previous repository location, while updating it, the Coverall badge is no longer valid (at least it isn't updated with latest reports).

Furthermore, coverage is actually disabled in .travis.yml so the coverage report has not been updated in a while anyway.

The graphiql property doesn't allow assigning any value with type other than a boolean (TypeScript).

  • Typescript: 3.9.3
  • koa-graphql: 0.8.0
  • @types/koa-graphql: 0.8.3

I'm tried to set up the "Darkula" theme for GraphiQL following this manual: Custom GraphiQL themes, but get an error about a type.

Type '{ editorTheme: string; }' is not assignable to type 'boolean'.

Code

graphqlHTTP({
    schema,
    graphiql: {
        editorTheme: 'darkula',
    },
})

Type definitions

    /**
     * A boolean to optionally enable GraphiQL mode.
     */
    graphiql?: boolean;

Expose GetBody Limits?

Allow limit to be passed instead of forcing it to 100Kb. Just got an error in production while doing a demo and flipped. At least set the default to something like 1mb or 2mb.

install from github

is it possible to install koa-graphql directly from github?

npm i git+ssh://[email protected]/chentsulin/koa-graphql.git --save

the folder of koa-graphql it is empty inside node_modules when I install from github

how to using koa-graphql with [email protected]

i used koa-router and koa-graphql with koa2 like this:

var router = new Router();
router.use('/graphql',graphqlHTTP({schema: schema}));
app.use(router.routes());

when i visite /graphql. but the router not work.
how do i do. thx.

Execution after validation failed.

Hi,
I'm writing complexity validator.
But I found that still processing query after return 400.
And the point is in koa-graphgl/dist/index.js line 132 ~ 138

        // Validate AST, reporting any errors.
        var validationErrors = (0, _graphql.validate)(schema, documentAST, validationRules);
        if (validationErrors.length > 0) {
          // Return 400: Bad Request if any validation errors exist.
          response.status = 400;
          resolve({ errors: validationErrors });
        }

And it can simple change by add return after calling resolve.

In express-graphql implementation it will not continue execution after validation failed.

Maybe we can add a option to determine whether it should be execute after validation failed or not.
It would be great.

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.