Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Some eslint fixes #428

Merged
merged 25 commits into from
Aug 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ jobs:
turbo-${{ github.job }}-${{ github.ref_name }}-

- name: Install dependencies
run: pnpm install
run: pnpm --version && pnpm install --frozen-lockfile

- name: Build
run: pnpm run build
Expand Down
6 changes: 2 additions & 4 deletions apps/checkout/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
module.exports = {
parser: "@typescript-eslint/parser",
root: true,
extends: ["checkout"],
parserOptions: {
tsconfigRootDir: __dirname,
project: ["./tsconfig.json"],
},
plugins: ["react-hooks"],
extends: ["checkout"],
};
9 changes: 5 additions & 4 deletions apps/checkout/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,18 @@
"@types/node": "^16.11.22",
"@types/react": "^18.0.15",
"@types/react-dom": "^18.0.6",
"eslint": "8.19.0",
"eslint": "^8.22.0",
"eslint-config-checkout": "workspace:*",
"eslint-plugin-react": "7.30.1",
"eslint-plugin-react-hooks": "4.6.0",
"react-scripts": "5.0.1",
"tsconfig": "workspace:*",
"typescript": "4.7.4"
},
"scripts": {
"dev": "react-scripts start",
"build": "react-scripts build"
"build": "react-scripts build",
"lint": "eslint .",
"lint:staged": "eslint --fix .",
"check-types": "tsc --noEmit"
},
"browserslist": {
"production": [
Expand Down
5 changes: 4 additions & 1 deletion apps/checkout/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ import "@saleor/checkout-storefront/dist/esm/index.css";
import invariant from "ts-invariant";

const apiUrl = process.env["REACT_APP_SALEOR_API_URL"];
const checkoutApiUrl = process.env["REACT_APP_CHECKOUT_APP_URL"] + `/api`;
const checkoutApiUrl =
typeof process.env["REACT_APP_CHECKOUT_APP_URL"] === "string"
? process.env["REACT_APP_CHECKOUT_APP_URL"] + `/api`
: "";
const checkoutAppUrl = process.env["REACT_APP_CHECKOUT_APP_URL"];

export function App() {
Expand Down
1 change: 1 addition & 0 deletions apps/checkout/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { StrictMode } from "react";
import * as ReactDOM from "react-dom/client";
import { App } from "./App";

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const root = ReactDOM.createRoot(document.getElementById("root")!);
root.render(
<StrictMode>
Expand Down
11 changes: 1 addition & 10 deletions apps/saleor-app-checkout/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,6 @@
module.exports = {
extends: ["checkout", "next"],
extends: ["checkout"],
parserOptions: {
tsconfigRootDir: __dirname,
project: ["./tsconfig.json"],
},
settings: {
next: {
rootDir: ["."],
},
},
rules: {
"require-await": ["error"],
},
};
2 changes: 1 addition & 1 deletion apps/saleor-app-checkout/__tests__/pages/api/pay.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ describe("/api/pay", () => {
expect(mockedCreateOrder).toHaveBeenCalledTimes(1);

expect(mockedCreateAdyenPayment).toHaveBeenCalledWith({
appUrl: "http://undefined",
appUrl: "http://",
method: "creditCard",
order: {
privateMetafield: '{"provider":"adyen","session":"session-id-2","method":"creditCard"}',
Expand Down
2 changes: 1 addition & 1 deletion apps/saleor-app-checkout/backend/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export const isAuthenticated = async (req: NextApiRequest) => {

const jwtVerifier = JwtVerifier.getInstance(tokenData["iss"]);

return await jwtVerifier.verify(token);
return jwtVerifier.verify(token);
};

export const hasPermissionsInToken = (
Expand Down
4 changes: 2 additions & 2 deletions apps/saleor-app-checkout/backend/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ export const getClient = (params: ClientParams = {}) => {
const { apiUrl = envVars.apiUrl, appToken = getAuthToken() } = params;

return createClient({
url: apiUrl!,
url: apiUrl,
requestPolicy: "network-only", // On SSR, Vercel uses client cache in consecutive requests, so we need network-only to always return fresh data from Saleor
fetchOptions: {
headers: {
Authorization: `Bearer ${appToken!}`,
Authorization: `Bearer ${appToken}`,
},
},
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ const readSettingsValues = (
return {
...subSettings,
[subSettingKey]: subSetting.encrypted
? decryptSetting(subSetting as SettingValue, obfuscateEncryptedData)
? decryptSetting(subSetting, obfuscateEncryptedData)
: subSetting.value,
};
},
Expand Down Expand Up @@ -87,7 +87,9 @@ export const mapPrivateMetafieldsToSettings = (
return settings;
}

const metadataItemSettings = JSON.parse(metafield || "");
const metadataItemSettings = JSON.parse(
metafield || ""
) as UnknownPrivateSettingsValues<"encrypted">;

return {
...settings,
Expand Down
2 changes: 1 addition & 1 deletion apps/saleor-app-checkout/backend/payments/createOrder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export const createOrder = async (

if (!data?.orderCreateFromCheckout?.order) {
return {
errors: data?.orderCreateFromCheckout?.errors.map((e) => e.code!) || [
errors: data?.orderCreateFromCheckout?.errors.map((e) => e.code) || [
"COULD_NOT_CREATE_ORDER_FROM_CHECKOUT",
],
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import {
} from "@/saleor-app-checkout/graphql";

export const getOrderTransactions = async (args: OrderTransactionsQueryVariables) => {
const { data, error } = await getClient()
// @todo handle errors
const { data, error: _error } = await getClient()
.query<OrderTransactionsQuery, OrderTransactionsQueryVariables>(OrderTransactionsDocument, args)
.toPromise();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ export const isAdyenNotification: Middleware = (handler) => (request) => {
export const isAdyenWebhookAuthenticated: Middleware = (handler) => (request) => {
const { username, password } = request.context as AdyenRequestContext;

if (typeof request.headers.authorization !== "string") {
return Response.Unauthorized();
}

if (!verifyBasicAuth(username, password, request.headers.authorization)) {
return Response.Unauthorized();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ export const getNewTransactionData = (
transactionEvent,
transaction: {
status: eventCode.toString(),
type: `${ADYEN_PAYMENT_PREFIX}-${paymentMethod}`,
type: `${ADYEN_PAYMENT_PREFIX}-${paymentMethod || "(unknown-payment-method)"}`,
reference: pspReference,
availableActions: mapAvailableActions(operations),
...getTransactionAmountFromAdyen(notification, null),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const createMolliePayment = async ({ order, redirectUrl, appUrl }: Create
const mollieClient = await getMollieClient();

const mollieData = await mollieClient.orders.create({
orderNumber: order.number!,
orderNumber: order.number,
webhookUrl: `${appUrl}/api/webhooks/mollie`,
locale: "en_US",
redirectUrl: formatRedirectUrl(redirectUrl, order.id),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Order, OrderStatus as MollieOrderStatus } from "@mollie/api-client";
import { OrderStatus as MollieOrderStatus } from "@mollie/api-client";
import { getPrivateSettings } from "@/saleor-app-checkout/backend/configuration/settings";
import { envVars } from "@/saleor-app-checkout/constants";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const verifyPayment = async (
const { status, amountCaptured, amountRefunded, metadata, method, amount } =
await mollieClient.orders.get(id);

const type = `${MOLLIE_PAYMENT_PREFIX}-${method}`;
const type = `${MOLLIE_PAYMENT_PREFIX}-${method || "(unknown-payment-method)"}`;
const reference = id;
const eventName = getMollieEventName(status);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { getStripeClient } from "./stripeClient";
export const createStripePayment = async ({
order,
redirectUrl,
appUrl,
appUrl: _appUrl,
method,
}: CreatePaymentData): Promise<CreatePaymentResult> => {
const stripeClient = await getStripeClient();
Expand Down Expand Up @@ -107,9 +107,13 @@ const saleorPaymentMethodIdToStripePaymentMethodId = (
};

const createStripeCustomerFromOrder = (stripeClient: Stripe, order: OrderFragment) => {
const name = [order.billingAddress?.firstName.trim(), order.billingAddress?.lastName.trim()]
.filter(Boolean)
.join(" ");

return stripeClient.customers.create({
email: order.userEmail ?? undefined,
name: order.billingAddress?.firstName + " " + order.billingAddress?.lastName,
name,
address: order.billingAddress
? {
city: order.billingAddress.city,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export const checkoutSessionToTransactionCreateMutationVariables = async (
transaction: {
status: checkoutSession.status || "unknown",
reference: checkoutSession.id,
type: `${STRIPE_PAYMENT_PREFIX}-${method}`,
type: `${STRIPE_PAYMENT_PREFIX}-${method || "(unknown-payment-method)"}`,
availableActions: [],
},
transactionEvent: {
Expand Down Expand Up @@ -102,7 +102,7 @@ export const checkoutSessionToTransactionCreateMutationVariables = async (
transaction: {
status: checkoutSession.status || "unknown",
reference: checkoutSession.id,
type: `${STRIPE_PAYMENT_PREFIX}-${method}`,
type: `${STRIPE_PAYMENT_PREFIX}-${method || "(unknown-payment-method)"}`,
amountAuthorized: {
amount: getAmount("authorized"),
currency: charge.currency.toUpperCase(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import {
} from "@/saleor-app-checkout/graphql";

export const updateTransaction = async (args: TransactionUpdateMutationVariables) => {
const { data, error } = await getClient()
// @todo handle errors
const { data, error: _error } = await getClient()
typeofweb marked this conversation as resolved.
Show resolved Hide resolved
.mutation<TransactionUpdateMutation, TransactionUpdateMutationVariables>(
TransactionUpdateDocument,
args
Expand Down
12 changes: 8 additions & 4 deletions apps/saleor-app-checkout/backend/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { PermissionEnum } from "@/saleor-app-checkout/graphql";
import { NextApiHandler, NextApiRequest } from "next";
import { NextApiHandler } from "next";
import invariant from "ts-invariant";
import { debugEnvVars, envVars, envVarsNames } from "../constants";
import { isAuthenticated, isAuthorized } from "./auth";

Expand All @@ -18,7 +19,7 @@ export const allowCors =
return;
}

return await fn(req, res);
return fn(req, res);
};

export const requireAuthorization =
Expand All @@ -44,7 +45,7 @@ export const requireAuthorization =
});
}

return await fn(req, res);
return fn(req, res);
};

export const getBaseUrl = (req: { headers: Record<string, string | string[] | undefined> }) => {
Expand All @@ -53,7 +54,10 @@ export const getBaseUrl = (req: { headers: Record<string, string | string[] | un
return debugEnvVars.appUrl;
}

const { host, "x-forwarded-proto": protocol = "http" } = req.headers;
const { host = "", "x-forwarded-proto": protocol = "http" } = req.headers;

invariant(typeof host === "string", "host is not a string");
invariant(typeof protocol === "string", "protocol is not a string");

return `${protocol}://${host}`;
};
Expand Down
2 changes: 2 additions & 0 deletions apps/saleor-app-checkout/codegen.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ generates:
scalars:
JSONString: string
UUID: string
Metadata: Record<string, string>
DateTime: string
dedupeOperationSuffix: true # Prevent suffix duplication in generated names
enumsAsTypes: true # note: this doesn't work with @saleor/app-sdk webhook inference
./graphql.schema.json:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { PropsWithChildren } from "react";
import React, { ReactNode } from "react";
import { useStyles } from "./styles";

const AppContainer: React.FC<PropsWithChildren<{}>> = (props) => {
const AppContainer: React.FC<{ children: ReactNode }> = (props) => {
const classes = useStyles();

return <div className={classes.root} {...props} />;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { app, AppBridge } from "@/saleor-app-checkout/frontend/misc/app";
import { useRouter } from "next/router";
import { createContext, PropsWithChildren, useEffect, useState } from "react";
import { createContext, ReactNode, useEffect, useState } from "react";
import { handleRedirectEvent, handleRouteChange } from "./handlers";

interface IAppContext {
Expand All @@ -13,7 +13,7 @@ export const AppContext = createContext<IAppContext>({
isAuthorized: false,
});

const AppProvider: React.FC<PropsWithChildren<{}>> = (props) => {
const AppProvider: React.FC<{ children: ReactNode }> = (props) => {
const router = useRouter();
const [isAuthorized, setIsAuthorized] = useState(!!app?.getState()?.token);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ interface ErrorAlertProps<T> {
getErrorMessage: (error: UnknownError<T>, intl: IntlShape) => string | null | undefined;
}

const ErrorAlert = <T extends any>({ errors, getErrorMessage }: ErrorAlertProps<T>) => {
const ErrorAlert = <T,>({ errors, getErrorMessage }: ErrorAlertProps<T>) => {
const intl = useIntl();
const classes = useStyles();

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { defaultPrivateSettings } from "@/saleor-app-checkout/config/defaults";
import createSafeContext from "@/saleor-app-checkout/frontend/misc/createSafeContext";
import { PrivateSettingsValues } from "@/saleor-app-checkout/types/api";
import { Dispatch, PropsWithChildren, SetStateAction, useState } from "react";
import { Dispatch, ReactNode, SetStateAction, useState } from "react";

interface PrivateSettingsProviderContext {
privateSettings: PrivateSettingsValues<"unencrypted">;
Expand All @@ -11,7 +11,7 @@ interface PrivateSettingsProviderContext {
export const [usePrivateSettingsContext, Provider] =
createSafeContext<PrivateSettingsProviderContext>();

const PrivateSettingsProvider: React.FC<PropsWithChildren<{}>> = (props) => {
const PrivateSettingsProvider: React.FC<{ children: ReactNode }> = (props) => {
const [privateSettings, setPrivateSettings] = useState(defaultPrivateSettings);

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ const CustomizationDetails: React.FC<CustomizationDetailsProps> = ({
event: React.ChangeEvent<HTMLInputElement>
) => {
const inputFiles = event.target.files;
if (!!inputFiles?.length) {
if (inputFiles?.length) {
setFiles({
...files,
[optionId]: {
Expand Down
2 changes: 1 addition & 1 deletion apps/saleor-app-checkout/frontend/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export const uploadSettingsFiles = async ({
return data;
}

return await reduce(
return reduce(
dataFiles,
async (settings, subSettings, idx) => {
const uploadedSettings = await settings;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export const useFetch = <
if (result?.error) {
throw result.error;
}
setResult(result);
setResult(result as TData);
return result;
} catch (e) {
setError(e as TError);
Expand Down
10 changes: 7 additions & 3 deletions apps/saleor-app-checkout/frontend/misc/auth.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { app } from "./app";

export const getAuthHeaders = () => ({
Authorization: `Bearer ${app?.getState()?.token}`,
});
export const getAuthHeaders = () => {
const token = app?.getState()?.token;

return {
Authorization: token ? `Bearer ${token}` : "",
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export const mapPublicMetafieldsToSettings = (
}

try {
const metadataItemSettings = JSON.parse(metafield || "");
const metadataItemSettings = JSON.parse(metafield || "") as UnknownPublicSettingsValues;

return {
...settings,
Expand Down