mercurius-js / mercurius Goto Github PK
View Code? Open in Web Editor NEWImplement GraphQL servers and gateways with Fastify
Home Page: https://mercurius.dev/
License: MIT License
Implement GraphQL servers and gateways with Fastify
Home Page: https://mercurius.dev/
License: MIT License
🚨 You need to enable Continuous Integration on Greenkeeper branches of this repository. 🚨
To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.
Since we didn’t receive a CI status on the greenkeeper/initial
branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.
If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/
.
Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.
I would like to propose fastify.graphql.setSchema() , something like:
fastifyGraphQl.setSchema = function(s) {
if (typeof s === 'string') {
schema = buildSchema(s)
} else {
schema = s;
}
// we should clear the caches, because they could be totally invalid now
lru.clear();
lruErrors.clear();
}
My use case is an admin dashboard that allows adding/updating/deleting fields from types, as well as adding/deleting types.
I believe this function would allow me to make a change in my admin dashboard, call setSchema(), and then without re-starting the app, my graphql route would be utilizing the new schema.
I'd be willing to submit a PR with test and README updated if this is something that you think would be useful to the general community.
I have been trying to protect the following route
/graphql
/graphiql
How can this be done?
When bootstrapping fastify-gql
without a schema in order to add schemas with extendSchema
, the declaration of type Query makes the usage of GQL inconsistent as you have to extend Query but not Mutation. I understand that declaring type Mutation
in fastify-gql would force the user to declare a mutation to make a valid schema. But why chose query other mutation ?
Either both shouldn't be declared, or maybe add an option that enable the definitions ?
By the way the example of extendSchema
in the README is wrong the schema should be extend Query
as query is already declared.
Yesterday I've started a new plugin that adds the mutation, query, and date Scalar if needed fastify-gql-base. But I think that query and mutation should be handled in this plugin.
In order to use this package with typescript it requires proper typings.
I've made some progress, however I've find out that for now it's not possible. That's because now in fastify typings plugin RegisterOptions
extend RouteShorthandOptions
for some reason not known to me. RouteShorthandOptions
however contains schema
field that has type RouteSchema
that's obviously incompatible with the same field schema
in this module which could be either string or GraphQLSchema.
Typescript allows to redefine RouteShorthandOptions
with additional types for schema
, but it will affect all routes. So I think we should wait for fastify/fastify#1569 to be merged. Or if you have any other suggestions, you're welcome.
Kudos for creating an amazing library.
I have played with it and noticed that there is another problem when dealing with GraphQL on the resolver side. GraphQL-js by default has this feature to execute query and pick what user wanted from the whole object returned from root resolver (and relationship resolvers as well)
https://github.com/graphql/graphql-js/blob/master/src/execution/execute.js#L457-L463
What it does is simply pick elements from the graph based on what the user requested in the client. In some cases, graphql queries can be misused on client.
For example, someone can query half of the database with one resolver but just return a single key to client entire type. Querying username from getUserProfile()
query. The problem can be seen for API's that are shared with 3rd parties etc.
I think that developers can improve performance dramatically if:
info
object with the client query to see what client realy wants (instead of blindly return everything)For simple getProfile
example on the main page this can help backend to process around 80% more requests.
That approach will be an alternative to DataLoader which I think just adds to the problem for resolvers using direct database connections.
See blog post: https://medium.freecodecamp.org/a-5-line-major-efficiency-hack-for-your-graphql-api-type-resolvers-b58438b62864
Info object is not actually so nice to work with for someone who start with GraphQL. Adding helper to fastifyQL will radically improve the performance of average applications that connect to the database or REST endpoints that support the filter
argument.
I have experimented with this approach in https://github.com/graphql-heroes/graphql-backend-gen and it really works.
Hi
I use throw new Error("XXXX"), however looks like i got a 500 error for first requst everytime when program start, but the next requst is OK (i got 200 reponse for next time, the same request, the same error message without 500 error, shows username or password is wrong)
the error message shows something wrong from index.js:299:19... guys any idea for this?
I'm a newbie, please suggestions, thanks
My version: "fastify-gql": "^3.0.6",
server started at "http://localhost:3000/playground.html
InternalServerError: Internal Server Error
at Object.fastifyGraphQl [as graphql] (D:\javascript\alpha\node_modules\fastify-gql\index.js:299:19)
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
message: 'Internal Server Error',
errors: [
Error: input username or password is wrong
at userResolver.hello (D:\javascript\alpha\src\module\user\userResolver.ts:35:15)
at Object. (D:\javascript\alpha\node_modules\type-graphql\dist\resolvers\create.js:16:64)
at Generator.next ()
at fulfilled (D:\javascript\alpha\node_modules\tslib\tslib.js:107:62)
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
message: 'input username or password is wrong',
locations: [Array],
path: [Array]
}
],
data: null
}
Hello again,
following #125 I'm trying to create a plugin to make possible to upload a file thru this amazing library, based on GraphQL multipart request spec.
I'm using fastify-plugin and fastify-multipart. I have created this stub:
'use strict';
const fp = require('fastify-plugin');
function GQLUpload(fastify, opts, next) {
if (!fastify.hasRequestDecorator('multipart')) {
fastify.register(require('fastify-multipart'), opts);
}
fastify.addHook('onResponse', (request, reply, done) => {
if (request && request.body) {
console.log(request.body);
}
done();
});
next();
}
module.exports = fp(GQLUpload, {
fastify: '>= 2.x',
name: 'fastify-gql-upload',
dependencies: ['fastify-multipart']
});
With this code, I'm able to see the body in the console, like this:
{
'1': [
{
data: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 02 00 00 00 03 00 08 06 00 00 00 52 0f df 4e 00 00 00 04 73 42 49 54 08 08 08 08 7c 08 64 88 00 ... 35718 more bytes>,
filename: 'no_image.png',
encoding: '7bit',
mimetype: 'image/png',
limit: false
}
],
operations: '{"operationName":null,"variables":{"id":"F8JgzO4Wvp5TeicbO1mC","file":null},"query":"mutation ($id: ID!, $file: Upload!) {\\n addNewsImage(newsId: $id, file: $file)\\n}\\n"}',
map: '{"1":["variables.file"]}'
}
Now, the endpoint return this error with HTTP 400
Must provide Source. Received: undefined
and the resolver is not executing.
My question is: how to pass the data from the response.body to the resolver's function?
I'm very sorry to post such open and broad question with little code, but I'm really not understanding how to complete the flow.
Is it possible to enrich the context thats being sent to the resolvers?
Perhaps through a function that you supply when creating the instance, something like this:
app.register(GQL, {
schema,
resolvers,
context: (request, reply) => ({ foo: true }),
});
Is there any support for typescript in fastify-gql?
Hello!
It seems the calculation for query depth is not considering only the depth of a query, but also hoy many fields it returns.
Here is a real example:
fragment metric on WeatherDatum {
actual
units
delta
style
normal
}
fragment metricArray on WeatherData {
actual
normal
units
style
}
fragment summedMetricArray on WeatherSummedData {
units
array
sum
}
query FieldMetrics($farmId: String) {
fieldForecast(id: $farmId, unit: Metric) {
temperature {
today {
...metric
}
maximaOverYear {
...metricArray
}
}
rainfall {
accumulation {
...metricArray
}
last30DaysSummed {
...summedMetricArray
}
today {
...metric
}
yesterday {
...metric
}
nextWeek {
...metric
}
}
country
state
county
updateTime
createdTime
}
}
The maximum depth seems to be 3: fieldForecast > temperature > today
But when running the query in playground, I am receiving:
I'm using the fastify-caching npm package to cache requests, however large queries still takes 300ms to return to client, where the same query with express and memory-cache package take around 60 after being cached. So how can i efficiently cache the query results with fastify? :)
Hi. There's graphql playground that does pretty much the same things that graphiql does. However it has more features. Here's demo page: https://www.graphqlbin.com/v2/6RQ6TM
It has standalone package https://www.npmjs.com/package/graphql-playground-html that contains several html files https://github.com/prisma/graphql-playground/tree/master/packages/graphql-playground-html that could be used just like as graphiql.html. We could copy one of them into static folder just like it's done in fastify-swagger plugin.
Also it doesn't use service worker which allows to explore it without having https (e.g. on some domain like example.loc that will point to 127.0.0.1). In such case graphiql doesn't work.
I could send PR with this changes, but I need a suggestion which route it should expose: /gql-playground
or graphiql-playground
or something else.
After setting up fastify-gql, i get a 404 error relating to the main.js file whenever i go to the '/graphiql' endpoint.
here's my setup
export const gqlSchema = `
type Query {
adhesive: [String]
}
`
export const gqlResolvers = {
Query: {
adhesive: () => ['1', '2', '3']
}
}
`
and here's how i registered it on fastify
const server: fastify.FastifyInstance<
Server,
IncomingMessage,
ServerResponse
> = fastify({
logger
})
// eslint-disable-next-line
server.register(require('fastify-gql'), {
gqlSchema,
gqlResolvers,
graphiql: true
})
Why this has not been added yet to the fastify ecosystem ?
This is considered unstable ?
Or you do not plan a long term support for this library and it was just a technical demonstrator ?
Anyway I'm using it for a personal project and I love the work you've done with the LRU cache and the jit compiler, Nice optimizations !
most GraphQL code out there is probably using Apollo, and it is probably using makeExecutableSchema
which results in something meaningful for Apollo ( but not for fastify-gql )
Currently, passing the list of schema
and resolvers
directly to fastify-gql
won't work directly.
It could be cool to have a straightforward way to migrate this :)
Just based on the benchmarks here,
https://github.com/the-benchmarker/graphql-benchmarks/blob/develop/latency.md
I noticed that both frameworks using Fastify have high latency, especially fastify-gql. Is there some bias in the benchmark? Or, is this a limitation of fastify-gql?
Thanks
Sending payload in Mutation also returns this "[Object: null prototype]" as a reference key for the actual payload - seems to be a bug.
Workaround:
JSON.parse(JSON.stringify(payload))
Reproduce:
server.js config for GQL Fastify
app.register(GQL, {
schema: makeExecutableSchema({typeDefs, resolvers})
});
Resolver
Mutation: {
createUser: async (_, {payload}) => {
console.log(payload);
}
}
TypeDefs / Schema
type User {
id: ID
firstName: String
lastName: String
username: String
email: String
avatar: String
birthDate: Float
startDate: Float
}
input UserInput {
id: ID
firstName: String!
lastName: String!
username: String
email: String!
avatar: String
birthDate: Float
startDate: Float
}
type Query {
getOneUser(id: ID!): User
}
type Mutation {
createUser(payload: UserInput): User
}
Mutation Query
mutation {
createUser(payload:{
id: "52jk452k3j452jk3452k3452345kjfac",
firstName: "Rehan",
lastName: "Haider",
username: "rehanhaider",
email: "[email protected]",
avatar: "https://tinyurl.com/qsqau3r",
birthDate: 41234123412341,
startDate: 41234123412344
}) {
firstName
lastName
lastName
username
email
avatar
birthDate
startDate
}
}
Might be similar to this: apollographql/apollo-server#3149
Let me know if more details are required.
Any Example on how to leverage fastify-jwt plugin with fastify-gql for authentication and Authorization example?
Add support for application/graphql Content-Type.
express-graphql already supports it, while appolo-server does not.
It is true, that GQL variables can not be passed as part of the query, but it becomes much easier to use in command line, automated tests and benchmarks.
Just installed Fastify GQL and I can't seem to render the Graphiql interface / page on localhost.
Pretty basic stuff but can't seem to get it to work - maybe I'm missing something and I would appreciate the help.
Thanks!
Hey, thanks for this great tool.
I'm having difficulties to integrate an upload service.
These are the packages installed:
"fastify": "2.12.0",
"fastify-gql": "3.0.6",
"fastify-cors": "3.0.1",
"fastify-multipart": "1.0.5",
"graphql": "14.6.0",
"graphql-upload": "10.0.0",
and setup my server as:
import fastify = require('fastify');
import GQL = require('fastify-gql');
import cors = require('fastify-cors');
import multipart = require('fastify-multipart');
const app = fastify();
app.register(cors, { origin: '*' });
app.register(multipart, { addToBody: true });
// schema and context come from my graqphl implementation
app.register(GQL, {
path: '/',
schema,
context,
graphiql: process.env.NODE_ENV !== 'production' && 'playground'
});
const port = 4000;
app.listen(port, () => console.log(`🚀 Server ready at http://localhost:${port}`));
But every time I try to upload i get this error
Must provide Source. Received: undefined
as if the server does not recognize the post with multipart/form-data.
Thanks for any help!
2.19.0
to 2.19.1
.This version is covered by your current version range and after updating it in your project the build failed.
@typescript-eslint/parser is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.
The new version differs by 5 commits.
1c8f0df
chore: publish v2.19.1
4c12dac
fix(typescript-estree): ts returning wrong file with project references (#1575)
e9cf734
docs(eslint-plugin): fix typo in readme
10d86b1
docs(eslint-plugin): [no-dupe-class-members] fix typo (#1566)
4670aab
fix(eslint-plugin): [unbound-method] blacklist a few unbound natives (#1562)
See the full diff
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
In graphQL, it is possible to go create an object like this
const AuthorType = new GraphQLObjectType({
name: 'Author',
fields: ( ) => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
age: { type: GraphQLInt },
books: {
type: new GraphQLList(BookType),
resolve(parent, args){
return Book.find({ authorId: parent.id });
}
}
})
});
now with fastify-gql, i'm also trying to do something like that, i know the data types are different, but i don't know how to add a resolver to the dependent property
type AuthorType {
id: Int,
name:String,
age: Int,
books: {
type: [BookType],
resolve(parent, args){
return Book.find({ authorId: parent.id });
}
}
})
}
i've tried doing something like the above (i didn't think it'd work but i wanted to try it)..it didn't.
my issue now is, how do i go about creating a resolver for the dependent property.
The current implementation of processing Graphql Errors is not compatible with Graphql Specification.
From rmosolgo/graphql-ruby#1130 (comment)
It's common practice to use 200 for all GraphQL requests. When errors happen, they're put in the "errors" key. Non-200 response codes indicate that some issue occurred at the HTTP transport layer, not the GraphQL layer.
Current implementation includes next validation for 200 status code
const responseSchema = {
'2xx': {
type: 'object',
properties: {
data: {
type: 'object',
additionalProperties: true
},
errors: {
type: 'object', // <------- Problem is here. Errors should have type array
properties: {
message: { type: 'string' },
locations: {
type: 'array',
items: {
type: 'object',
properties: {
line: { type: 'integer' },
column: { type: 'integer' }
}
}
},
path: {
type: 'array',
items: { type: 'string' }
}
}
}
}
}
}
Also, I noticed, that data
can't be null.
It would be good to have some level of optional subscription support on top of fastify-gql, maybe using https://github.com/fastify/fastify-websocket.
https://github.com/graphql/graphql-spec/blob/master/rfcs/Subscriptions.md is the definition of subscriptions.
For the pub/sub layer, I'd recommend using https://github.com/mcollina/mqemitter as it has 2 backend implementations (one with Redis and one with MongoDB).
I'm looking for a way to take advantage of Fastify schema validation and serialization. GraphQL allows type validation but this is not enough for user inputs validation.
For now I'm using my own architecture with a model validation through AJV and json-schemas, but I'm wondering if I can benefit from fastify validation for inputs and serialization optimization for outputs (fast-json-stringify). Correct me if I'm wrong, but I don't think that fastify-gql response schema allows to break JSON recursive call for serialization optimization due to additionalProperties: true
https://github.com/mcollina/fastify-gql/blob/d5d79d4a62a03a9ac5d742fe90354b1c6070aef6/routes.js#L7-L18
Merging graphql schemas and fastify json-schemas handling would be awesome. Maybe providing a json-schema that mirrors graphql types, queries and mutation and handle this inside the lib ?
Did you think about this subject yet ? Is this viable or useless for any reason that I'm missing ? Or fastify can't bring much more than my actual setup with AJV ?
Can anyone provide an example of how to upload file via GraphQL?
Hey, everyone
Does fastify-gql
have method for replacing existing graphql schema with another one?
I'm using a microservice architecture with graphql and in some cases, I need to setup schema's autorefresh. (I'm using simple recursive setTimeout)
Example of code for Apollo-Server
const refreshSchema = async () => {
try {
const schemaDerivedData = await graphqlServer.schemaDerivedData;
graphqlServer.schemaDerivedData = Promise.resolve({
...schemaDerivedData,
schema: await generateSchema(),
});
} catch (err) {
logger.warn(err, {
method: 'server.initializeApplication::refreshSchema',
});
}
setTimeout(refreshSchema, config.refreshTimeout);
};
setTimeout(refreshSchema, config.refreshTimeout);
Could I somehow replace the existing graphql schema with a new one?
fastifyGraphQl.replaceSchema = function (s) {
if (!s || typeof s !== 'object') {
throw new Error('Must provide valid Document AST')
}
schema = s
}
Do you have plans to support Fastify 2?
In https://www.apollographql.com/docs/apollo-server/federation/federation-spec/, the Apollo fedaration protocol is defined. We should support the federation protocol so that fastify-gql services can be exposed by the federation server.
4.5.0
to 4.5.1
.This version is covered by your current version range and after updating it in your project the build failed.
autocannon is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
if I run this script:
'use strict'
const Fastify = require('fastify')
const GQL = require('fastify-gql')
const makeExecutableSchema = require('graphql-tools').makeExecutableSchema
const app = Fastify()
const schema = [
`
type Query {
history(id: ID!): [History]
}
`,
`
type History {
id: ID!
name: String!
created: Date!
sysPeriod: Range!
}
`,
`
type Range {
begin: Date!,
end: Date!
}
`,
`
scalar Date
`
]
const resolvers = {
Query: {
history: async ({ id }) => {
return Promise.resolve({ id, name: 'test', created: new Date(), sysPeriod: 'not a range!' })
}
}
}
app.register(GQL, {
schema: makeExecutableSchema({ typeDefs: schema, resolvers: [resolvers] }),
graphiql: true
})
app.get('/', async function (req, reply) {
console.log('/')
const query = `
{
history(id: "1") {
id
name
created
sysPeriod {
begin
end
}
}
}
`
return reply.graphql(query)
})
app.listen(7000)
then do a curl to hit /
like this, I have http 200 + some error reporting:
curl http://localhost:7000 | jq
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 170 100 170 0 0 3269 0 --:--:-- --:--:-- --:--:-- 3269
{
"errors": [
{
"message": "Expected Iterable, but did not find one for field Query.history.",
"locations": [
{
"line": 3,
"column": 5
}
],
"path": [
"history"
]
}
],
"data": {
"history": null
}
}
but if I go to /graphiql
with a browser and run the same query:
{
history(id: "1") {
id
name
created
sysPeriod {
begin
end
}
}
}
I still have a http 200, null
data.history
, but no errors reported.
I believe I should not have a http 200
as a result, probably an http 500
, and it should probably detail the errors
With:
I want to use graphql-cost-analysis, So my question is how can I use that one because it requires validationRules
property.
Any clue?
Dat your presentation at nodeconf. And want to use it instantly. So it would be Very helpful if you could Add some documentation.
2.11.0
to 2.12.0
.This version is covered by your current version range and after updating it in your project the build failed.
fastify is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.
📚 PR:
The new version differs by 38 commits.
7a37924
Bumped v2.12.0
aacefcd
Add docs to stop processing hooks with async (#2079)
c052c21
fix: throw hooks promise rejection (#2070) (#2074)
6b39870
Add missing TS definition for ServerOptions.genReqId function arg (#2076)
7fa4bdd
Fixed documentation typo (#2067)
6b73e0a
fix: use opts of onRoute hook (#2060)
7bb9733
Added fastify-response-validation to ecosystem (#2063)
0a1c1f0
Update README.md (#2064)
bd9f608
chore(package): update yup to version 0.28.1 (#2059)
e19d078
chore(package): update fluent-schema to version 0.10.0 (#2057)
d0c976e
http2: handle graceful close (#2050)
af8a6ac
docs: inject chainable methods (#1917) (#2043)
62f21b1
Workaround for using one schema for multiple routes (#2044)
5258f42
docs: OpenJS CoC (#2033)
ac46905
Shorten longest line (docs) (#2035)
There are 38 commits in total.
See the full diff
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
Some support for this feature would be interesting, which helps to improve network performance. But I don't know if there is any standardization to implement this.
About persisted queries: "A persisted query is an ID or hash that can be sent to the server instead of the entire GraphQL query string. This smaller signature reduces bandwidth utilization and speeds up client loading times. Persisted queries are especially nice paired with GET requests, enabling the browser cache and integration with a CDN."
Interesting links:
This plugin for express-graphql and koa-graphql address the issue of depth limiting graphql queries - https://github.com/stems/graphql-depth-limit to help with the problem of depth limiting
The rationale is explained in the readme - https://github.com/stems/graphql-depth-limit#why
This is probably only really an issue for public APIs but perhaps we could implement a fastify-gql version of this plugin or raise a pr on that one to add support for fastify-gql
2.19.0
to 2.19.1
.This version is covered by your current version range and after updating it in your project the build failed.
@typescript-eslint/eslint-plugin is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.
The new version differs by 5 commits.
1c8f0df
chore: publish v2.19.1
4c12dac
fix(typescript-estree): ts returning wrong file with project references (#1575)
e9cf734
docs(eslint-plugin): fix typo in readme
10d86b1
docs(eslint-plugin): [no-dupe-class-members] fix typo (#1566)
4670aab
fix(eslint-plugin): [unbound-method] blacklist a few unbound natives (#1562)
See the full diff
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
Hello, I'm trying fastify-gql but I have been getting this issue when I try to register GQL. It happens with or without the options and with or without other fastify plugins.
Every dependency is up-to-date.
(node:25896) UnhandledPromiseRejectionWarning: Error: plugin must be a function or a promise
at assertPlugin (/nodejs_graphql_typescript_starter/node_modules/avvio/boot.js:184:11)
at Boot._addPlugin (/nodejs_graphql_typescript_starter/node_modules/avvio/boot.js:196:3)
at Boot.use (/nodejs_graphql_typescript_starter/node_modules/avvio/boot.js:190:8)
at Object.server.<computed> [as register] (/nodejs_graphql_typescript_starter/node_modules/avvio/boot.js:31:14)
at /nodejs_graphql_typescript_starter/src/index.ts:25:7
at Generator.next (<anonymous>)
at fulfilled (/nodejs_graphql_typescript_starter/src/index.ts:5:58)
(node:25896) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:25896) [DEP0018] 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.
index.ts
import * as dotenv from 'dotenv';
import * as fastify from 'fastify';
import * as cors from 'fastify-cors';
import GQL from 'fastify-gql';
import * as helmet from 'fastify-helmet';
import * as rateLimiter from 'fastify-rate-limit';
import 'reflect-metadata';
import { createSchema } from './utils/mergeSchemas';
dotenv.config();
async function setupApp(): Promise<fastify.FastifyInstance> {
const schema = await createSchema();
const app = fastify();
app.register(helmet);
app.register(cors, {
credentials: true,
origin: process.env.CORS_ORIGIN,
});
app.register(rateLimiter, {
timeWindow: 15 * 60 * 1000,
max: 10000,
});
app.register(GQL, {
schema,
jit: 1,
context: ({ req }: any) => ({ req }),
});
return app;
};
function watchForErrors(app: any): void {
process.on('uncaughtException', error => {
const currentDate = new Date().toUTCString();
app.log.error(`${currentDate} - uncaughtException: `, error);
process.exit(1);
});
process.on('unhandledRejection', error => {
app.log.error('uncaughtRejection: ', error);
});
process.on('SIGINT', async () => {
try {
// await db.destroy();
process.exit(0);
} catch (err) {
process.exit(1);
}
});
}
(async function(): Promise<void> {
const app = await setupApp();
// await createConnection();
const PORT = Number(process.env.APP_PORT) || 4000;
app.listen({ port: PORT }, () => console.log(`🚀 Server ready at port 4000`));
watchForErrors(app);
})();
"start": "cross-env NODE_ENV=development nodemon --exec ts-node src/index.ts",
I also tried importing with require using const GQL = require('fastify-gql');
and when I try to access the /graphql
endpoint I get the error message Must provide Source. Received: undefined
Hey, everyone
Could I somehow provide graphql URI?
For example, I need to set up service on /
endpoint instead of /graphql
.
I had next code for apollo-server-hapi
library
await graphqlServer.applyMiddleware({ app: server, path: '/' });
I guess it can be a little bit simpler (for example, parameter path
in the constructor).
Hi there!
This is a very minor issue, but I've been puzzled as you can access both graphiql.html
and playground.html
as soon as you define graphiql
configuration key (as long as it is not falsy).
The reason is because the two files are served from the static folder:
https://github.com/mcollina/fastify-gql/blob/ca23bb6c22d88b021a4b4503cfae321895e5dc8d/lib/routes.js#L190-L205
So when graphiql
key is
true
or 'graphiql'
: you have access to /graphiql
and /playground.html
'playground'
: you have access to /graphiql.html
and /playground
This is not really an issue, more an improvement.
Hello @mcollina
I have configured graphql by :
// a function
authHook(instance);
instance.register(require('fastify-gql'), graphQlOptions);
done();
//
My GraphlQlSchema
const RootQuery = new GraphQLObjectType({
name: 'EmployeeLocation',
fields: {
employee: {
type: EmployeeType,
args: {
id: { type: GraphQLID }
},
resolve(parent, args) {
console.log('Entering Resolver'); // This prints two times even though I made single call
return Employee.findById(args.id);
}
});
module.exports = new GraphQLSchema({
query: RootQuery,
});
ISSUE
I have other mutations as well which are triggering two times even though I hit the api only one time
🚨 You need to enable Continuous Integration on Greenkeeper branches of this repository. 🚨
To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.
Since we didn’t receive a CI status on the greenkeeper/initial
branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.
If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/
.
Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.
Is there any way to use request inside resolver.
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.