Skip to content

Instantly share code, notes, and snippets.

@wickedev
Last active November 18, 2023 22:46
Show Gist options
  • Save wickedev/8dfbc026e2142a5e82810a2d7a7156a9 to your computer and use it in GitHub Desktop.
Save wickedev/8dfbc026e2142a5e82810a2d7a7156a9 to your computer and use it in GitHub Desktop.
GraphQL(apollo) relative path setup
import { ApolloClient, ApolloLink, HttpLink, InMemoryCache, split } from '@apollo/client'
import { WebSocketLink } from '@apollo/client/link/ws'
const httpLink = new HttpLink({
uri: '/graphql',
})
const wsLink = new WebSocketLink({
uri: `${getWebsocketURI()}/subscriptions`,
options: {
reconnect: true,
lazy: true,
},
})
const networkLink = split(
({ query }) => {
const definition = getMainDefinition(query)
return definition.kind === 'OperationDefinition' && definition.operation === 'subscription'
}, // test function
wsLink, // use when test return true
httpLink // use when test return false
)
const links = ApolloLink.from([networkLink])
export const client = new ApolloClient({
links,
cache: new InMemoryCache({}),
})
function getWebsocketURI() {
const location = window.location
const protocol = location.protocol === 'http:' ? 'ws:' : 'wss:'
return protocol + '//' + location.hostname + (location.port ? ':' + location.port : '')
}
server {
set $backend FILL_YOUR_DOMAIN_OR_IP:PORT;
listen 80;
server_name _;
root /var/www/;
index index.html;
location /graphql {
rewrite /graphql/(.*) /$1 break;
proxy_pass http://$backend/graphql;
}
location /subscriptions {
rewrite /subscriptions/(.*) /$1 break;
proxy_pass http://$backend/subscriptions;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host $host;
proxy_set_header Origin \"\";
}
# Force all paths to load either itself (js files) or go through index.html.
location / {
try_files $uri /index.html;
add_header Cache-Control "private, no-cache, no-store, must-revalidate";
}
}
// noinspection HttpUrlsUsage
const { createProxyMiddleware: proxy } = require('http-proxy-middleware')
// Write REMOTE_SERVER=FILL_YOUR_DOMAIN_OR_IP:PORT on your .env file
const REMOTE_SERVER = process.env.REMOTE_SERVER || 'localhost:8080'
module.exports = function (app) {
app.use(
proxy('/graphql', {
target: `http://${REMOTE_SERVER}`,
changeOrigin: true,
autoRewrite: true,
})
)
app.use(
proxy('/subscriptions', {
target: `ws://${REMOTE_SERVER}`,
ws: true,
})
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment