@ludo.ninja/api 2.8.58 → 2.8.59

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.
@@ -24,92 +24,60 @@ const resolvePendingRequests = () => {
24
24
  pendingRequests = [];
25
25
  };
26
26
  let apolloClient;
27
+ const handleTokenRefresh = (operation, forward) => {
28
+ const { refreshToken } = (0, cookies_1.getCookies)();
29
+ const client = apolloClient ?? createApolloClient();
30
+ if (!isRefreshing) {
31
+ isRefreshing = true;
32
+ return (0, client_1.fromPromise)(client
33
+ .mutate({
34
+ context: { uri: index_1.hosts.authHost },
35
+ variables: { refreshToken },
36
+ mutation: index_1.authSchema.RefreshTokenDocument,
37
+ })
38
+ .then(({ data: { refreshToken: { tokenAuth, tokenRefresh } } }) => {
39
+ (0, cookies_1.refreshCookies)(tokenAuth, tokenRefresh, mainDomain);
40
+ resolvePendingRequests();
41
+ return true;
42
+ })
43
+ .catch(async () => {
44
+ await apolloClient?.mutate({
45
+ context: { uri: index_1.hosts.authHost },
46
+ mutation: index_1.authSchema.RevokeTokenDocument,
47
+ });
48
+ (0, cookies_1.destroyCookies)(mainDomain);
49
+ pendingRequests = [];
50
+ window.location.reload();
51
+ return false;
52
+ })
53
+ .finally(() => {
54
+ isRefreshing = false;
55
+ })).filter((value) => Boolean(value));
56
+ }
57
+ else {
58
+ return (0, client_1.fromPromise)(new Promise((resolve) => {
59
+ // @ts-ignore
60
+ pendingRequests.push(() => resolve());
61
+ }));
62
+ }
63
+ };
27
64
  const errorLink = (0, error_1.onError)(({ graphQLErrors, networkError, operation, forward }) => {
28
- const { authToken, refreshToken } = (0, cookies_1.getCookies)();
65
+ const { authToken } = (0, cookies_1.getCookies)();
29
66
  if (graphQLErrors) {
30
67
  graphQLErrors.forEach(({ message, locations, path }) => console.warn(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`));
31
68
  for (const err of graphQLErrors) {
32
69
  if (err.message.includes("Auth token not found") && authToken) {
33
- let forward$;
34
- const client = apolloClient ?? createApolloClient();
35
- if (!isRefreshing) {
36
- isRefreshing = true;
37
- forward$ = (0, client_1.fromPromise)(client
38
- .mutate({
39
- context: { uri: index_1.hosts.authHost },
40
- variables: { refreshToken },
41
- mutation: index_1.authSchema.RefreshTokenDocument,
42
- })
43
- .then(({ data: { refreshToken: { tokenAuth, tokenRefresh }, }, }) => {
44
- (0, cookies_1.refreshCookies)(tokenAuth, tokenRefresh, mainDomain);
45
- resolvePendingRequests();
46
- return true;
47
- })
48
- .catch(async () => {
49
- await apolloClient?.mutate({
50
- context: { uri: index_1.hosts.authHost },
51
- mutation: index_1.authSchema.RevokeTokenDocument,
52
- });
53
- (0, cookies_1.destroyCookies)(mainDomain);
54
- pendingRequests = [];
55
- window.location.reload();
56
- return false;
57
- })
58
- .finally(() => {
59
- isRefreshing = false;
60
- })).filter((value) => Boolean(value));
61
- }
62
- else {
63
- forward$ = (0, client_1.fromPromise)(new Promise((resolve) => {
64
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
65
- // @ts-ignore
66
- pendingRequests.push(() => resolve());
67
- }));
68
- }
69
- return forward$.flatMap(() => forward(operation));
70
+ return handleTokenRefresh(operation, forward).flatMap(() => forward(operation));
70
71
  }
71
72
  }
72
73
  }
73
74
  if (networkError) {
74
75
  console.warn(`[Network error]: ${networkError}`);
76
+ if (networkError.message.includes("503")) {
77
+ console.error(`[503 Service Unavailable]: ${networkError.message}`);
78
+ }
75
79
  if (networkError.message.includes("401") && authToken) {
76
- let forward$;
77
- const client = apolloClient ?? createApolloClient();
78
- if (!isRefreshing) {
79
- isRefreshing = true;
80
- forward$ = (0, client_1.fromPromise)(client
81
- .mutate({
82
- context: { uri: index_1.hosts.authHost },
83
- variables: { refreshToken },
84
- mutation: index_1.authSchema.RefreshTokenDocument,
85
- })
86
- .then(({ data: { refreshToken: { tokenAuth, tokenRefresh }, }, }) => {
87
- (0, cookies_1.refreshCookies)(tokenAuth, tokenRefresh, mainDomain);
88
- resolvePendingRequests();
89
- return true;
90
- })
91
- .catch(async () => {
92
- await apolloClient?.mutate({
93
- context: { uri: index_1.hosts.authHost },
94
- mutation: index_1.authSchema.RevokeTokenDocument,
95
- });
96
- (0, cookies_1.destroyCookies)(mainDomain);
97
- pendingRequests = [];
98
- window.location.reload();
99
- return false;
100
- })
101
- .finally(() => {
102
- isRefreshing = false;
103
- })).filter((value) => Boolean(value));
104
- }
105
- else {
106
- forward$ = (0, client_1.fromPromise)(new Promise((resolve) => {
107
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
108
- // @ts-ignore
109
- pendingRequests.push(() => resolve());
110
- }));
111
- }
112
- return forward$.flatMap(() => forward(operation));
80
+ return handleTokenRefresh(operation, forward).flatMap(() => forward(operation));
113
81
  }
114
82
  }
115
83
  });
@@ -158,26 +126,18 @@ function createApolloClient() {
158
126
  function initializeApollo(initialState = null, domain) {
159
127
  const _apolloClient = apolloClient ?? createApolloClient();
160
128
  mainDomain = domain || '';
161
- // If your page has Next.js data fetching methods that use Apollo Client, the initial state
162
- // gets hydrated here
163
129
  if (initialState) {
164
- // Get existing cache, loaded during client side data fetching
165
130
  const existingCache = _apolloClient.extract();
166
- // Merge the initialState from getStaticProps/getServerSideProps in the existing cache
167
131
  const data = (0, deepmerge_1.default)(existingCache, initialState, {
168
- // combine arrays using object equality (like in sets)
169
132
  arrayMerge: (destinationArray, sourceArray) => [
170
133
  ...sourceArray,
171
134
  ...destinationArray.filter((d) => sourceArray.every((s) => !(0, lodash_isequal_1.default)(d, s))),
172
135
  ],
173
136
  });
174
- // Restore the cache with the merged data
175
137
  _apolloClient.cache.restore(data);
176
138
  }
177
- // For SSG and SSR always create a new Apollo Client
178
139
  if (typeof window === "undefined")
179
140
  return _apolloClient;
180
- // Create the Apollo Client once in the client
181
141
  if (!apolloClient)
182
142
  apolloClient = _apolloClient;
183
143
  return _apolloClient;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ludo.ninja/api",
3
- "version": "2.8.58",
3
+ "version": "2.8.59",
4
4
  "main": "./build/index.js",
5
5
  "scripts": {
6
6
  "test": "jest",
@@ -7,17 +7,17 @@ import {
7
7
  split,
8
8
  ApolloLink,
9
9
  } from "@apollo/client";
10
- import {onError} from "@apollo/client/link/error";
11
- import {setContext} from "@apollo/client/link/context";
12
- import {createUploadLink} from "apollo-upload-client";
10
+ import { onError } from "@apollo/client/link/error";
11
+ import { setContext } from "@apollo/client/link/context";
12
+ import { createUploadLink } from "apollo-upload-client";
13
13
  import merge from "deepmerge";
14
14
  import isEqual from "lodash.isequal";
15
- import {destroyCookies, getCookies, refreshCookies} from "../cookies";
16
- import {typePoliciesPortal} from "./typePolicies";
17
- import {GraphQLWsLink} from "@apollo/client/link/subscriptions";
18
- import {getMainDefinition} from "@apollo/client/utilities";
19
- import {createClient} from "graphql-ws";
20
- import {hosts, authSchema as schema} from "../index";
15
+ import { destroyCookies, getCookies, refreshCookies } from "../cookies";
16
+ import { typePoliciesPortal } from "./typePolicies";
17
+ import { GraphQLWsLink } from "@apollo/client/link/subscriptions";
18
+ import { getMainDefinition } from "@apollo/client/utilities";
19
+ import { createClient } from "graphql-ws";
20
+ import { hosts, authSchema as schema } from "../index";
21
21
 
22
22
  let isRefreshing = false;
23
23
  let pendingRequests: never[] = [];
@@ -30,63 +30,59 @@ const resolvePendingRequests = () => {
30
30
 
31
31
  let apolloClient: ApolloClient<NormalizedCacheObject> | undefined;
32
32
 
33
- const errorLink = onError(({graphQLErrors, networkError, operation, forward}) => {
34
- const {authToken, refreshToken} = getCookies();
33
+ const handleTokenRefresh = (operation: any, forward: any) => {
34
+ const { refreshToken } = getCookies();
35
+ const client = apolloClient ?? createApolloClient();
36
+
37
+ if (!isRefreshing) {
38
+ isRefreshing = true;
39
+ return fromPromise(
40
+ client
41
+ .mutate({
42
+ context: { uri: hosts.authHost },
43
+ variables: { refreshToken },
44
+ mutation: schema.RefreshTokenDocument,
45
+ })
46
+ .then(({ data: { refreshToken: { tokenAuth, tokenRefresh } } }) => {
47
+ refreshCookies(tokenAuth, tokenRefresh, mainDomain);
48
+ resolvePendingRequests();
49
+ return true;
50
+ })
51
+ .catch(async () => {
52
+ await apolloClient?.mutate({
53
+ context: { uri: hosts.authHost },
54
+ mutation: schema.RevokeTokenDocument,
55
+ });
56
+ destroyCookies(mainDomain);
57
+ pendingRequests = [];
58
+ window.location.reload();
59
+ return false;
60
+ })
61
+ .finally(() => {
62
+ isRefreshing = false;
63
+ })
64
+ ).filter((value) => Boolean(value));
65
+ } else {
66
+ return fromPromise(
67
+ new Promise((resolve) => {
68
+ // @ts-ignore
69
+ pendingRequests.push(() => resolve());
70
+ })
71
+ );
72
+ }
73
+ };
74
+
75
+ const errorLink = onError(({ graphQLErrors, networkError, operation, forward }) => {
76
+ const { authToken } = getCookies();
35
77
 
36
78
  if (graphQLErrors) {
37
- graphQLErrors.forEach(({message, locations, path}) =>
38
- console.warn(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`),
79
+ graphQLErrors.forEach(({ message, locations, path }) =>
80
+ console.warn(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`)
39
81
  );
40
82
 
41
83
  for (const err of graphQLErrors) {
42
84
  if (err.message.includes("Auth token not found") && authToken) {
43
- let forward$;
44
- const client = apolloClient ?? createApolloClient();
45
- if (!isRefreshing) {
46
- isRefreshing = true;
47
- forward$ = fromPromise(
48
- client
49
- .mutate({
50
- context: {uri: hosts.authHost},
51
- variables: {refreshToken},
52
- mutation: schema.RefreshTokenDocument,
53
- })
54
- .then(
55
- ({
56
- data: {
57
- refreshToken: {tokenAuth, tokenRefresh},
58
- },
59
- }) => {
60
- refreshCookies(tokenAuth, tokenRefresh, mainDomain);
61
- resolvePendingRequests();
62
- return true;
63
- },
64
- )
65
- .catch(async () => {
66
- await apolloClient?.mutate({
67
- context: {uri: hosts.authHost},
68
- mutation: schema.RevokeTokenDocument,
69
- });
70
-
71
- destroyCookies(mainDomain);
72
- pendingRequests = [];
73
- window.location.reload();
74
- return false;
75
- })
76
- .finally(() => {
77
- isRefreshing = false;
78
- }),
79
- ).filter((value) => Boolean(value));
80
- } else {
81
- forward$ = fromPromise(
82
- new Promise((resolve) => {
83
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
84
- // @ts-ignore
85
- pendingRequests.push(() => resolve());
86
- }),
87
- );
88
- }
89
- return forward$.flatMap(() => forward(operation));
85
+ return handleTokenRefresh(operation, forward).flatMap(() => forward(operation));
90
86
  }
91
87
  }
92
88
  }
@@ -94,66 +90,24 @@ const errorLink = onError(({graphQLErrors, networkError, operation, forward}) =>
94
90
  if (networkError) {
95
91
  console.warn(`[Network error]: ${networkError}`);
96
92
 
93
+ if (networkError.message.includes("503")) {
94
+ console.error(`[503 Service Unavailable]: ${networkError.message}`);
95
+ }
96
+
97
97
  if (networkError.message.includes("401") && authToken) {
98
- let forward$;
99
- const client = apolloClient ?? createApolloClient();
100
- if (!isRefreshing) {
101
- isRefreshing = true;
102
- forward$ = fromPromise(
103
- client
104
- .mutate({
105
- context: {uri: hosts.authHost},
106
- variables: {refreshToken},
107
- mutation: schema.RefreshTokenDocument,
108
- })
109
- .then(
110
- ({
111
- data: {
112
- refreshToken: {tokenAuth, tokenRefresh},
113
- },
114
- }) => {
115
- refreshCookies(tokenAuth, tokenRefresh, mainDomain);
116
- resolvePendingRequests();
117
- return true;
118
- },
119
- )
120
- .catch(async () => {
121
- await apolloClient?.mutate({
122
- context: {uri: hosts.authHost},
123
- mutation: schema.RevokeTokenDocument,
124
- });
125
-
126
- destroyCookies(mainDomain);
127
- pendingRequests = [];
128
- window.location.reload();
129
- return false;
130
- })
131
- .finally(() => {
132
- isRefreshing = false;
133
- }),
134
- ).filter((value) => Boolean(value));
135
- } else {
136
- forward$ = fromPromise(
137
- new Promise((resolve) => {
138
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
139
- // @ts-ignore
140
- pendingRequests.push(() => resolve());
141
- }),
142
- );
143
- }
144
- return forward$.flatMap(() => forward(operation));
98
+ return handleTokenRefresh(operation, forward).flatMap(() => forward(operation));
145
99
  }
146
100
  }
147
101
  });
148
102
 
149
- const authLink = setContext(async (operation, {headers}) => {
150
- const {authToken} = getCookies();
103
+ const authLink = setContext(async (operation, { headers }) => {
104
+ const { authToken } = getCookies();
151
105
 
152
106
  const header = authToken
153
107
  ? {
154
- headers: {...headers, "x-client-authorization": `${authToken}`},
108
+ headers: { ...headers, "x-client-authorization": `${authToken}` },
155
109
  }
156
- : {headers: {...headers}};
110
+ : { headers: { ...headers } };
157
111
 
158
112
  return {
159
113
  headers: header.headers,
@@ -174,7 +128,7 @@ const wsLink =
174
128
  connected: () => console.log("GraphQLWsLink connected"),
175
129
  closed: () => console.log("GraphQLWsLink closed"),
176
130
  },
177
- }),
131
+ })
178
132
  )
179
133
  : null;
180
134
 
@@ -183,12 +137,12 @@ const opsLink: ApolloLink = from([errorLink, authLink, httpLink as unknown as Ap
183
137
  const terminatingLink =
184
138
  typeof window !== "undefined" && wsLink !== null
185
139
  ? split(
186
- ({query}) => {
140
+ ({ query }) => {
187
141
  const definition = getMainDefinition(query);
188
142
  return definition.kind === "OperationDefinition" && definition.operation === "subscription";
189
143
  },
190
144
  wsLink,
191
- opsLink,
145
+ opsLink
192
146
  )
193
147
  : httpLink;
194
148
 
@@ -198,8 +152,8 @@ function createApolloClient() {
198
152
  link: terminatingLink as ApolloLink,
199
153
  cache: new InMemoryCache({
200
154
  typePolicies: typePoliciesPortal,
201
- addTypename: true,
202
- resultCaching: true,
155
+ addTypename: true,
156
+ resultCaching: true,
203
157
  }),
204
158
  });
205
159
  }
@@ -208,27 +162,19 @@ export function initializeApollo(initialState = null, domain?: string) {
208
162
  const _apolloClient = apolloClient ?? createApolloClient();
209
163
  mainDomain = domain || '';
210
164
 
211
- // If your page has Next.js data fetching methods that use Apollo Client, the initial state
212
- // gets hydrated here
213
165
  if (initialState) {
214
- // Get existing cache, loaded during client side data fetching
215
166
  const existingCache = _apolloClient.extract();
216
-
217
- // Merge the initialState from getStaticProps/getServerSideProps in the existing cache
218
167
  const data = merge(existingCache, initialState, {
219
- // combine arrays using object equality (like in sets)
220
168
  arrayMerge: (destinationArray, sourceArray) => [
221
169
  ...sourceArray,
222
170
  ...destinationArray.filter((d) => sourceArray.every((s) => !isEqual(d, s))),
223
171
  ],
224
172
  });
225
173
 
226
- // Restore the cache with the merged data
227
174
  _apolloClient.cache.restore(data);
228
175
  }
229
- // For SSG and SSR always create a new Apollo Client
176
+
230
177
  if (typeof window === "undefined") return _apolloClient;
231
- // Create the Apollo Client once in the client
232
178
  if (!apolloClient) apolloClient = _apolloClient;
233
179
 
234
180
  return _apolloClient;