Skip to content

Commit

Permalink
feat: refactor image url function (#189)
Browse files Browse the repository at this point in the history
* feat: refactor image url

* style(event-card): add back filter background

* feat: revalidate API use POST
  • Loading branch information
PaiJi committed Jun 2, 2024
1 parent 779fce4 commit 1de47b2
Show file tree
Hide file tree
Showing 5 changed files with 28 additions and 57 deletions.
6 changes: 3 additions & 3 deletions src/components/eventCard/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { BsCalendar2DateFill } from "react-icons/bs";
import Image from "@/components/image";
import clsx from "clsx";
import { sendTrack } from "@/utils/track";
import { getEventCoverUrl } from "@/utils/imageLoader";
import { getEventCoverImgPath } from "@/utils/imageLoader";
import { format } from "date-fns";
import { zhCN } from "date-fns/locale";

Expand All @@ -20,7 +20,7 @@ export default function EventCard({
event: Event;
sizes?: string;
}) {
const finalEventCoverImage = getEventCoverUrl(event);
const finalEventCoverImage = getEventCoverImgPath(event);
const isDefaultCover = finalEventCoverImage.includes(
"fec-event-default-cover"
);
Expand Down Expand Up @@ -117,7 +117,7 @@ export default function EventCard({
<div
className={clsx(
styles["event-card__desc-container"],
"p-2 md:p-4 bg-red-100/20 group-hover:bg-red-400/90 transition duration-300 rounded-b-xl z-10 w-full",
"p-2 md:p-4 bg-black/20 group-hover:bg-red-400/90 transition duration-300 rounded-b-xl z-10 w-full",
"text-white",
!isDefaultCover && "backdrop-blur-md"
)}
Expand Down
18 changes: 4 additions & 14 deletions src/pages/[organization]/[slug].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { TbArrowsRightLeft } from "react-icons/tb";
import Link from "next/link";
import { EventScaleLabel, EventStatus, EventStatusSchema } from "@/types/event";
import { sendTrack } from "@/utils/track";
import { getEventCoverUrl, imageUrl } from "@/utils/imageLoader";
import { getEventCoverImgPath, imageUrl } from "@/utils/imageLoader";
import Script from "next/script";
import OrganizationLinkButton, {
BiliButton,
Expand Down Expand Up @@ -45,7 +45,7 @@ export default function EventDetail({ event }: { event: Event }) {
return MapLoadingStatus.Idle;
});

const finalEventCoverImage = getEventCoverUrl(event);
const finalEventCoverImage = getEventCoverImgPath(event);

const initMap = () => {
if (!window.TMap) throw new Error("TMap is not loaded");
Expand Down Expand Up @@ -457,11 +457,7 @@ export async function getStaticProps(context: GetStaticPropsContext) {
}),
des: metaDes,
url: `https://www.furryeventchina.com/${context.params?.organization}/${event?.slug}/`,
cover: imageUrl(
event?.coverUrl ||
event?.posterUrl?.[0] ||
"https://images.furrycons.cn/fec-event-default-cover.png"
),
cover: imageUrl(getEventCoverImgPath(event)),
},
structuredData: {
breadcrumb: {
Expand Down Expand Up @@ -508,13 +504,7 @@ export async function getStaticProps(context: GetStaticPropsContext) {
addressCountry: "CN",
},
},
image: [
imageUrl(
event?.coverUrl ||
event?.posterUrl?.[0] ||
"https://images.furrycons.cn/fec-event-default-cover.png"
),
],
image: [imageUrl(getEventCoverImgPath(event))],
description: event?.detail,
// offers: {
// "@type": "Offer",
Expand Down
27 changes: 11 additions & 16 deletions src/pages/api/revalidate.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,28 @@
import { NextApiRequest, NextApiResponse } from "next";

const simpleToken = process.env.XATA_API_KEY?.slice(0, 6);

export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const { secret, pathname } = req.query;
// Check for secret to confirm this is a valid request
if (
typeof process.env.XATA_API_KEY !== "string" ||
typeof secret !== "string" ||
typeof pathname !== "string"
) {
return res.status(401).json({ message: "Invalid token or params." });
const auth = req.headers.authorization;

if (auth !== simpleToken) {
return res.status(401).json({ message: "Invalid token." });
}
const payload = req.body;

const simpleToken = process.env.XATA_API_KEY.slice(0, 6);
const { pathname } = payload;

if (secret !== simpleToken) {
return res.status(401).json({ message: "Invalid token" });
if (typeof pathname !== "string") {
return res.status(401).json({ message: "Invalid path." });
}

try {
// this should be the actual path not a rewritten path
// e.g. for "/blog/[slug]" this should be "/blog/post-1"
await res.revalidate(pathname);
return res.json({ revalidated: true });
return res.json({ revalidated: true, revalidatedPath: pathname });
} catch (err) {
// If there was an error, Next.js will continue
// to show the last successfully generated page
return res.status(500).send("Error revalidating");
}
}
4 changes: 2 additions & 2 deletions src/pages/city.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Event, XataClient } from "@/xata/xata";
import groupBy from "lodash-es/groupBy";
import Link from "next/link";
import { useMemo, useState } from "react";
import { getEventCoverUrl } from "@/utils/imageLoader";
import { getEventCoverImgPath } from "@/utils/imageLoader";
import { format } from "date-fns";
import Image from "@/components/image";
import { titleGenerator } from "@/utils/meta";
Expand Down Expand Up @@ -140,7 +140,7 @@ function CityYearSelection({ events }: { events: Event[] }) {
<div className="rounded-xl duration-500 transition group-hover:border-gray-400 w-full h-full absolute brightness-75 hover:brightness-100">
<Image
alt="活动背景"
src={getEventCoverUrl(event)}
src={getEventCoverImgPath(event)}
width={350}
className="h-full w-full object-cover rounded-xl overflow-hidden"
autoFormat
Expand Down
30 changes: 8 additions & 22 deletions src/utils/imageLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,20 @@ import { ImageLoaderProps } from "next/image";
import { EventRecord } from "@/xata/xata";

const GLOBAL_AUTO_CDN_IMAGE_URL = "images.furrycons.cn";
const GLOBAL_MANUAL_CDN_IMAGE_URL = "images.furryeventchina.com";
const NO_CDN_IMAGE_URL = "cos-proxy.furrycons.cn";

export const getEventCoverUrl = (event: Partial<EventRecord>) => {
return imageUrl(
event.coverUrl ||
event.posterUrl?.[0] ||
`https://images.furrycons.cn/fec-event-default-cover.png`
export const getEventCoverImgPath = (event: Partial<EventRecord>) => {
return (
event.coverUrl || event.posterUrl?.[0] || `fec-event-default-cover.png`
);
};

export const imageUrl = (src: string) => {
const withoutDefaultHostSrc = src
.replace("https://cdn.furryeventchina.com/", "")
.replace("https://images.furryeventchina.com/", "")
.replace("https://images.furrycons.cn/", "")
.trim();

if (process.env.NODE_ENV === "development") {
return `https://${GLOBAL_MANUAL_CDN_IMAGE_URL}/${withoutDefaultHostSrc}`;
return `https://${NO_CDN_IMAGE_URL}/${src}`;
}

return `https://${GLOBAL_AUTO_CDN_IMAGE_URL}/${withoutDefaultHostSrc}`;
return `https://${GLOBAL_AUTO_CDN_IMAGE_URL}/${src}`;
};

const imageLoader = ({
Expand All @@ -39,17 +31,11 @@ const imageLoader = ({
width?: number;
height?: number;
}) => {
const withoutDefaultHostSrc = src
.replace("https://cdn.furryeventchina.com/", "")
.replace("https://images.furryeventchina.com/", "")
.replace("https://images.furrycons.cn/", "")
.trim();

const imageURLHost =
process.env.NODE_ENV === "development"
? `https://${GLOBAL_MANUAL_CDN_IMAGE_URL}`
? `https://${NO_CDN_IMAGE_URL}`
: `https://${GLOBAL_AUTO_CDN_IMAGE_URL}`;
const imageURL = new URL(`${imageURLHost}/${withoutDefaultHostSrc}`);
const imageURL = new URL(`${imageURLHost}/${src}`);

width !== undefined && imageURL.searchParams.set("w", width.toString());
height !== undefined && imageURL.searchParams.set("h", height.toString());
Expand Down

0 comments on commit 1de47b2

Please sign in to comment.