Giter Site home page Giter Site logo

mercurius-js / mercurius Goto Github PK

View Code? Open in Web Editor NEW
2.3K 30.0 233.0 1.38 MB

Implement GraphQL servers and gateways with Fastify

Home Page: https://mercurius.dev/

License: MIT License

JavaScript 94.57% HTML 1.79% Shell 0.16% TypeScript 3.48%
gateway graphql nodejs fastify hacktoberfest federation

mercurius's People

Contributors

alcidesqueiroz avatar aldis-ameriks avatar andreialecu avatar blimmer avatar brainrepo avatar capaj avatar chemicalkosek avatar codeflyer avatar dependabot-preview[bot] avatar dependabot[bot] avatar drakhart avatar eomm avatar frikille avatar greenkeeper[bot] avatar iviaks avatar jemikanegara avatar jonnydgreen avatar leorossi avatar mcollina avatar pabloszx avatar pacodu avatar pscarey avatar psteinroe avatar rafaelgss avatar sameer-coder avatar simenb avatar simoneb avatar skellla avatar tomi-bigpi avatar wiktor-obrebski 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  avatar  avatar  avatar  avatar  avatar

mercurius's Issues

Action required: Greenkeeper could not be activated 🚨

🚨 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.

Proposal: fastify.graphql.setSchema() function

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.

type Query and Mutation are inconsistent

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.

https://github.com/mcollina/fastify-gql/blob/d5d79d4a62a03a9ac5d742fe90354b1c6070aef6/index.js#L52-L59

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.

Add typescript typings

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.

Making fastify-gql even faster

Introduction

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:

  • They will use only root resolvers (yes - No nested/relationship resolvers)
  • They will use info object with the client query to see what client realy wants (instead of blindly return everything)
  • All nested relationships can be executed using SQL joins etc. to reduce the number of calls to the database.
  • The final object can be shaped on the root resolver.

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

Problem with info

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.

https://gist.githubusercontent.com/the-vampiire/3d4875ef51c18c20fa3a53fd9307aa63/raw/c1679be181be09683ab5db4e2afa623a92963204/mapAttributes.js

I have experimented with this approach in https://github.com/graphql-heroes/graphql-backend-gen and it really works.

Got 500 error: Unexpected end of JSON input

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
}

File upload plugin

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.

Enrich context

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 }),
});

queryDepth being too strict

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:
image

Caching query results?

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? :)

Add graphql playground alongside with graphiql

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.

Unable to find 'main.js' on '/graphiql' page

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
  })

Fastify ecosystem ?

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 !

GQL Mutation - Receiving unexpected "[Object: null prototype]"

Sending payload in Mutation also returns this "[Object: null prototype]" as a reference key for the actual payload - seems to be a bug.

Error:
image

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.

Graphiql page isn't rendering

Just installed Fastify GQL and I can't seem to render the Graphiql interface / page on localhost.

  • Tried setting routes to true / false
  • Tried the example -- didn't work

Index.js
image

Browser:
image

Package.json:
image

Pretty basic stuff but can't seem to get it to work - maybe I'm missing something and I would appreciate the help.

Thanks!

File Upload

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!

An in-range update of @typescript-eslint/parser is breaking the build 🚨

The devDependency @typescript-eslint/parser was updated from 2.19.0 to 2.19.1.

🚨 View failing branch.

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.

Status Details

Release Notes for v2.19.1

2.19.1 (2020-02-10)

Bug Fixes

  • eslint-plugin: [unbound-method] blacklist a few unbound natives (#1562) (4670aab)
  • typescript-estree: ts returning wrong file with project references (#1575) (4c12dac)
Commits

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

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Using a sub-property

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.

Incorrect Graphql Error processing

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.

User inputs validation and serialization

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 ?

File upload?

Can anyone provide an example of how to upload file via GraphQL?

Proposal: Graphql Schema replacement

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?

Implementation

  fastifyGraphQl.replaceSchema = function (s) {
    if (!s || typeof s !== 'object') {
      throw new Error('Must provide valid Document AST')
    }

    schema = s
  }

An in-range update of autocannon is breaking the build 🚨

The devDependency autocannon was updated from 4.5.0 to 4.5.1.

🚨 View failing branch.

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.

Status Details

Release Notes for v4.5.1
  • do not include nyc output in the published package.
Commits

The new version differs by 2 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Error management issue on `/graphql` endpoint

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

Please add documentation

Dat your presentation at nodeconf. And want to use it instantly. So it would be Very helpful if you could Add some documentation.

An in-range update of fastify is breaking the build 🚨

The devDependency fastify was updated from 2.11.0 to 2.12.0.

🚨 View failing branch.

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.

Status Details

Release Notes for v2.12.0

📚 PR:

  • fix: skip serialization for json string (#1937)
  • Added fastify-casl to Community Plugins (#1977)
  • feature: added validation context to validation result (#1915)
  • ESM support (#1984)
  • fix: adjust hooks body null (#1991)
  • Added mcollina's plugin "fastify-secure-session" (#1999)
  • Add fastify-typeorm-plugin to community plugins (#1998)
  • Remove Azure Pipelines (#1985)
  • Update validation docs (#1994)
  • Drop Windows-latest and Node 6 from CI as its failing. (#2002)
  • doc: fix esm-support anchor (#2001)
  • Docs(Fluent-Schema.md): fix fluent schema repo link (#2007)
  • fix - docs - hooks - error handling (#2000)
  • add fastify-explorer to ecosystem (#2003)
  • Add a recommendations doc (#1997)
  • Fix TOC typo in recommendations (#2009)
  • docs(Typescript): typo (#2016)
  • docs: fix onResponse parameter (#2020)
  • Update template bug.md (#2025)
  • fix replace way enum (#2026)
  • docs: update inject features (#2029)
  • Update Copyright Year to 2020 (#2031)
  • add generic to typescript Reply.send payload (#2032)
  • Shorten longest line (docs) (#2035)
  • docs: OpenJS CoC (#2033)
  • Workaround for using one schema for multiple routes (#2044)
  • docs: inject chainable methods (#1917) (#2043)
  • http2: handle graceful close (#2050)
  • chore(package): update fluent-schema to version 0.10.0 (#2057)
  • chore(package): update yup to version 0.28.1 (#2059)
  • Update README.md (#2064)
  • Added fastify-response-validation to ecosystem (#2063)
  • fix: use opts of onRoute hook (#2060)
  • Fixed documentation typo (#2067)
  • Add missing TS definition for ServerOptions.genReqId function arg (#2076)
  • fix: throw hooks promise rejection (#2070) (#2074)
  • Add docs to stop processing hooks with async (#2079)
Commits

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

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Support for Automatic Persisted Queries

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:

An in-range update of @typescript-eslint/eslint-plugin is breaking the build 🚨

The devDependency @typescript-eslint/eslint-plugin was updated from 2.19.0 to 2.19.1.

🚨 View failing branch.

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.

Status Details

Release Notes for v2.19.1

2.19.1 (2020-02-10)

Bug Fixes

  • eslint-plugin: [unbound-method] blacklist a few unbound natives (#1562) (4670aab)
  • typescript-estree: ts returning wrong file with project references (#1575) (4c12dac)
Commits

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

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Error: plugin must be a function or a promise

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

Graphql URI

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).

graphiql & graphql-playground accessible simultaneously

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.

Query Running Multiple Times (Bug ?)

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

Action required: Greenkeeper could not be activated 🚨

🚨 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.

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.