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