Skip to content

Commit

Permalink
upgrades to SvelteKit 2.x
Browse files Browse the repository at this point in the history
  • Loading branch information
AlanBreck committed Feb 22, 2024
1 parent f686835 commit 5054980
Show file tree
Hide file tree
Showing 13 changed files with 454 additions and 278 deletions.
597 changes: 380 additions & 217 deletions package-lock.json

Large diffs are not rendered by default.

17 changes: 10 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@
"@sentry/node": "7.101.1",
"@stablelib/base64": "1.0.1",
"@stablelib/utf8": "1.0.2",
"@sveltejs/adapter-node": "1.3.1",
"@sveltejs/kit": "1.30.3",
"@sveltejs/adapter-node": "2.1.2",
"@sveltejs/kit": "2.5.0",
"@types/marked": "6.0.0",
"autoprefixer": "10.4.17",
"graphql": "16.8.1",
Expand All @@ -38,16 +38,19 @@
"marked": "9.1.6",
"postcss": "8.4.35",
"prettier": "3.2.5",
"prettier-plugin-svelte": "3.0.3",
"prettier-plugin-svelte": "3.2.1",
"qs": "6.11.2",
"sass": "1.71.0",
"stripe": "13.11.0",
"svelte": "4.2.10",
"svelte-check": "3.5.2",
"svelte-preprocess": "5.0.4",
"svelte": "4.2.11",
"svelte-check": "3.6.4",
"svelte-preprocess": "5.1.3",
"tailwindcss": "3.4.1",
"tweetnacl": "1.0.3",
"typescript": "4.9.5",
"vite": "4.5.2"
"vite": "5.1.3"
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "3.0.2"
}
}
3 changes: 2 additions & 1 deletion src/lib/graphql/sdk.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { GraphQLClient } from 'graphql-request';
import { getSdk } from '$lib/graphql/index.generated';
import { env } from '$env/dynamic/private';
import { building } from '$app/environment';

const client = new GraphQLClient(`${env.API_URL}/api/graphql`);
const client = new GraphQLClient(`${!building && env.API_URL}/api/graphql`);

export const sdk = getSdk(client);
17 changes: 10 additions & 7 deletions src/lib/printful-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,24 +16,27 @@ export async function printfulApi (resourcePath: string, options?: RequestInit)
const responseBody = await response.json();

if (response.status !== 200) {
throw error(400, responseBody.result);
error(400, responseBody.result);
}

return responseBody.result;
}

interface CreateOrderOptions {
draft: boolean
draft: boolean;
}

export async function createOrder (order: App.Order, { draft = true }: CreateOrderOptions): Promise<void> {
let url = "/orders";
export async function createOrder(
order: App.Order,
{ draft = true }: CreateOrderOptions
): Promise<void> {
let url = '/orders';
if (!draft) {
url += "?confirm=true";
url += '?confirm=true';
}

await printfulApi(url, {
method: "POST",
method: 'POST',
body: JSON.stringify(order)
});
}
}
4 changes: 3 additions & 1 deletion src/lib/stripe-api.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import Stripe from 'stripe';
import { env } from '$env/dynamic/private';
import { building } from '$app/environment';

export const stripe = new Stripe(env.STRIPE_KEY, {
// @ts-ignore
export const stripe = new Stripe(!building && env.STRIPE_KEY, {
apiVersion: '2022-11-15'
});
4 changes: 2 additions & 2 deletions src/routes/+layout.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import { onMount, setContext } from 'svelte';
import { writable } from 'svelte/store';
import DOMPurify from 'isomorphic-dompurify';
import { env } from '$env/dynamic/public';
import { PUBLIC_ASSETS_PATH } from '$env/static/public';
import { browser } from '$app/environment';
import { page } from '$app/stores';
import { afterNavigate } from '$app/navigation';
Expand Down Expand Up @@ -127,7 +127,7 @@

<svelte:head>
<title>{$page.error ? $page.status : $page.data.title} | Brave Merch Store</title>
<link rel="preconnect" crossorigin="anonymous" href={env.PUBLIC_ASSETS_PATH} />
<link rel="preconnect" crossorigin="anonymous" href={PUBLIC_ASSETS_PATH} />
</svelte:head>

{#if showNewItemToast}
Expand Down
2 changes: 1 addition & 1 deletion src/routes/[slug=slug]/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export const load: PageServerLoad = async ({ params }) => {
}, new Map());

if (!pageMap.has(params.slug)) {
throw error(404, "Page not found.");
error(404, "Page not found.");
}

const pageData = await readFile(`${BASE_DIR}/${pageMap.get(params.slug)}`, "utf-8");
Expand Down
59 changes: 30 additions & 29 deletions src/routes/cart/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,15 @@ type Address = {
};

type ShippingRate = {
id: string,
name: string,
rate: string,
currency: string,
minDeliveryDays?: number,
maxDeliveryDays?: number,
minDeliveryDate?: string,
maxDeliveryDate?: string
}
id: string;
name: string;
rate: string;
currency: string;
minDeliveryDays?: number;
maxDeliveryDays?: number;
minDeliveryDate?: string;
maxDeliveryDate?: string;
};

interface StrongVariant extends Omit<Variant, 'details'> {
printfulVariantId: string;
Expand Down Expand Up @@ -84,7 +84,6 @@ function sortStateCountryAlphabetically(a: StateCountry, b: StateCountry) {
const canceledSessionQueryParam = 'session_id';

export const load: PageServerLoad = async ({ url }) => {

/**
* If this page load is from a canceled session then delete
* the shipping data key from DB.
Expand Down Expand Up @@ -188,10 +187,7 @@ export const actions: Actions = {
errors.shippingAddress.hasErrors = true;
errors.shippingAddress.state_code = { missing: true };
}
if (
shippingAddress.phone &&
!isValidPhoneNumber(shippingAddress.phone, callingCodeCountry)
) {
if (shippingAddress.phone && !isValidPhoneNumber(shippingAddress.phone, callingCodeCountry)) {
errors.shippingAddress.hasErrors = true;
errors.shippingAddress.phone = { invalid: true };
}
Expand Down Expand Up @@ -270,31 +266,34 @@ export const actions: Actions = {
})
});

const formatDate = (date: Date) => date.toLocaleString("en-US", { month: "short", day: "numeric" });
const formatDate = (date: Date) =>
date.toLocaleString('en-US', { month: 'short', day: 'numeric' });

const getCustomShippingName = (shippingRate: ShippingRate) => {
const shippingNameMappings: Record<string, string> = {
STANDARD: "Standard",
PRINTFUL_FAST: "Express"
STANDARD: 'Standard',
PRINTFUL_FAST: 'Express'
};

let shippingName = shippingNameMappings[shippingRate.id] || shippingRate.name;

const minDate = shippingRate?.minDeliveryDate && new Date(shippingRate.minDeliveryDate + "T00:00:00");
const maxDate = shippingRate?.maxDeliveryDate && new Date(shippingRate.maxDeliveryDate + "T00:00:00");
const minDate =
shippingRate?.minDeliveryDate && new Date(shippingRate.minDeliveryDate + 'T00:00:00');
const maxDate =
shippingRate?.maxDeliveryDate && new Date(shippingRate.maxDeliveryDate + 'T00:00:00');

if (minDate && maxDate && minDate.getDate() === maxDate.getDate()) {
shippingName += ` (Estimated delivery: ${formatDate(maxDate)})`
shippingName += ` (Estimated delivery: ${formatDate(maxDate)})`;
} else if (minDate && maxDate) {
shippingName += ` (Estimated delivery: ${formatDate(minDate)}-${formatDate(maxDate)})`
shippingName += ` (Estimated delivery: ${formatDate(minDate)}-${formatDate(maxDate)})`;
} else if (minDate) {
shippingName += ` (Estimated delivery: ${formatDate(minDate)})`
shippingName += ` (Estimated delivery: ${formatDate(minDate)})`;
} else if (maxDate) {
shippingName += ` (Estimated delivery: ${formatDate(maxDate)})`
shippingName += ` (Estimated delivery: ${formatDate(maxDate)})`;
}

return shippingName;
}
};

const stripeShippingOptions: Array<Stripe.Checkout.SessionCreateParams.ShippingOption> =
shippingRates.map(
Expand Down Expand Up @@ -325,15 +324,15 @@ export const actions: Actions = {
shippingOption.shipping_rate_data.delivery_estimate.minimum = {
unit: 'day',
value: shippingRate.minDeliveryDays
}
};
}

// Add the maximum estimate if Printful provided one
if (shippingRate.maxDeliveryDays) {
shippingOption.shipping_rate_data.delivery_estimate.maximum = {
unit: 'day',
value: shippingRate.maxDeliveryDays
}
};
}
}

Expand All @@ -346,10 +345,12 @@ export const actions: Actions = {
const encryptionKey = generateKey();
const encryptedShippingData = encrypt(recipientInformation, encryptionKey);

const { createShippingDataKey: shippingDataKey } = await sdk.AddShippingDataKey({ key: encryptionKey });
const { createShippingDataKey: shippingDataKey } = await sdk.AddShippingDataKey({
key: encryptionKey
});

if (!shippingDataKey?.id) {
throw new CustomError("Could not get shipping data key id.");
throw new CustomError('Could not get shipping data key id.');
}

session = await stripe.checkout.sessions.create({
Expand All @@ -373,7 +374,7 @@ export const actions: Actions = {
}

if (session.url) {
throw redirect(303, session.url);
redirect(303, session.url);
}
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,16 @@ export const load: PageServerLoad = async function load({ params, url }) {
const basePath = url.pathname.split("page/")[0];

if (params.pagination === 'page/' && !pagination) {
throw redirect(307, basePath);
redirect(307, basePath);
} else if (params.pagination && !pagination) {
throw error(404);
error(404);
}

const limit = 9;
const page = parseInt((pagination && pagination?.groups?.pageNum) ?? '') || 1;

if (pagination && page === 1) {
throw redirect(307, basePath);
redirect(307, basePath);
}

const pageIndex = page ? page - 1 : 0;
Expand All @@ -41,7 +41,7 @@ export const load: PageServerLoad = async function load({ params, url }) {
const { products, productsCount, ...category } = results || {};

if (!products || (products && products?.length <= 0)) {
throw error(404, 'No products found.');
error(404, 'No products found.');
}

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ export async function load({ params }) {
* should redirect to the first variant.
*/
if (!variants || variants.length < 1) {
throw error(404, 'Product not found.');
error(404, 'Product not found.');
} else if (variants.length > 1) {
throw redirect(303, variants[0]?.permalink ?? '');
redirect(303, variants[0]?.permalink ?? '');
}

const { product, ...variant } = variants[0];
Expand Down
2 changes: 1 addition & 1 deletion src/routes/success/+page.server.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ import { redirect } from '@sveltejs/kit';

/** @type {import('./$types').PageServerLoad} */
export async function load() {
throw redirect(307, "/");
redirect(307, "/");
}
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,6 @@ export const load: PageServerLoad = async function load({ params }) {
purchaseItems: items
};
} catch (e) {
throw redirect(307, '/');
redirect(307, '/');
}
};
13 changes: 8 additions & 5 deletions src/routes/webhooks/stripe/+server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import * as printfulApi from '$lib/printful-api';
import { CustomError, decrypt, blockedCountryCodes, ValidationError } from '$lib/utils';
import { sdk } from '$lib/graphql/sdk';

import * as Sentry from "@sentry/node";
import * as Sentry from '@sentry/node';

Sentry.init({
dsn: env.SENTRY_DSN,
Expand All @@ -16,7 +16,7 @@ Sentry.init({
delete event.user;
}
return event;
},
}
});

export const POST: RequestHandler = async ({ request }) => {
Expand All @@ -37,7 +37,7 @@ export const POST: RequestHandler = async ({ request }) => {
await sdk.AddProcessedOrder({ idempotencyKey: session.payment_intent });
fulfillOrder(session);
} catch (e: any) {
if (e.response?.errors[0]?.extensions?.prisma?.code === "P2002") {
if (e.response?.errors[0]?.extensions?.prisma?.code === 'P2002') {
console.log(`Order for ${session.payment_intent} has already been processed.`);
}
}
Expand Down Expand Up @@ -74,7 +74,7 @@ async function fulfillOrder(session: Stripe.Checkout.Session): Promise<void> {
if (encryptedShippingData && shippingDataKey && shippingDataKey.key) {
shippingData = decrypt(encryptedShippingData, shippingDataKey.key);
} else {
throw new CustomError("Could not find encrypted shippingData or shippingDataKey.");
throw new CustomError('Could not find encrypted shippingData or shippingDataKey.');
}

const newOrder = {
Expand All @@ -101,6 +101,9 @@ async function fulfillOrder(session: Stripe.Checkout.Session): Promise<void> {
await sdk.DeleteShippingDataKey({ id: metadata?.keyId });
} catch (e: any) {
console.log(e);
Sentry.captureMessage(`Customer order not submitted to Printful ${session.payment_intent}`, 'error');
Sentry.captureMessage(
`Customer order not submitted to Printful ${session.payment_intent}`,
'error'
);
}
}

0 comments on commit 5054980

Please sign in to comment.