graphql-community / koa-graphql Goto Github PK
View Code? Open in Web Editor NEWCreate a GraphQL HTTP server with Koa.
License: MIT License
Create a GraphQL HTTP server with Koa.
License: MIT License
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
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?
As said in self-closed #32:
npm install --save koa-graphql
[email protected] .../Desktop/app
├── UNMET PEER DEPENDENCY [email protected]
├── UNMET PEER DEPENDENCY graphql@^0.4.16
└─┬ [email protected]
└─┬ [email protected]
├── [email protected]
└── [email protected]
Execution:
module.js:341
throw err;
^
Error: Cannot find module 'graphql'
Latest graphql already add fieldResolver in execution, koa-graphql should keep up with it.
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.
Will need to support async await with koa 2.0:
app.use(async (ctx, next) => {
// ...
await next();
// ...
});
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.
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.
Throw errors to be handled by koa error handler rather than formatting and sending them to the client with a 200.
That way the client can respond to failed requests based on HTTP status codes rather than checking for stack
in the returned data
When there is a validation errors in the variables, a 200 is returned instead of a 400
It's helpful for using node req
and node res
to directly migrate from express to koa, but It's not the koa style. We should use request
and response
wrapped by koa.
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
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: {
...
},
...
};
})));
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,
}
},
)
}
}
graphql version is 0.11.1 now, but cannot satisfy ^0.10.0
listed in peerDependencies
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)
Use case:
Throw a GraphQLError
as part of a validation on a custom GraphQLScalarType
.
0.8.0:
parseValue
: returns a 500 response
0.7.5:
parseValue
: returns 200 and the actual errors
from GraphQL
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:
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?
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?
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.
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
npm WARN [email protected] requires a peer of graphql@^0.12.0 || ^0.13.0 || ^14.0.0 but none is installed. You must install peer dependencies
yourself.
npm WARN [email protected] requires a peer of graphql@^0.12.0 || ^0.13.0 || ^14.0.0 but none is installed. You must install peer dependencies yourself.
@chentsulin koa-graphql should now be available to you.
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:
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
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 👍
In console React.render is not a function
Can we do something like this: https://github.com/janie128/subscription-graphql/blob/master/server/index.js#L18-L21?
using koa-graphql?
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
Latest version available is only 0.8.0:
https://www.npmjs.com/package/koa-graphql
When installed i get this warning:
npm WARN koa-graphql@0.4.10 requires a peer of graphql@^0.4.16 but none was installed.
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)
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
Hello, thanks for this awesome lib.
Are there any special reasons for not allowing mutations on GET?
Lines 229 to 249 in 4d6d9c3
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.
Per express-graphql
documentation :
customFormatErrorFn
. It will be removed in version 1.0.0.getGraphQLParams(request: Request): Promise<GraphQLParams>
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;
I cannot find any example of using this lib to handle subscriptions. Is it even supported? If so, please point me to an example. Thanks
How can i'm parse response?
and add back npm run check
app.use(urlString(), graphqlHTTP((request, ctx) => {})
will become:
app.use(urlString(), graphqlHTTP((request, response, ctx) => {})
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.
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
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.
Refs:
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.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.