@operato/graphql 2.0.0-alpha.0 → 2.0.0-alpha.110

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,21 +1,6 @@
1
- import { createUploadLink } from 'apollo-upload-client'
2
- import { createClient } from 'graphql-ws'
3
-
4
- import {
5
- ApolloClient,
6
- ApolloLink,
7
- DefaultOptions,
8
- from,
9
- HttpLink,
10
- HttpOptions,
11
- InMemoryCache,
12
- ServerParseError,
13
- split
14
- } from '@apollo/client/core'
15
- import { ErrorLink, onError } from '@apollo/client/link/error'
16
- import { GraphQLWsLink } from '@apollo/client/link/subscriptions'
17
- import { getMainDefinition } from '@apollo/client/utilities'
18
- import { activeRequestCounterLink, decreaseActiveRequestCounter } from './active-request-counter-link'
1
+ import { ApolloClient, DefaultOptions, InMemoryCache } from '@apollo/client/core'
2
+
3
+ import { getClientLink } from './graphql-env'
19
4
 
20
5
  export const GRAPHQL_URI = '/graphql'
21
6
  export const SUBSCRIPTION_URI = GRAPHQL_URI
@@ -34,85 +19,73 @@ const defaultOptions: DefaultOptions = {
34
19
  }
35
20
  }
36
21
 
37
- const ERROR_HANDLER: ErrorLink.ErrorHandler = ({ operation, graphQLErrors, networkError }) => {
38
- if (graphQLErrors) {
39
- document.dispatchEvent(
40
- new CustomEvent('notify', {
41
- detail: {
42
- level: 'error',
43
- message: graphQLErrors[0].message,
44
- ex: graphQLErrors
45
- }
46
- })
47
- )
48
- }
49
-
50
- if (networkError) {
51
- decreaseActiveRequestCounter()
52
-
53
- /* networkError가 ServerParseError 이거나 ServerError 인 경우에만 statusCode를 갖는다. */
54
- switch ((networkError as ServerParseError).statusCode) {
55
- case undefined /* in case this error is not a server side error */:
56
- document.dispatchEvent(
57
- new CustomEvent('notify', {
58
- detail: {
59
- level: 'error',
60
- message: networkError.message,
61
- ex: networkError
62
- }
63
- })
64
- )
65
- break
66
-
67
- case 401:
68
- /* 401 에러가 리턴되면, 인증이 필요하다는 메시지를 dispatch 한다. 이 auth 모듈 등에서 이 메시지를 받아서 signin 프로세스를 진행할 수 있다. */
69
- document.dispatchEvent(new CustomEvent('auth-required'))
70
- break
71
-
72
- case 403:
73
- /* 403 에러가 리턴되면, 도메인 정보가 필요하다는 메시지를 dispatch 한다. 이 auth 모듈 등에서 이 메시지를 받아서 domain-register 프로세스 등을 진행할 수 있다. */
74
- document.dispatchEvent(new CustomEvent('domain-required'))
75
- break
76
-
77
- default:
78
- var { name, response, statusCode, bodyText, message } = networkError as ServerParseError
79
- if (name == 'ServerParseError') {
80
- message = `[ ${statusCode || ''} : ${response.statusText} ] ${bodyText}`
81
- } else {
82
- /* in case this error is instanceof ServerError */
83
- message = `[ ${statusCode || ''} : ${response.statusText} ] ${message}`
84
- }
85
-
86
- document.dispatchEvent(
87
- new CustomEvent('notify', {
88
- detail: {
89
- level: 'error',
90
- message,
91
- ex: networkError
92
- }
93
- })
94
- )
95
- }
96
- }
97
- }
22
+ // const ERROR_HANDLER: ErrorLink.ErrorHandler = ({ operation, graphQLErrors, networkError }) => {
23
+ // if (graphQLErrors) {
24
+ // document.dispatchEvent(
25
+ // new CustomEvent('notify', {
26
+ // detail: {
27
+ // level: 'error',
28
+ // message: graphQLErrors[0].message,
29
+ // ex: graphQLErrors
30
+ // }
31
+ // })
32
+ // )
33
+ // }
34
+
35
+ // if (networkError) {
36
+ // decreaseActiveRequestCounter()
37
+
38
+ // /* networkError가 ServerParseError 이거나 ServerError 인 경우에만 statusCode를 갖는다. */
39
+ // switch ((networkError as ServerParseError).statusCode) {
40
+ // case undefined /* in case this error is not a server side error */:
41
+ // document.dispatchEvent(
42
+ // new CustomEvent('notify', {
43
+ // detail: {
44
+ // level: 'error',
45
+ // message: networkError.message,
46
+ // ex: networkError
47
+ // }
48
+ // })
49
+ // )
50
+ // break
51
+
52
+ // case 401:
53
+ // /* 401 에러가 리턴되면, 인증이 필요하다는 메시지를 dispatch 한다. 이 auth 모듈 등에서 이 메시지를 받아서 signin 프로세스를 진행할 수 있다. */
54
+ // document.dispatchEvent(new CustomEvent('auth-required'))
55
+ // break
56
+
57
+ // case 403:
58
+ // /* 403 에러가 리턴되면, 도메인 정보가 필요하다는 메시지를 dispatch 한다. 이 auth 모듈 등에서 이 메시지를 받아서 domain-register 프로세스 등을 진행할 수 있다. */
59
+ // document.dispatchEvent(new CustomEvent('domain-required'))
60
+ // break
61
+
62
+ // default:
63
+ // var { name, response, statusCode, bodyText, message } = networkError as ServerParseError
64
+ // if (name == 'ServerParseError') {
65
+ // message = `[ ${statusCode || ''} : ${response.statusText} ] ${bodyText}`
66
+ // } else {
67
+ // /* in case this error is instanceof ServerError */
68
+ // message = `[ ${statusCode || ''} : ${response.statusText} ] ${message}`
69
+ // }
70
+
71
+ // document.dispatchEvent(
72
+ // new CustomEvent('notify', {
73
+ // detail: {
74
+ // level: 'error',
75
+ // message,
76
+ // ex: networkError
77
+ // }
78
+ // })
79
+ // )
80
+ // }
81
+ // }
82
+ // }
98
83
 
99
84
  const cache = new InMemoryCache({
100
85
  addTypename: false
101
86
  // dataIdFromObject: object => object.key
102
87
  })
103
88
 
104
- const httpOptions: HttpOptions = {
105
- uri: GRAPHQL_URI,
106
- credentials: 'include',
107
- headers: { 'Apollo-Require-Preflight': 'true' }
108
- }
109
-
110
- const httpLink = ApolloLink.split(
111
- operation => operation.getContext().hasUpload,
112
- createUploadLink(httpOptions) as any,
113
- new HttpLink(httpOptions)
114
- )
115
-
116
89
  // const initPersistCache = async () => {
117
90
  // persistCache({
118
91
  // cache,
@@ -122,39 +95,40 @@ const httpLink = ApolloLink.split(
122
95
 
123
96
  // initPersistCache()
124
97
 
125
- const wsLink = new GraphQLWsLink(
126
- createClient({
127
- url: location.origin.replace(/^http/, 'ws') + SUBSCRIPTION_URI,
128
- keepAlive: 10_000,
129
- retryAttempts: 1_000_000,
130
- shouldRetry: e => true,
131
- connectionParams: {
132
- headers: {
133
- /*
134
- 특정 도메인의 데이타만 받고자 하는 경우에, referer 정보를 제공해서 서버에서 서브도메인 정보를 취득하도록 한다.
135
- referer: location.href
136
- 또는, 이미 서브도메인 정보를 알고 있다면,
137
- 'x-things-factory-domain': '[subdomain]'
138
- 을 보낼 수 있다.
139
- 관련 정보를 보내지 않는다면, 사용자가 권한을 가진 모든 도메인의 데이타를 수신하게 된다.
140
- */
141
- referer: location.href
142
- }
143
- }
144
- })
145
- )
98
+ // var mockedResponses: any = {}
99
+
100
+ // const createMockLink = () =>
101
+ // new ApolloLink((operation, forward) => {
102
+ // return new Observable(observer => {
103
+ // const operationName = operation.operationName
104
+
105
+ // if (mockedResponses[operationName]) {
106
+ // observer.next({
107
+ // data: mockedResponses[operationName]
108
+ // })
109
+ // } else {
110
+ // observer.error(new Error(`No mock response for operation ${operationName}`))
111
+ // }
112
+
113
+ // observer.complete()
114
+ // })
115
+ // })
116
+
117
+ // const link = process.env.STORYBOOK_ENV
118
+ // ? createMockLink()
119
+ // : split(
120
+ // ({ query }) => {
121
+ // const def = getMainDefinition(query)
122
+ // return def.kind === 'OperationDefinition' && def.operation === 'subscription'
123
+ // },
124
+ // wsLink,
125
+ // from([activeRequestCounterLink, onError(ERROR_HANDLER), httpLink])
126
+ // )
146
127
 
147
128
  export const client = new ApolloClient({
148
129
  defaultOptions,
149
130
  cache,
150
- link: split(
151
- ({ query }) => {
152
- const def = getMainDefinition(query)
153
- return def.kind === 'OperationDefinition' && def.operation === 'subscription'
154
- },
155
- wsLink,
156
- from([activeRequestCounterLink, onError(ERROR_HANDLER), httpLink])
157
- )
131
+ link: getClientLink()
158
132
  })
159
133
 
160
134
  export const subscribe = async (request: any, subscribe: any) => {
@@ -0,0 +1,145 @@
1
+ import createUploadLink from 'apollo-upload-client/createUploadLink.mjs'
2
+ import { createClient as createWebSocketClient } from 'graphql-ws'
3
+
4
+ import { ApolloLink, from, HttpLink, HttpOptions, Observable, ServerParseError, split } from '@apollo/client/core'
5
+ import { ErrorLink, onError } from '@apollo/client/link/error'
6
+ import { GraphQLWsLink } from '@apollo/client/link/subscriptions'
7
+ import { getMainDefinition } from '@apollo/client/utilities'
8
+ import { activeRequestCounterLink, decreaseActiveRequestCounter } from './active-request-counter-link'
9
+
10
+ export const GRAPHQL_URI = '/graphql'
11
+ export const SUBSCRIPTION_URI = GRAPHQL_URI
12
+
13
+ var apolloLink: ApolloLink
14
+
15
+ const httpOptions: HttpOptions = {
16
+ uri: GRAPHQL_URI,
17
+ credentials: 'include',
18
+ headers: { 'Apollo-Require-Preflight': 'true' }
19
+ }
20
+
21
+ const httpLink = ApolloLink.split(
22
+ operation => operation.getContext().hasUpload,
23
+ createUploadLink(httpOptions) as any,
24
+ new HttpLink(httpOptions)
25
+ )
26
+
27
+ const wsLink = new GraphQLWsLink(
28
+ createWebSocketClient({
29
+ url: location.origin.replace(/^http/, 'ws') + SUBSCRIPTION_URI,
30
+ keepAlive: 10_000,
31
+ retryAttempts: 1_000_000,
32
+ shouldRetry: e => true,
33
+ connectionParams: {
34
+ headers: {
35
+ /*
36
+ 특정 도메인의 데이타만 받고자 하는 경우에, referer 정보를 제공해서 서버에서 서브도메인 정보를 취득하도록 한다.
37
+ referer: location.href
38
+ 또는, 이미 서브도메인 정보를 알고 있다면,
39
+ 'x-things-factory-domain': '[subdomain]'
40
+ 을 보낼 수 있다.
41
+ 관련 정보를 보내지 않는다면, 사용자가 권한을 가진 모든 도메인의 데이타를 수신하게 된다.
42
+ */
43
+ referer: location.href
44
+ }
45
+ }
46
+ })
47
+ )
48
+
49
+ const ERROR_HANDLER: ErrorLink.ErrorHandler = ({ operation, graphQLErrors, networkError }) => {
50
+ if (graphQLErrors) {
51
+ document.dispatchEvent(
52
+ new CustomEvent('notify', {
53
+ detail: {
54
+ level: 'error',
55
+ message: graphQLErrors[0].message,
56
+ ex: graphQLErrors
57
+ }
58
+ })
59
+ )
60
+ }
61
+
62
+ if (networkError) {
63
+ decreaseActiveRequestCounter()
64
+
65
+ /* networkError가 ServerParseError 이거나 ServerError 인 경우에만 statusCode를 갖는다. */
66
+ switch ((networkError as ServerParseError).statusCode) {
67
+ case undefined /* in case this error is not a server side error */:
68
+ document.dispatchEvent(
69
+ new CustomEvent('notify', {
70
+ detail: {
71
+ level: 'error',
72
+ message: networkError.message,
73
+ ex: networkError
74
+ }
75
+ })
76
+ )
77
+ break
78
+
79
+ case 401:
80
+ /* 401 에러가 리턴되면, 인증이 필요하다는 메시지를 dispatch 한다. 이 auth 모듈 등에서 이 메시지를 받아서 signin 프로세스를 진행할 수 있다. */
81
+ document.dispatchEvent(new CustomEvent('auth-required'))
82
+ break
83
+
84
+ case 403:
85
+ /* 403 에러가 리턴되면, 도메인 정보가 필요하다는 메시지를 dispatch 한다. 이 auth 모듈 등에서 이 메시지를 받아서 domain-register 프로세스 등을 진행할 수 있다. */
86
+ document.dispatchEvent(new CustomEvent('domain-required'))
87
+ break
88
+
89
+ default:
90
+ var { name, response, statusCode, bodyText, message } = networkError as ServerParseError
91
+ if (name == 'ServerParseError') {
92
+ message = `[ ${statusCode || ''} : ${response.statusText} ] ${bodyText}`
93
+ } else {
94
+ /* in case this error is instanceof ServerError */
95
+ message = `[ ${statusCode || ''} : ${response.statusText} ] ${message}`
96
+ }
97
+
98
+ document.dispatchEvent(
99
+ new CustomEvent('notify', {
100
+ detail: {
101
+ level: 'error',
102
+ message,
103
+ ex: networkError
104
+ }
105
+ })
106
+ )
107
+ }
108
+ }
109
+ }
110
+
111
+ export const setClientLink = (link: ApolloLink) => {
112
+ apolloLink = link
113
+ }
114
+
115
+ export const getClientLink = () => {
116
+ if (!apolloLink) {
117
+ apolloLink = split(
118
+ ({ query }) => {
119
+ const def = getMainDefinition(query)
120
+ return def.kind === 'OperationDefinition' && def.operation === 'subscription'
121
+ },
122
+ wsLink,
123
+ from([activeRequestCounterLink, onError(ERROR_HANDLER), httpLink])
124
+ )
125
+ }
126
+
127
+ return apolloLink
128
+ }
129
+
130
+ export const createMockLink = (mockedResponses: any = {}) =>
131
+ new ApolloLink((operation, forward) => {
132
+ return new Observable(observer => {
133
+ const operationName = operation.operationName
134
+
135
+ if (mockedResponses[operationName]) {
136
+ observer.next({
137
+ data: mockedResponses[operationName]
138
+ })
139
+ } else {
140
+ observer.error(new Error(`No mock response for operation ${operationName}`))
141
+ }
142
+
143
+ observer.complete()
144
+ })
145
+ })
package/src/index.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export * from './gql-context'
2
2
  export * from './graphql-client'
3
3
  export * from './json-to-grqphql-query'
4
-
5
- export { setActiveRequestCounterCallback, resetActiveRequestCounterCallback } from './active-request-counter-link'
4
+ export * from './active-request-counter-link'
5
+ export * from './use-query'
@@ -0,0 +1,34 @@
1
+ import gql from 'graphql-tag'
2
+ import { useState, useEffect } from 'haunted'
3
+
4
+ import { client } from './graphql-client'
5
+
6
+ export function useQuery(query: string, variables: any = {}) {
7
+ const [data, setData] = useState(null)
8
+ const [loading, setLoading] = useState(true)
9
+ const [error, setError] = useState(null)
10
+
11
+ useEffect(() => {
12
+ const fetchData = async () => {
13
+ setLoading(true)
14
+
15
+ try {
16
+ const { data } = await client.query({
17
+ query: gql`
18
+ ${query}
19
+ `,
20
+ variables
21
+ })
22
+ setData(data)
23
+ } catch (error: any) {
24
+ setError(error)
25
+ }
26
+
27
+ setLoading(false)
28
+ }
29
+
30
+ fetchData()
31
+ }, [query, variables]) // 의존성 배열에 쿼리와 변수를 포함시켜 쿼리나 변수가 바뀔 때마다 쿼리를 다시 실행합니다.
32
+
33
+ return { data, loading, error }
34
+ }