@ludo.ninja/api 2.6.0 → 2.6.1

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.
@@ -0,0 +1,2 @@
1
+ import { ApolloClient, NormalizedCacheObject } from "@apollo/client";
2
+ export declare function initializeApollo(initialState?: null, domain?: string): ApolloClient<NormalizedCacheObject>;
@@ -0,0 +1,186 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.initializeApollo = void 0;
7
+ const client_1 = require("@apollo/client");
8
+ const error_1 = require("@apollo/client/link/error");
9
+ const context_1 = require("@apollo/client/link/context");
10
+ const apollo_upload_client_1 = require("apollo-upload-client");
11
+ const deepmerge_1 = __importDefault(require("deepmerge"));
12
+ const lodash_isequal_1 = __importDefault(require("lodash.isequal"));
13
+ const cookies_1 = require("../cookies");
14
+ const typePolicies_1 = require("./typePolicies");
15
+ const subscriptions_1 = require("@apollo/client/link/subscriptions");
16
+ const utilities_1 = require("@apollo/client/utilities");
17
+ const graphql_ws_1 = require("graphql-ws");
18
+ const index_1 = require("../index");
19
+ let isRefreshing = false;
20
+ let pendingRequests = [];
21
+ let mainDomain = "";
22
+ const resolvePendingRequests = () => {
23
+ pendingRequests.map((callback) => callback());
24
+ pendingRequests = [];
25
+ };
26
+ let apolloClient;
27
+ const errorLink = (0, error_1.onError)(({ graphQLErrors, networkError, operation, forward }) => {
28
+ const { authToken, refreshToken } = (0, cookies_1.getCookies)();
29
+ if (graphQLErrors) {
30
+ graphQLErrors.forEach(({ message, locations, path }) => console.warn(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`));
31
+ for (const err of graphQLErrors) {
32
+ 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.schema.RefreshTokenDocument,
42
+ })
43
+ .then(({ data: { refreshToken: { tokenAuth, tokenRefresh }, }, }) => {
44
+ console.log(tokenAuth, "newAuthToken");
45
+ (0, cookies_1.refreshCookies)(tokenAuth, tokenRefresh, mainDomain);
46
+ resolvePendingRequests();
47
+ return true;
48
+ })
49
+ .catch(async () => {
50
+ await apolloClient?.mutate({
51
+ context: { uri: index_1.hosts.authHost },
52
+ mutation: index_1.schema.RevokeTokenDocument,
53
+ });
54
+ (0, cookies_1.destroyCookies)(mainDomain);
55
+ pendingRequests = [];
56
+ window.location.reload();
57
+ return false;
58
+ })
59
+ .finally(() => {
60
+ isRefreshing = false;
61
+ })).filter((value) => Boolean(value));
62
+ }
63
+ else {
64
+ forward$ = (0, client_1.fromPromise)(new Promise((resolve) => {
65
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
66
+ // @ts-ignore
67
+ pendingRequests.push(() => resolve());
68
+ }));
69
+ }
70
+ return forward$.flatMap(() => forward(operation));
71
+ }
72
+ }
73
+ }
74
+ if (networkError) {
75
+ console.warn(`[Network error]: ${networkError}`);
76
+ if (networkError.message.includes("401") && authToken) {
77
+ let forward$;
78
+ const client = apolloClient ?? createApolloClient();
79
+ if (!isRefreshing) {
80
+ isRefreshing = true;
81
+ forward$ = (0, client_1.fromPromise)(client
82
+ .mutate({
83
+ context: { uri: index_1.hosts.authHost },
84
+ variables: { refreshToken },
85
+ mutation: index_1.schema.RefreshTokenDocument,
86
+ })
87
+ .then(({ data: { refreshToken: { tokenAuth, tokenRefresh }, }, }) => {
88
+ (0, cookies_1.refreshCookies)(tokenAuth, tokenRefresh, mainDomain);
89
+ resolvePendingRequests();
90
+ return true;
91
+ })
92
+ .catch(async () => {
93
+ await apolloClient?.mutate({
94
+ context: { uri: index_1.hosts.authHost },
95
+ mutation: index_1.schema.RevokeTokenDocument,
96
+ });
97
+ (0, cookies_1.destroyCookies)(mainDomain);
98
+ pendingRequests = [];
99
+ window.location.reload();
100
+ return false;
101
+ })
102
+ .finally(() => {
103
+ isRefreshing = false;
104
+ })).filter((value) => Boolean(value));
105
+ }
106
+ else {
107
+ forward$ = (0, client_1.fromPromise)(new Promise((resolve) => {
108
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
109
+ // @ts-ignore
110
+ pendingRequests.push(() => resolve());
111
+ }));
112
+ }
113
+ return forward$.flatMap(() => forward(operation));
114
+ }
115
+ }
116
+ });
117
+ const authLink = (0, context_1.setContext)(async (operation, { headers }) => {
118
+ const { authToken } = (0, cookies_1.getCookies)();
119
+ const header = authToken
120
+ ? {
121
+ headers: { ...headers, "x-client-authorization": `${authToken}` },
122
+ }
123
+ : { headers: { ...headers } };
124
+ return {
125
+ headers: header.headers,
126
+ };
127
+ });
128
+ const httpLink = (0, apollo_upload_client_1.createUploadLink)({
129
+ uri: index_1.hosts.authHost,
130
+ });
131
+ const wsLink = typeof window !== "undefined"
132
+ ? new subscriptions_1.GraphQLWsLink((0, graphql_ws_1.createClient)({
133
+ url: index_1.hosts.experiencesSubscriptionHost,
134
+ retryAttempts: 3,
135
+ on: {
136
+ connected: () => console.log("GraphQLWsLink connected"),
137
+ closed: () => console.log("GraphQLWsLink closed"),
138
+ },
139
+ }))
140
+ : null;
141
+ const opsLink = (0, client_1.from)([errorLink, authLink, httpLink]);
142
+ const terminatingLink = typeof window !== "undefined" && wsLink !== null
143
+ ? (0, client_1.split)(({ query }) => {
144
+ const definition = (0, utilities_1.getMainDefinition)(query);
145
+ return definition.kind === "OperationDefinition" && definition.operation === "subscription";
146
+ }, wsLink, opsLink)
147
+ : httpLink;
148
+ function createApolloClient() {
149
+ return new client_1.ApolloClient({
150
+ ssrMode: typeof window === "undefined",
151
+ link: terminatingLink,
152
+ cache: new client_1.InMemoryCache({
153
+ typePolicies: typePolicies_1.typePoliciesPortal,
154
+ addTypename: true,
155
+ resultCaching: true,
156
+ }),
157
+ });
158
+ }
159
+ function initializeApollo(initialState = null, domain) {
160
+ const _apolloClient = apolloClient ?? createApolloClient();
161
+ mainDomain = domain || '';
162
+ // If your page has Next.js data fetching methods that use Apollo Client, the initial state
163
+ // gets hydrated here
164
+ if (initialState) {
165
+ // Get existing cache, loaded during client side data fetching
166
+ const existingCache = _apolloClient.extract();
167
+ // Merge the initialState from getStaticProps/getServerSideProps in the existing cache
168
+ const data = (0, deepmerge_1.default)(existingCache, initialState, {
169
+ // combine arrays using object equality (like in sets)
170
+ arrayMerge: (destinationArray, sourceArray) => [
171
+ ...sourceArray,
172
+ ...destinationArray.filter((d) => sourceArray.every((s) => !(0, lodash_isequal_1.default)(d, s))),
173
+ ],
174
+ });
175
+ // Restore the cache with the merged data
176
+ _apolloClient.cache.restore(data);
177
+ }
178
+ // For SSG and SSR always create a new Apollo Client
179
+ if (typeof window === "undefined")
180
+ return _apolloClient;
181
+ // Create the Apollo Client once in the client
182
+ if (!apolloClient)
183
+ apolloClient = _apolloClient;
184
+ return _apolloClient;
185
+ }
186
+ exports.initializeApollo = initializeApollo;
@@ -0,0 +1,2 @@
1
+ import { TypePolicies } from "@apollo/client";
2
+ export declare const typePoliciesPortal: TypePolicies;
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.typePoliciesPortal = void 0;
4
+ exports.typePoliciesPortal = {
5
+ Query: {
6
+ fields: {
7
+ fetchAsset: {
8
+ keyArgs: ["rank", "likes", "assetId"],
9
+ merge: true,
10
+ },
11
+ fetchUserGalleries: {
12
+ keyArgs: ["galleryId"],
13
+ merge: true,
14
+ },
15
+ fetchUserFavorites: {
16
+ keyArgs: ["galleryId"],
17
+ merge: true,
18
+ },
19
+ fetchUserFavoritesV2: {
20
+ keyArgs: ["galleryId"],
21
+ merge: true,
22
+ },
23
+ fetchMyFavoritesV2: {
24
+ keyArgs: ["galleryId"],
25
+ merge: true,
26
+ },
27
+ fetchMyGalleriesV2: {
28
+ keyArgs: ["galleryId"],
29
+ merge: true,
30
+ },
31
+ fetchUserGalleriesV2: {
32
+ keyArgs: ["galleryId"],
33
+ merge: true,
34
+ },
35
+ fetchCreations: {
36
+ keyArgs: ["itemId"],
37
+ merge: true,
38
+ },
39
+ CollectionPage: {
40
+ keyArgs: ["collectionId"],
41
+ merge: true,
42
+ },
43
+ fetchCreationsByType: {
44
+ keyArgs: ["nextPageToken"],
45
+ merge: true,
46
+ },
47
+ fetchAllCreations: {
48
+ keyArgs: ["nextPageToken"],
49
+ merge: true,
50
+ },
51
+ },
52
+ },
53
+ };
@@ -0,0 +1,25 @@
1
+ import * as express from "express";
2
+ import * as next from 'next';
3
+ declare const assignCookies: (userId: string, wallets: Array<string>, authToken: string, refreshToken: string, newUser: string, inviteCode: string, domain?: string) => void;
4
+ declare const refreshCookies: (authToken: string, refreshToken: string, domain?: string) => void;
5
+ declare const getCookies: (ctx?: Pick<next.NextPageContext, 'req'> | {
6
+ req: next.NextApiRequest;
7
+ } | {
8
+ req: express.Request;
9
+ } | null | undefined) => {
10
+ authToken: null;
11
+ refreshToken: null;
12
+ userId: null;
13
+ wallets: null;
14
+ newUser: null;
15
+ inviteCode: null;
16
+ } | {
17
+ authToken: string;
18
+ refreshToken: string;
19
+ userId: string;
20
+ wallets: string[];
21
+ newUser: string;
22
+ inviteCode: string;
23
+ };
24
+ declare const destroyCookies: (domain?: string) => void;
25
+ export { assignCookies, refreshCookies, destroyCookies, getCookies };
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getCookies = exports.destroyCookies = exports.refreshCookies = exports.assignCookies = void 0;
4
+ const nookies_1 = require("nookies");
5
+ // handle change version when update cookies structure
6
+ const cookiesVersion = '1.0.1';
7
+ const addVersionCookies = (domain) => {
8
+ (0, nookies_1.setCookie)(null, "versionAuth", cookiesVersion, {
9
+ maxAge: 2629800000,
10
+ path: "/",
11
+ domain,
12
+ sameSite: true,
13
+ });
14
+ };
15
+ const validationVersion = (version) => version === cookiesVersion;
16
+ const assignCookies = (userId, wallets, authToken, refreshToken, newUser, inviteCode, domain) => {
17
+ addVersionCookies(domain);
18
+ if (userId)
19
+ (0, nookies_1.setCookie)(null, "userId", userId, { maxAge: 2629800000, path: "/", domain });
20
+ if (wallets)
21
+ (0, nookies_1.setCookie)(null, "wallets", encodeURIComponent(JSON.stringify(wallets)), {
22
+ maxAge: 2629800000,
23
+ path: "/",
24
+ domain,
25
+ sameSite: true,
26
+ });
27
+ if (authToken)
28
+ (0, nookies_1.setCookie)(null, "authToken", authToken, {
29
+ maxAge: 2629800000,
30
+ path: "/",
31
+ domain,
32
+ sameSite: true,
33
+ });
34
+ if (refreshToken)
35
+ (0, nookies_1.setCookie)(null, "refreshToken", refreshToken, {
36
+ maxAge: 2629800000,
37
+ path: "/",
38
+ domain,
39
+ sameSite: true,
40
+ });
41
+ if (newUser)
42
+ (0, nookies_1.setCookie)(null, "newUser", newUser, {
43
+ maxAge: 2629800000,
44
+ path: "/",
45
+ domain,
46
+ sameSite: true,
47
+ });
48
+ if (inviteCode)
49
+ (0, nookies_1.setCookie)(null, "inviteCode", inviteCode, {
50
+ maxAge: 2629800000,
51
+ path: "/",
52
+ domain,
53
+ sameSite: true,
54
+ });
55
+ };
56
+ exports.assignCookies = assignCookies;
57
+ const refreshCookies = (authToken, refreshToken, domain) => {
58
+ if (authToken)
59
+ (0, nookies_1.setCookie)(null, "authToken", authToken, {
60
+ maxAge: 2629800000,
61
+ path: "/",
62
+ domain,
63
+ sameSite: true,
64
+ });
65
+ if (refreshToken)
66
+ (0, nookies_1.setCookie)(null, "refreshToken", refreshToken, {
67
+ maxAge: 2629800000,
68
+ path: "/",
69
+ domain,
70
+ sameSite: true,
71
+ });
72
+ };
73
+ exports.refreshCookies = refreshCookies;
74
+ const getCookies = (ctx) => {
75
+ const { authToken, refreshToken, userId, wallets, newUser, inviteCode, versionAuth } = (0, nookies_1.parseCookies)(ctx);
76
+ const nullResult = {
77
+ authToken: null,
78
+ refreshToken: null,
79
+ userId: null,
80
+ wallets: null,
81
+ newUser: null,
82
+ inviteCode: null,
83
+ };
84
+ if (authToken && refreshToken && userId && wallets && newUser && inviteCode && versionAuth && validationVersion(versionAuth)) {
85
+ let walletsParsed;
86
+ try {
87
+ walletsParsed = JSON.parse(decodeURIComponent(wallets));
88
+ if (!Array.isArray(walletsParsed)) {
89
+ return nullResult;
90
+ }
91
+ }
92
+ catch (e) {
93
+ return nullResult;
94
+ }
95
+ return {
96
+ authToken,
97
+ refreshToken,
98
+ userId,
99
+ wallets: walletsParsed,
100
+ newUser,
101
+ inviteCode,
102
+ };
103
+ }
104
+ return nullResult;
105
+ };
106
+ exports.getCookies = getCookies;
107
+ const destroyCookies = (domain) => {
108
+ (0, nookies_1.destroyCookie)(null, "userId", { path: "/", domain });
109
+ (0, nookies_1.destroyCookie)(null, "wallets", { path: "/", domain });
110
+ (0, nookies_1.destroyCookie)(null, "authToken", { path: "/", domain });
111
+ (0, nookies_1.destroyCookie)(null, "refreshToken", { path: "/", domain });
112
+ (0, nookies_1.destroyCookie)(null, "newUser", { path: "/", domain });
113
+ (0, nookies_1.destroyCookie)(null, "inviteCode", { path: "/", domain });
114
+ };
115
+ exports.destroyCookies = destroyCookies;