Skip to content

Commit 9f61ba2

Browse files
feat(in-4412): logger in magento api (#1559)
* chore: remove consola * refactor: replace consola with logger * chore: changeset * Update packages/api-client/src/api/cmsPage/index.ts Co-authored-by: Bartosz Herba <[email protected]> * Update packages/api-client/src/api/productDetails/index.ts Co-authored-by: Bartosz Herba <[email protected]> * Update packages/api-client/src/api/products/index.ts Co-authored-by: Bartosz Herba <[email protected]> * refactor: requestPasswordResetEmail debug log * refactor: reset password debug log * refactor: graphql error logs * refactor: network error log * chore: remove redundant debug log * refactor: invalid token log * refactor: link handlers debug logs --------- Co-authored-by: Bartosz Herba <[email protected]>
1 parent f1dfc20 commit 9f61ba2

File tree

12 files changed

+108
-59
lines changed

12 files changed

+108
-59
lines changed

.changeset/grumpy-eels-care.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@vue-storefront/magento-api": minor
3+
---
4+
5+
[CHANGED] Replaced `consola` with Alokai Logger. To learn more about logger, visit [Alokai Logger](https://docs.alokai.com/middleware/guides/logging/).

packages/api-client/package.json

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@
2626
"@vue-storefront/magento-types": "2.0.0",
2727
"@vue-storefront/middleware": "^5.1.0",
2828
"agentkeepalive": "^4.2.1",
29-
"consola": "^3.1.0",
3029
"dotenv": "^16.0.1",
3130
"graphql": "^16.3.0",
3231
"graphql-tag": "^2.12.6",

packages/api-client/src/api/cmsPage/index.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import { ApolloQueryResult } from "@apollo/client/core";
2-
import consola from "consola";
32
import type { CustomHeaders } from "@vue-storefront/magento-types";
43
import { CmsPageQuery, CmsPageQueryVariables, CustomQuery } from "@vue-storefront/magento-types";
54
import gql from "graphql-tag";
5+
import { getLogger } from "@vue-storefront/middleware";
66
import cmsPageQuery from "./cmsPage";
77
import { Context } from "../../types/context";
88
import getHeaders from "../getHeaders";
@@ -71,6 +71,8 @@ export async function cmsPage(
7171
customQuery: CustomQuery = { cmsPage: "cmsPage" },
7272
customHeaders: CustomHeaders = {}
7373
): Promise<ApolloQueryResult<CmsPageQuery>> {
74+
const logger = getLogger(context);
75+
7476
try {
7577
const { cmsPage: cmsPageGQL } = context.extendQuery(customQuery, {
7678
cmsPage: {
@@ -91,15 +93,15 @@ export async function cmsPage(
9193
} catch (error) {
9294
// For error in data we don't throw 500, because it's not server error
9395
if (error.graphQLErrors) {
94-
consola.debug(error);
96+
logger.error(error);
9597

9698
return {
9799
...error,
98100
errors: error.graphQLErrors,
99101
data: null,
100102
};
101103
}
102-
consola.error(error);
104+
103105
throw error.networkError?.result || error;
104106
}
105107
}

packages/api-client/src/api/productDetails/index.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import type {
99
ProductDetailsQueryVariables,
1010
} from "@vue-storefront/magento-types";
1111
import gql from "graphql-tag";
12-
import consola from "consola";
12+
import { getLogger } from "@vue-storefront/middleware";
1313
import productDetailsQuery from "./productDetailsQuery";
1414
import type { Context } from "../../types/context";
1515
import getHeaders from "../getHeaders";
@@ -111,6 +111,8 @@ export async function productDetails(
111111
customQuery: CustomQuery = { productDetails: "productDetails" },
112112
customHeaders: CustomHeaders = {}
113113
): Promise<ApolloQueryResult<ProductDetailsQuery>> {
114+
const logger = getLogger(context);
115+
114116
const defaultParams = {
115117
pageSize: 10,
116118
currentPage: 1,
@@ -148,15 +150,15 @@ export async function productDetails(
148150
} catch (error) {
149151
// For error in data we don't throw 500, because it's not server error
150152
if (error.graphQLErrors) {
151-
consola.debug(error);
153+
logger.error(error);
152154

153155
return {
154156
...error,
155157
errors: error.graphQLErrors,
156158
data: null,
157159
};
158160
}
159-
consola.error(error);
161+
160162
throw error.networkError?.result || error;
161163
}
162164
}

packages/api-client/src/api/products/index.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import {
99
ProductsListQueryVariables,
1010
} from "@vue-storefront/magento-types";
1111
import gql from "graphql-tag";
12-
import consola from "consola";
12+
import { getLogger } from "@vue-storefront/middleware";
1313
import productsListQuery from "./productsList";
1414
import { Context } from "../../types/context";
1515
import getHeaders from "../getHeaders";
@@ -111,6 +111,8 @@ export async function products(
111111
customQuery: CustomQuery = { products: "products" },
112112
customHeaders: CustomHeaders = {}
113113
): Promise<ApolloQueryResult<ProductsListQuery>> {
114+
const logger = getLogger(context);
115+
114116
const defaultParams = {
115117
pageSize: 10,
116118
currentPage: 1,
@@ -148,15 +150,15 @@ export async function products(
148150
} catch (error) {
149151
// For error in data we don't throw 500, because it's not server error
150152
if (error.graphQLErrors) {
151-
consola.debug(error);
153+
logger.error(error);
152154

153155
return {
154156
...error,
155157
errors: error.graphQLErrors,
156158
data: null,
157159
};
158160
}
159-
consola.error(error);
161+
160162
throw error.networkError?.result || error;
161163
}
162164
}

packages/api-client/src/api/requestPasswordResetEmail/index.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { GraphQLError } from "graphql";
33
import type { CustomHeaders } from "@vue-storefront/magento-types";
44
import { RequestPasswordResetEmailMutation, RequestPasswordResetEmailMutationVariables } from "@vue-storefront/magento-types";
55
import gql from "graphql-tag";
6-
import consola from "consola";
6+
import { getLogger } from "@vue-storefront/middleware";
77
import recaptchaValidator from "../../helpers/recaptcha/recaptchaValidator";
88
import requestPasswordResetEmailMutation from "./requestPasswordResetEmail";
99
import { Context } from "../../types/context";
@@ -28,6 +28,8 @@ export async function requestPasswordResetEmail(
2828
input: RequestPasswordResetEmailMutationVariables,
2929
customHeaders: CustomHeaders = {}
3030
): Promise<FetchResult<RequestPasswordResetEmailMutation>> {
31+
const logger = getLogger(context);
32+
3133
const { recaptchaToken, ...variables } = input;
3234

3335
if (context.config.recaptcha.isEnabled) {
@@ -44,7 +46,7 @@ export async function requestPasswordResetEmail(
4446
}
4547
}
4648

47-
consola.debug("[VSF: Magento] requestPasswordResetEmail", JSON.stringify(input, null, 2));
49+
logger.debug(`Requesting password reset email with input`, { input });
4850
const result = await context.client.mutate<RequestPasswordResetEmailMutation, RequestPasswordResetEmailMutationVariables>({
4951
mutation: gql`
5052
${requestPasswordResetEmailMutation}

packages/api-client/src/api/resetPassword/index.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { GraphQLError } from "graphql";
33
import type { CustomHeaders } from "@vue-storefront/magento-types";
44
import { ResetPasswordMutation, ResetPasswordMutationVariables } from "@vue-storefront/magento-types";
55
import gql from "graphql-tag";
6-
import consola from "consola";
6+
import { getLogger } from "@vue-storefront/middleware";
77
import resetPasswordMutation from "./resetPassword";
88
import { Context } from "../../types/context";
99
import recaptchaValidator from "../../helpers/recaptcha/recaptchaValidator";
@@ -30,6 +30,8 @@ export async function resetPassword(
3030
input: ResetPasswordMutationVariables,
3131
customHeaders: CustomHeaders = {}
3232
): Promise<FetchResult<ResetPasswordMutation>> {
33+
const logger = getLogger(context);
34+
3335
const { recaptchaToken, ...variables } = input;
3436

3537
if (context.config.recaptcha.isEnabled) {
@@ -46,7 +48,7 @@ export async function resetPassword(
4648
}
4749
}
4850

49-
consola.debug("[VSF: Magento] requestPasswordResetEmail", JSON.stringify(input, null, 2));
51+
logger.debug("Initiating password reset request with input", { input });
5052
const result = await context.client.mutate<ResetPasswordMutation, ResetPasswordMutationVariables>({
5153
mutation: gql`
5254
${resetPasswordMutation}

packages/api-client/src/helpers/magentoLink/graphQl.ts

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { onError } from "@apollo/client/link/error";
44
import { RetryLink } from "@apollo/client/link/retry";
55
import { setContext } from "@apollo/client/link/context";
66
import AgentKeepAlive from "agentkeepalive";
7-
import consola from "consola";
7+
import { getLogger, type AlokaiContainer } from "@vue-storefront/middleware";
88
import { handleRetry } from "./linkHandlers";
99
import { Config } from "../../types/setup";
1010
import possibleTypes from "../../types/possibleTypes.json";
@@ -15,8 +15,10 @@ const agent = new HttpsAgent({
1515
timeout: 30000,
1616
});
1717

18-
const createErrorHandler = () =>
18+
const createErrorHandler = (alokai: AlokaiContainer) =>
1919
onError(({ graphQLErrors, networkError }) => {
20+
const logger = getLogger(alokai);
21+
2022
if (graphQLErrors) {
2123
graphQLErrors.forEach(({ message, locations, path, extensions }) => {
2224
// Mute all GraphQL authorization errors
@@ -26,27 +28,28 @@ const createErrorHandler = () =>
2628

2729
if (!message.includes("Resource Owner Password Credentials Grant")) {
2830
if (!locations) {
29-
consola.error(`[GraphQL error]: Message: ${message}, Path: ${path}`);
31+
logger.error(message, { path });
3032
return;
3133
}
3234

3335
const parsedLocations = locations.map(({ column, line }) => `[column: ${column}, line: ${line}]`);
3436

35-
consola.error(`[GraphQL error]: Message: ${message}, Location: ${parsedLocations.join(", ")}, Path: ${path}`);
37+
logger.error(message, { path, location: parsedLocations.join(", ") });
3638
}
3739
});
3840
}
3941

4042
if (networkError) {
41-
consola.error(`[Network error]: ${networkError}`);
43+
logger.error(networkError, { type: "Network Error" });
4244
}
4345
});
4446

4547
export const apolloLinkFactory = (
4648
settings: Config,
47-
handlers?: {
49+
handlers: {
4850
apolloLink?: ApolloLink;
49-
}
51+
},
52+
alokai: AlokaiContainer
5053
) => {
5154
const baseLink =
5255
handlers?.apolloLink ||
@@ -66,10 +69,10 @@ export const apolloLinkFactory = (
6669
...settings.customApolloHttpLinkOptions,
6770
});
6871

69-
const onErrorLink = createErrorHandler();
72+
const onErrorLink = createErrorHandler(alokai);
7073

7174
const errorRetry = new RetryLink({
72-
attempts: handleRetry(),
75+
attempts: handleRetry({ alokai }),
7376
delay: () => 0,
7477
});
7578

packages/api-client/src/helpers/magentoLink/index.ts

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
1-
import consola from "consola";
1+
import { type AlokaiContainer } from "@vue-storefront/middleware";
22
import { Config } from "../../types/setup";
33
import { apolloLinkFactory } from "./graphQl";
44
import { linkFactory } from "./linkHandlers";
55

6-
export const createMagentoConnection = (settings: Config) => {
7-
consola.debug("createMagentoConnection");
8-
9-
const apolloLink = apolloLinkFactory(settings, {
10-
apolloLink: linkFactory({ state: settings.state }),
11-
});
6+
export const createMagentoConnection = (settings: Config, alokai: AlokaiContainer) => {
7+
const apolloLink = apolloLinkFactory(
8+
settings,
9+
{
10+
apolloLink: linkFactory({ state: settings.state, alokai }),
11+
},
12+
alokai
13+
);
1214

1315
return {
1416
apolloLink,

packages/api-client/src/helpers/magentoLink/linkHandlers.ts

Lines changed: 26 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,48 @@
11
import { setContext } from "@apollo/client/link/context";
2-
import consola from "consola";
2+
import { getLogger, type AlokaiContainer } from "@vue-storefront/middleware";
33
import { ConfigState } from "../../types/setup";
44

5-
export const handleRetry = () => (count, operation, error) => {
6-
if (count > 3) {
7-
return false;
8-
}
5+
export const handleRetry =
6+
({ alokai }: { alokai: AlokaiContainer }) =>
7+
(retryCount, operation, error) => {
8+
const logger = getLogger(alokai);
9+
10+
if (retryCount > 3) {
11+
return false;
12+
}
913

10-
if (error?.result?.message === "invalid_token") {
11-
consola.debug(`Apollo retry-link, the operation (${operation.operationName}) sent with wrong token, creating a new one... (attempt: ${count})`);
12-
return true;
13-
}
14+
if (error?.result?.message === "invalid_token") {
15+
const { operationName } = operation;
16+
logger.error(`Invalid token used for operation ${operationName}, Apollo retry-link will refresh the token and retry`, {
17+
operation,
18+
retryCount,
19+
});
20+
return true;
21+
}
1422

15-
return false;
16-
};
23+
return false;
24+
};
1725

18-
export const linkFactory = ({ state }: { state: ConfigState }) =>
26+
export const linkFactory = ({ state, alokai }: { state: ConfigState; alokai: AlokaiContainer }) =>
1927
setContext((apolloReq, { headers }) => {
20-
consola.debug("Apollo linkFactory", apolloReq.operationName);
28+
const logger = getLogger(alokai);
29+
30+
logger.debug(`Apollo linkFactory ${apolloReq.operationName}`);
2131

2232
const Store: string = state.getStore();
2333
const token: string = state.getCustomerToken();
2434
const currency: string = state.getCurrency();
2535

2636
if (currency) {
27-
consola.debug("Apollo currencyLinkFactory, finished, currency: ", currency);
37+
logger.debug(`Finished executing Apollo currencyLinkFactory.`, { currency });
2838
}
2939

3040
if (Store) {
31-
consola.debug("Apollo storeLinkFactory, finished, storeId: ", Store);
41+
logger.debug(`Finished executing Apollo storeLinkFactory.`, { Store });
3242
}
3343

3444
if (token) {
35-
consola.debug("Apollo authLinkFactory, finished, token: ", token);
45+
logger.debug(`Finished executing Apollo authLinkFactory.`, { token });
3646
}
3747

3848
return {

0 commit comments

Comments
 (0)