-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapollo.js
91 lines (71 loc) · 2.32 KB
/
apollo.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* Used for creating an apollo client connected to a Phoenix web application backend.
*/
import { ApolloClient, HttpLink, InMemoryCache, ApolloLink } from 'apollo-boost'
import { Socket as PhoenixSocket } from 'phoenix'
import * as AbsintheSocket from '@absinthe/socket'
import { createAbsintheSocketLink } from '@absinthe/socket-apollo-link'
import { split } from 'apollo-link'
import { hasSubscription } from '@jumpn/utils-graphql'
import camelcaseKeys from "camelcase-keys"
const getHostname = ({ host, forceProd }) => {
if (forceProd) return host
const hostname = window.location.hostname
let isDev = hostname.indexOf('localhost') > -1
if (hostname.indexOf('192.168') > -1) {
isDev = true
}
if (isDev) {
host = `http://${hostname}:4000`
}
return host
}
const getSocketHost = (params) => {
return getHostname(params).replace('http', 'ws')
}
export const createClient = ({ host = '', token = '', forceProd = false }) => {
const hostname = getHostname({ host, forceProd })
const socketHost = getSocketHost({ host, forceProd })
const httpLink = new HttpLink({
uri: hostname + '/graphql'
})
const authLink = new ApolloLink((operation, forward) => {
operation.setContext({
headers: {
authorization: `Bearer ${token}`
}
})
return forward(operation)
})
const authHttpLink = authLink.concat(httpLink)
const phoenixSocket = new PhoenixSocket(socketHost + '/socket', {
params: () => {
return !!token ? { token } : {}
}
})
const absintheSocket = AbsintheSocket.create(phoenixSocket)
const websocketLink = createAbsintheSocketLink(absintheSocket)
const link = split(
operation => hasSubscription(operation.query),
websocketLink,
authHttpLink
)
const cache = new InMemoryCache()
const client = new ApolloClient({ link, cache })
return client
}
/**
* Maps the GraphQL response from `useMutation` to an error object.
* This expects the server to implement the Elixir.Absinthe.HandleChangesetErrors
* @param {Object} errors
* @return {Object}
*/
export const mapErrors = (errors) => {
const { graphQLErrors } = errors
if (!graphQLErrors) return errors
errors = graphQLErrors.reduce((prev, { message }) => {
const [key, value] = message.split(": ")
return { ...prev, [key]: value }
}, {})
return camelcaseKeys(errors)
}