Strapi v4: How to enable graphql playground in prod? - graphql

my-app.herokuapp.com/graphql responses with 'GET query missing.' and doesn't provide graphql playground interface.
Conf from https://docs.strapi.io/developer-docs/latest/plugins/graphql.html#configurations doesn't work for me.
./config/plugins.js
module.exports = ({ env }) => ({
//
graphql: {
config: {
endpoint: "/graphql",
shadowCRUD: true,
playgroundAlways: true,
depthLimit: 100,
apolloServer: {
tracing: false,
},
}
},
});
and this from forums too..
module.exports = ({ env }) => ({
//
graphql: {
endpoint: "/graphql",
shadowCRUD: true,
playgroundAlways: true,
depthLimit: 100,
apolloServer: {
tracing: false,
},
},
});
```

When I tried to query my GraphQL API on Heroku with Postman, at first it said "restricted access" or something like that. Then I realised that, unlike with MongoDB, when you deploy PostgreSQL on Heroku, the latter creates it's own database, different from the one created in dev environment
So, in prod, Strapi content-types are saved, but naturally some things are wiped, like the entries in collections and permissions settings. I had "find" and "findOne" checkboxes unchecked there, so I checked them back on. Prod API still shows "GET query missing", but the data appeared in Postman and the app worked as expected
If you have PostgreSQL deployed, check your Strapi settings (Settings -> Users & Permissions Plugin -> Roles -> Permissions -> name of your collection type) and see if the checkboxes are unchecked and try to check them back. That did the trick for me

This worked for me Strapi v.4 on Heroku with postgreSQL
config/plugins.js
module.exports = ({ env }) => ({
graphql: {
enabled: true,
config: {
endpoint: "/graphql",
shadowCRUD: true,
playgroundAlways: true,
defaultLimit: 10,
maxLimit: 20,
apolloServer: {
tracing: true,
},
},
},
});

Related

Set Cookies in apollo server azure functions

I am using apollo server in the azure function. I want to set cookies from apollo server azure functions. But it's not working. It doesn't throw any kind of errors.
How do I set cookies in apollo server azure functions? I tried this way but it's not working.
Here is my code
import { ApolloServer, gql } from "apollo-server-azure-functions";
import { ApolloServerPluginLandingPageLocalDefault } from "apollo-server-core";
import { serialize, parse } from "cookie";
// Construct a schema, using GraphQL schema language
const typeDefs = gql`
type Query {
user: User
}
type User {
id: ID!
name: String!
email: String!
}
`;
// Provide resolver functions for your schema fields
const resolvers = {
Query: {
user: (parents, args, { request, context }, info) => {
const cookie = serialize("token", "123", {
expires: new Date(Date.now() + 900000),
httpOnly: true,
});
context.res.setHeader("Set-Cookie", cookie);
return {
id: "1",
name: "John Doe",
email: "john#example.com",
};
},
},
};
// #ts-ignore
const server = new ApolloServer({
typeDefs,
resolvers,
debug: true,
plugins: [ApolloServerPluginLandingPageLocalDefault({ embed: true })],
context: (context) => {
return context;
},
});
export default server.createHandler({
cors: {
origin: ["*", "https://studio.apollographql.com"],
methods: ["GET", "POST", "OPTIONS"],
allowedHeaders: [
"access-control-allow-header",
"access-control-allow-credentials",
"access-control-allow-origin",
"content-type",
],
},
});
There is no documentation available for apollo server azure functions.
Official repository from apollo server azure functions: https://github.com/Azure-Samples/js-e2e-azure-function-graphql-hello.git
Sharing the discussion with the team internal and posting the update as updated here.
After looking at the issue, the infrastructure, and the announcement from Apollo for this package, I believe Apollo is the correct organization to post this issue because Apollo is providing the server in this sample. It just happens to be running on an Azure Function. Additionally, when I look for a solution on Apollo, it looks like the ApolloServer dependency needs to be swapped out for an Apollo server for express dependency in order to successfully set the cookie.
None of this is great news. I apologize for this.
I believe the sample works in this repo without cookes and doesn't currently include cookies in the code. Moving forward with the Apollo dependency, we will re-evaluate its use based on this feedback.

Which `apollo-server-express` Version Work Best For These Apollo Server Packages?

I’m trying to get apollo-server-lambda or apollo-server-express to work with an executable schema for v3.36.
Here are the packages we use:
apollo-server-express#3.36 or apollo-server-lambda#3+
graphql-constraint-directive#3.0.0
#graphql-tools/schema#7.1.3
I ran multiple regression test to make it work, and it does not seem to hit GraphQL.
Here’s my Apollo server config:
const apolloServer = new ApolloServer({
schema: initializeSchema(),
plugins: [
ApolloServerPluginLandingPageGraphQLPlayground(),
{
didEncounterErrors(errors) {
logger.info(`didEncounterErrors:`)
logger.info(errors)
},
async requestDidStart(requestContext) {
logger.info(`Request started! ${requestContext}`);
return {
async parsingDidStart(requestContext) {
logger.info(`Parsing started! ${requestContext}`);
},
async validationDidStart(requestContext) {
logger.info(`Validation started! ${requestContext}`);
}
}
},
}],
context: async ({ event, context, express }) => {
logger.info(`Loading event... ${JSON.stringify(event)}`)
const newContext = {
headers: event.headers,
functionName: context.functionName,
event,
context,
expressRequest: express.req,
user: {} ?? null,
}
logger.info(`context ${JSON.stringify(newContext)}`)
return newContext
},
dataSources: () => {
logger.info('!initializing datasource')
initializeDbConnection()
return {}
},
...(['staging', 'production', 'demo'].includes(process.env.stage as string)
? { introspection: false, playground: false }
: {}),
})
I was able to log the executable schema inside initializeSchema, but it does not seem to hit the GraphQL Typedef and Resolver after upgrading. It just goes straight to context. So, I'm kinda stumped how to make HTTP request hit the Typedef and Resolvers using makeExecutableSchema()
I just need some advise or a list of table that could help me which version works best with the given apollo-server-<server_version>.

How to configure proxy in Vite?

I was trying to follow the docs and created vite.config.js like this:
const config = {
outDir: '../wwwroot/',
proxy: {
// string shorthand
'/foo': 'http://localhost:4567',
// with options
'/api': {
target: 'http://jsonplaceholder.typicode.com',
changeOrigin: true,
rewrite: path => path.replace(/^\/api/, '')
}
}
};
export default config;
And tried to test it with following calls:
fetch('/foo');
fetch('/api/test/get');
I was expecting to have actual requests as http://localhost:4567/foo and http://jsonplaceholder.typicode.com/test/get
But both of them had my dev server as an origin like this: http://localhost:3000/foo and http://localhost:3000/api/test/get
Did I misunderstand it? How proxies should work?
I also created an issue in the Vite repo but it was closed and I did not understand the closing comment.
Turns out it's needed to specify secure flag to false like this:
proxy: {
'/api': {
target: 'https://localhost:44305',
changeOrigin: true,
secure: false,
ws: true,
}
}
Related github issue
Based on the Vite Config you need to specify it via server -> proxy inside vite.config.js:
export default defineConfig({
server: {
proxy: {
"/api": {
target: "https://your-remote-domain.com",
changeOrigin: true,
secure: false,
},
},
},
// some other configuration
})
For debugging I highly recommend to add event listeners to the proxy, so you can see how the requests are transformed, if they hit the target server, and what is returned.
proxy: {
'/api': {
target: 'https://localhost:44305',
changeOrigin: true,
secure: false,
ws: true,
configure: (proxy, _options) => {
proxy.on('error', (err, _req, _res) => {
console.log('proxy error', err);
});
proxy.on('proxyReq', (proxyReq, req, _res) => {
console.log('Sending Request to the Target:', req.method, req.url);
});
proxy.on('proxyRes', (proxyRes, req, _res) => {
console.log('Received Response from the Target:', proxyRes.statusCode, req.url);
});
},
}
}
proxy will be an instance of 'http-proxy',
Please see for further info https://github.com/http-party/node-http-proxy#options

nuxt.js + Apollo Client: How to disable cache?

I managed to get an nuxt.js + nest.js with typescript and apollo graphql running.
To test if graphql works, i used the files from this example, and added a Button to the nuxt.js-page (on:click -> load all cats via graphql).
Everything works, reading and writing.
The problem is that after doing a mutation via playground or restarting the nest.js server with other graphql-data, the nuxt.js-page is displaying the old data(on click). I have to reload the whole page in the browser, to get the Apollo-Client fetching the new data.
I've tried to add a 'no-cache'-flag and 'network-only'-flag to nuxt.config.ts without success:
apollo: {
defaultOptions: {
$query: {
loadingKey: 'loading',
fetchPolicy: 'no-cache'
}
},
clientConfigs: {
default: {
httpEndpoint: 'http://localhost:4000/graphql',
wsEndpoint: 'ws://localhost:4000/graphql'
}
}
}
The function to get the cats:
private getCats() {
this.$apollo.query({ query: GET_CATS_QUERY }).then((res:any) => {
alert(JSON.stringify(res.data, null, 0));
});
}
How can I disable the cache or is there an other solution?
I had a similar problem recently and managed to fix it by creating a Nuxt plugin which overrides default client's options:
// plugins/apollo-overrides.ts
import { Plugin } from '#nuxt/types';
const apolloOverrides: Plugin = ({ app }) => {
// disable caching on all the queries
app.apolloProvider.defaultClient.defaultOptions = {
query: {
fetchPolicy: 'no-cache',
},
};
};
export default apolloOverrides;
Don't forget to register it in Nuxt's config:
// nuxt.config.js
export default {
...
plugins: [
'~/plugins/apollo-overrides',
],
...
};
I had problem like this you can fix it easily with remove $ before query
defaultOptions: {
query: {
fetchPolicy: 'no-cache',
errorPolicy: 'all'
}
},
And Reopen your dev server
If this solution not working add fetch policy for each query
.query({
query: sample,
variables: {},
errorPolicy: "all",
fetchPolicy: "no-cache"
})

Proxy only POST requests (or any other HTTP method) through Webpack Dev Server?

Is there any way to only allow POST requests to be proxied using Webpack Dev Server? My app uses /login for GET requests and unfortunately it is being proxied to my other host regardless of HTTP method.
// Serve the Relay app
const compiler = webpack(config);
appServer = new WebpackDevServer(compiler, {
contentBase: '/public/',
proxy: {
'/login': `http://localhost:${GRAPHQL_PORT}`, // only for POST?
},
publicPath: '/js/',
stats: {
colors: true,
chunks: false,
},
historyApiFallback: true
});
Yes, there is. You can use bypass parameter.
// Serve the Relay app
const compiler = webpack(config);
appServer = new WebpackDevServer(compiler, {
contentBase: '/public/',
proxy: {
'/login': {
target: `http://localhost:${GRAPHQL_PORT}`, // only for POST?
bypass: function(req, res, proxyOptions) {
if(req.method != 'POST') return false;
}
}
},
publicPath: '/js/',
stats: {
colors: true,
chunks: false,
},
historyApiFallback: true
});
documentation Webpack 1
documentation Webpack 2

Resources