I am trying to follow the apollo client installation instructions.
I'm copying exactly what they are doing into my project, but whenever I call client.query, I get a 400 status code with the following error:
Error: Schema must be an instance of GraphQLSchema. Also ensure that there are not multiple versions of GraphQL installed in your node_modules directory.
This is all the code in my project's index.js:
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import gql from 'graphql-tag';
const client = new ApolloClient({
link: new HttpLink({ uri: 'https://q80vw8qjp.lp.gql.zone/graphql' }),
cache: new InMemoryCache()
});
client.query({ query: gql`{ hello }` }).then(console.log);
I've configured my babelrc file with the following option per the instructions in apollo's documentation:
{
"presets": ["env", "react"],
"plugins": [
"graphql-tag"
]
}
My project is just a basic webpack configuration with react. I've tried de-duping my npm packages, and checked if there are conflicting versions of graphql in my project but had no success. My best guess is that graphql-tag isn't working correctly and my query isn't being translated into the appropriate syntax for the request. It feels like I am missing something very basic. I would greatly appreciate any clarification. Thanks!
This doesn't look like an issue with your client config so much as a bug with Launchpad. If you access the GraphiQL interface for that endpoint and attempt to run a query, it'll throw the same error.
If you log into Launchpad with your Github account, you can start a new pad (which will be identical to that one), save it and then use that url in your project instead.
Related
I'm trying to figure out how to open the apollo studio for my next js app.
When I run the local host, I get a message that says:
Server started at http://localhost:5555/graphql
When I click that link, I get a page that says:
GET query missing.
I'm trying to find a way to get to the apollo studio explorer.
For others looking (or maybe for myself the next time I forget), the address: http://localhost:5555/graphql gets inserted in the sandbox address bar, that you find at the url: https://studio.apollographql.com/sandbox/explorer. It won't work if you put the local host address in the url bar
I faced the same issue and have managed to solve it by connecting to apollo studio as a deployed graph (not using the sandbox) but running locally.
Firstly I followed this tutorial https://master--apollo-docs-index.netlify.app/docs/tutorial/production/ which does not use NextJS but it does connect a react app to the apollo studio sandbox then by section 5 it connects the deployed graph to apollo studio. Unfortunately section 5 is quite outdated so i will try to fill in the blanks and get you up and running.
After you have set up an account in apollo studio add a new graph (+ New Graph button). Use whatever architecture you like but I tried this using 'supergraph'.
On the next page ('Publish your schema using Federation') I used the 'schema document' tab and pipeline: 'Federation 2 Supergraph'.This generates the 2 of the 3 env keys you need to add to your local env file and feed it into your app. keys as follows:
APOLLO_KEY - this starts 'service:' and ends before the space, it is a single line about 50 characters long.
APOLLO_GRAPH_REF - this can be found at the end of the line below the APOLLO_KEY. it is a single word with a '#' symbol in the middle.
APOLLO_SCHEMA_REPORTING=true - written as shown here.
Do not close the 'Publish your schema using Federation' page/ re-open it if you have closed it as it will indicate that you have successful connected the graph when you run the app locally after the next step.
Start the app locally using the CLI and in the browser request a page that queries the apollo server.
Watch the CLI as the page is served and you should see the comment 'Apollo usage reporting starting!', also the 'Publish your schema using Federation' page should confirm the graph has been connected. Now you can use all the features of the sandbox as well as monitoring etc.
Hope this helps.
The reason why Next.js doesn't allow you to connect to Apollo Studio is because Next.js does not allow CORS by default in api handlers.
Apollo Studio tries to send a request from its own domain and it's blocked by Next.js default setup.
Let's assume you have your graphql/Apollo server in your NextJs app at /api/graphql path. When you navigate to that path (from your local) by using http://localhost:3000/api/graphql it will show you the welcome page and allow you to access Apollo Sandbox.
Once you enter the Apollo Sandbox in the bottom right corner it will display this message:
When you run the diagnose problem on your local you'll see the following message:
$ npx diagnose-endpoint#1.1.0 --endpoint=http://localhost:3000/api/graphql
Diagnosing http://localhost:3000/api/graphql
⚠️ OPTIONS response is missing header 'access-control-allow-methods: POST'
⚠️ POST response missing 'access-control-allow-origin' header.
If using cookie-based authentication, the following headers are required from your endpoint:
access-control-allow-origin: https://studio.apollographql.com
access-control-allow-credentials: true
Otherwise, a wildcard value would work:
access-control-allow-origin: *
(📫 Interested in previewing a local tunnel to bypass CORS requirements? Please let us know at https://docs.google.com/forms/d/e/1FAIpQLScUCi3PdMerraiy6GpD-QiC_9KEKVHr4oDL5Vef5fIvzqqQWg/viewform )
The solution for the problem looks like this:
import type { NextApiRequest, NextApiResponse } from "next";
import Cors from "cors";
import { server } from "../../apollo";
// Initializing the cors middleware
// You can read here: https://github.com/expressjs/cors#configuration-options
const cors = Cors({
methods: ["POST"],
});
// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
function runMiddleware(
req: NextApiRequest,
res: NextApiResponse,
fn: Function
) {
return new Promise((resolve, reject) => {
fn(req, res, (result: any) => {
if (result instanceof Error) {
return reject(result);
}
return resolve(result);
});
});
}
export const config = {
api: {
bodyParser: false,
},
};
const startServer = server.start();
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
// Run cors middleware (to allow Apollo Studio access)
await runMiddleware(req, res, cors);
// run apollo server
await startServer;
await server.createHandler({ path: "/api/graphql" })(req, res);
}
It combines using the Apollo server and this CORS example
the import:
import { server } from "../../apollo"
from the example above is the apollo server that looks like this:
import { ApolloServer } from "apollo-server-micro";
import { typeDefs } from "./schema";
import { resolvers } from "./resolvers";
export const server = new ApolloServer({
typeDefs,
resolvers,
});
You can also use alternative options like embedding sandbox into your app but I'm finding the above solution a bit easier for my current needs so hope it helps you as well.
I'd like to render GraphQL Playground as a React component in one of my pages but it fails due to missing file-loader in webpack. Is there a way to fix this in docs or do I need to create new plugin with new webpack config?
Is it good idea to integrate Playground and Docusaurus at all?
Thanks for your ideas...
A few Docusaurus sites have embedded playgrounds:
Hermes
Uniforms
In your case you will have to write a plugin to extend the webpack config with file-loader.
Not sure if you found a better way but check out: https://www.npmjs.com/package/graphql-playground-react
You can embed this react component directly in your react app - It looks like Apollo also uses the vanilla JS version of this
I just had exactly the same problem. Basically, Docusaurus with a gQL Playground Integration runs fine in local but won't compile due to errors when running yarn build as above.
In the end I found the answer is in Docusaurus, not in building a custom compiler:
I switched from using graphql-react-playground to GraphiQL: package: "graphiql": "^1.8.7"
This moved my error on to a weird one with no references anywhere on the web (rare for me): "no valid fetcher implementation available"
I fixed the above by importing createGraphiQLFetcher from '#graphiql/create-fetcher' to my component
Then the error was around not being able to find a window component, this was an easy one, I followed docusaurus docs here: https://docusaurus.io/docs/docusaurus-core#browseronly and wrapped my component on this page in like this:
import BrowserOnly from '#docusaurus/BrowserOnly';
const Explorer = () => {
const { siteConfig } = useDocusaurusContext();
return (
<BrowserOnly fallback={Loading...}>
{() => {
const GraphEx = GraphExplorer
return
}}
);
}
This now works and builds successfully
I'm trying to test a component that imports a .gql file. When I try to build the component in a Jest file, I receive this error:
( object. anonymous function(module exports require __dirname __filename global jest) {
query getUser {
ˆˆˆˆˆˆˆ
<script>
import GET_USER from 'PATH';
ˆ
Does anyone have any idea of how to ignore the import? Because I don't need to test the GraphQL call.
GraphQL documents (which typically have a .gql extension) can be imported directly if you use webpack and utilize the loader that comes with graphql-tag. Jest does not work with webpack out of the box and needs to be configured to handle any imports of asset files like stylesheets, images, etc. This process is outlined in the docs.
According to the graphql-tag documentation:
Testing environments that don't support Webpack require additional configuration. For Jest use jest-transform-graphql.
So you can utilize jest-transform-graphql along with the babel-jest plugin, which you're probably already using:
"jest": {
"transform": {
"\\.(gql|graphql)$": "jest-transform-graphql",
".*": "babel-jest"
}
}
Mocking the file is technically possible by adding the moduleNameMapper config option as shown in the docs, however, doing so is likely to break your components.
I am trying to understand the Apollo client in an Angular client. The following code gives me no typings:
fireMutation() {
this.apollo.mutate<{foo: string}>({
mutation: gql`some mutation {}`,
variables: {}
}).subscribe(v => {
// No typings on v.
return;
});
}
I found this issue on Github, but it's apparently not related to the issue I'm facing.
I have created a Stackblitz here, to make it easy for you to confirm.
Based on this Github comment, I found the solution.
The fix was to install graphql types: npm i #types/graphql --save-dev.
I updated the stackblitz, and it now works 🔥
Many thanks to ekron.
I want to use the Login component provided by the ra-ui-materialui inside the next version of admin-on-rest.
I tried
import { Login } from 'ra-ui-materialui'
import { Login } from 'react-admin/ra-ui-materialui'
import { Login } from 'react-admin/ra-ui-materialui/auth'
import { Login } from 'react-admin/packages/ra-ui-materialui/src/auth'
import Login from 'react-admin/packages/ra-ui-materialui/src/auth'
They all resulted into an compile error:
Module not found: Can't resolve 'ra-ui-materialui' in '/my-app/src'
or
Module not found: Can't resolve 'react-admin/ra-ui-materialui' in '/my-app/src'
etc.
How can I import the provided Login component and use it in my react-admin app?
PS: For the time being, I've added the admin-on-rest tag too as this is the first question that concerns react-admin. For the purpose of this question and maybe many more to come, I created the tag react-admin.
I assumed that the local packages of react-admin would be available automatically just by the earlier installation of react-admin that I did. I was wrong. You need to yarn add that separately.
So, next to:
yarn add react-admin
You also need to:
yarn add ra-ui-materialui
And then this works:
import { Login } from 'ra-ui-materialui'