refactor: relative Zeitangaben in einer Funktion, Stripe-Client per getStripe() (Deploy B)
- W6: formatRelative(date, t, "compact" | "verbose") ersetzt formatRelativeCompact/formatRelativeVerbose (nur die Übersetzungsschlüssel unterschieden sich). Test hält beide Formen und die Grenzen fest. - W7: getStripe() statt eines Proxy-Objekts um den faulen Singleton; der Client entsteht weiterhin erst beim ersten Aufruf (fehlender Key bricht den Import nicht). Sponsor-Router, Webhook und Mock angepasst. W5 (Bild-/Musik-URLs zusammenführen) bewusst nicht umgesetzt. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5dbde04c6f
commit
1c6c95955e
12 files changed
+110
-59
No files matched your search
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Relative Zeitangaben: kurz („5m“, Kommentare/Mitteilungen) und ausführlich
|
||||
* („vor 5 Minuten“, Beitragskarten). Plan W6 (07.10.).
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, afterAll } from "vitest";
|
||||
import { formatRelative } from "@/lib/format-relative-time";
|
||||
|
||||
const NOW = new Date("2026-10-07T12:00:00Z");
|
||||
const ago = (ms: number) => new Date(NOW.getTime() - ms);
|
||||
const MIN = 60_000;
|
||||
const t = (key: string, values?: Record<string, string | number>) =>
|
||||
values ? `${key}:${values.count}` : key;
|
||||
|
||||
beforeAll(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(NOW);
|
||||
});
|
||||
afterAll(() => vi.useRealTimers());
|
||||
|
||||
describe("formatRelative", () => {
|
||||
it("kurze Form: justNow, minutes, hours, days", () => {
|
||||
expect(formatRelative(ago(30_000), t)).toBe("justNow");
|
||||
expect(formatRelative(ago(5 * MIN), t)).toBe("minutes:5");
|
||||
expect(formatRelative(ago(3 * 60 * MIN), t)).toBe("hours:3");
|
||||
expect(formatRelative(ago(2 * 24 * 60 * MIN), t)).toBe("days:2");
|
||||
});
|
||||
|
||||
it("ausführliche Form nutzt die …Ago-Schlüssel", () => {
|
||||
expect(formatRelative(ago(30_000), t, "verbose")).toBe("justNow");
|
||||
expect(formatRelative(ago(5 * MIN), t, "verbose")).toBe("minutesAgo:5");
|
||||
expect(formatRelative(ago(3 * 60 * MIN), t, "verbose")).toBe("hoursAgo:3");
|
||||
expect(formatRelative(ago(2 * 24 * 60 * MIN), t, "verbose")).toBe("daysAgo:2");
|
||||
});
|
||||
|
||||
it("ab 7 Tagen das Datum, auch als String-Eingabe", () => {
|
||||
const old = ago(8 * 24 * 60 * MIN);
|
||||
expect(formatRelative(old.toISOString(), t)).toBe(old.toLocaleDateString());
|
||||
expect(formatRelative(old, t, "verbose")).toBe(old.toLocaleDateString());
|
||||
});
|
||||
|
||||
it("Grenzen: genau 1 Minute, 60 Minuten, 24 Stunden", () => {
|
||||
expect(formatRelative(ago(MIN), t)).toBe("minutes:1");
|
||||
expect(formatRelative(ago(60 * MIN), t)).toBe("hours:1");
|
||||
expect(formatRelative(ago(24 * 60 * MIN), t)).toBe("days:1");
|
||||
});
|
||||
});
|
||||
@@ -18,11 +18,11 @@ const mockCustomersCreate = vi.fn();
|
||||
const mockCheckoutSessionsCreate = vi.fn();
|
||||
const mockSubscriptionsUpdate = vi.fn();
|
||||
vi.mock("@/lib/stripe", () => ({
|
||||
stripe: {
|
||||
getStripe: () => ({
|
||||
customers: { create: (...args: unknown[]) => mockCustomersCreate(...args) },
|
||||
checkout: { sessions: { create: (...args: unknown[]) => mockCheckoutSessionsCreate(...args) } },
|
||||
subscriptions: { update: (...args: unknown[]) => mockSubscriptionsUpdate(...args) },
|
||||
},
|
||||
}),
|
||||
STRIPE_WEBHOOK_SECRET: "whsec_test",
|
||||
}));
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Stripe-Client (src/lib/stripe.ts): erst bei Bedarf erzeugen — ein fehlender
|
||||
* STRIPE_SECRET_KEY darf den Import (und damit den ganzen tRPC-Router) nicht
|
||||
* abstürzen lassen. Plan W7 (07.10.).
|
||||
*/
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
vi.mock("server-only", () => ({}));
|
||||
const StripeCtor = vi.fn(function (this: { key: string }, key: string) {
|
||||
this.key = key;
|
||||
});
|
||||
vi.mock("stripe", () => ({ default: StripeCtor }));
|
||||
|
||||
describe("getStripe", () => {
|
||||
it("erzeugt den Client erst beim ersten Aufruf und danach nicht erneut", async () => {
|
||||
const { getStripe } = await import("@/lib/stripe");
|
||||
expect(StripeCtor).not.toHaveBeenCalled();
|
||||
|
||||
const first = getStripe();
|
||||
const second = getStripe();
|
||||
|
||||
expect(StripeCtor).toHaveBeenCalledTimes(1);
|
||||
expect(second).toBe(first);
|
||||
});
|
||||
});
|
||||
@@ -9,13 +9,13 @@ import { useActivePet } from "@/context/ActivePetContext";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { getAvatarUrl } from "@/lib/avatar-url";
|
||||
import { formatRelativeCompact } from "@/lib/format-relative-time";
|
||||
import { formatRelative } from "@/lib/format-relative-time";
|
||||
import { RankRing } from "@/components/referrals/RankRing";
|
||||
|
||||
export default function MessagesPage() {
|
||||
const t = useTranslations("Messages");
|
||||
const trt = useTranslations("RelativeTime");
|
||||
const formatRelativeTime = (date: Date | string) => formatRelativeCompact(date, trt);
|
||||
const formatRelativeTime = (date: Date | string) => formatRelative(date, trt);
|
||||
const trpc = useTRPC();
|
||||
const router = useRouter();
|
||||
const { activePetId } = useActivePet();
|
||||
|
||||
@@ -14,7 +14,7 @@ import { BlurImage } from "@/components/ui/blur-image";
|
||||
import { PostDetailDialog } from "@/components/feed/PostDetailDialog";
|
||||
import type { PostCardPost } from "@/components/feed/PostCard";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { formatRelativeCompact } from "@/lib/format-relative-time";
|
||||
import { formatRelative } from "@/lib/format-relative-time";
|
||||
import { RankRing } from "@/components/referrals/RankRing";
|
||||
import { StoryViewer } from "@/components/stories/StoryViewer";
|
||||
|
||||
@@ -54,7 +54,7 @@ export default function NotificationsPage() {
|
||||
const trt = useTranslations("RelativeTime");
|
||||
const t = useTranslations("NotificationsPage");
|
||||
const locale = useLocale();
|
||||
const formatRelativeTime = (date: Date | string) => formatRelativeCompact(date, trt);
|
||||
const formatRelativeTime = (date: Date | string) => formatRelative(date, trt);
|
||||
|
||||
const { data, isLoading, dataUpdatedAt } = useQuery({
|
||||
...trpc.notifications.list.queryOptions({ petId: activePetId ?? "", limit: 30 }),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import type Stripe from "stripe";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { stripe, STRIPE_WEBHOOK_SECRET } from "@/lib/stripe";
|
||||
import { getStripe, STRIPE_WEBHOOK_SECRET } from "@/lib/stripe";
|
||||
|
||||
/**
|
||||
* POST /api/webhooks/stripe
|
||||
@@ -28,7 +28,7 @@ export async function POST(req: NextRequest) {
|
||||
|
||||
let event: Stripe.Event;
|
||||
try {
|
||||
event = stripe.webhooks.constructEvent(body, signature, STRIPE_WEBHOOK_SECRET);
|
||||
event = getStripe().webhooks.constructEvent(body, signature, STRIPE_WEBHOOK_SECRET);
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Invalid signature" }, { status: 400 });
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import { useTranslations } from "next-intl";
|
||||
import { useTRPC } from "@/trpc/client";
|
||||
import { getMediaUrl } from "@/lib/media-url";
|
||||
import { getAvatarUrl } from "@/lib/avatar-url";
|
||||
import { formatRelativeCompact } from "@/lib/format-relative-time";
|
||||
import { formatRelative as formatRelativeCompact } from "@/lib/format-relative-time";
|
||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
@@ -40,7 +40,7 @@ import { Button } from "@/components/ui/button";
|
||||
import Link from "next/link";
|
||||
import { getMediaUrl } from "@/lib/media-url";
|
||||
import { parseCaption } from "@/lib/parse-caption";
|
||||
import { formatRelativeVerbose } from "@/lib/format-relative-time";
|
||||
import { formatRelative } from "@/lib/format-relative-time";
|
||||
import { PawRing } from "@/components/stories/PawRing";
|
||||
import { MilestoneCard } from "@/components/feed/MilestoneCard";
|
||||
import { VideoCard } from "@/components/video/VideoCard";
|
||||
@@ -143,7 +143,7 @@ function PostCardImpl({ post, onDeleted, variant = "feed" }: PostCardProps) {
|
||||
const trpc = useTRPC();
|
||||
const { activePetId } = useActivePet();
|
||||
|
||||
const formatRelativeTime = (date: Date | string) => formatRelativeVerbose(date, t);
|
||||
const formatRelativeTime = (date: Date | string) => formatRelative(date, t, "verbose");
|
||||
|
||||
const { pet, images, createdAt } = post;
|
||||
const [currentCaption, setCurrentCaption] = useState(post.caption);
|
||||
|
||||
@@ -41,7 +41,7 @@ import Link from "next/link";
|
||||
import { getMediaUrl } from "@/lib/media-url";
|
||||
import { BlurImage } from "@/components/ui/blur-image";
|
||||
import { parseCaption } from "@/lib/parse-caption";
|
||||
import { formatRelativeCompact } from "@/lib/format-relative-time";
|
||||
import { formatRelative } from "@/lib/format-relative-time";
|
||||
import { PawButton } from "@/components/feed/PawButton";
|
||||
import { PawBackButton } from "@/components/feed/PawBackButton";
|
||||
import { PawRing } from "@/components/stories/PawRing";
|
||||
@@ -173,7 +173,7 @@ export function PostDetailDialog({ post, open, onClose, onDeleted }: PostDetailD
|
||||
[handleSubmitComment]
|
||||
);
|
||||
|
||||
const formatRelativeTime = (date: Date | string) => formatRelativeCompact(date, trt);
|
||||
const formatRelativeTime = (date: Date | string) => formatRelative(date, trt);
|
||||
|
||||
if (!post) return null;
|
||||
|
||||
|
||||
@@ -1,36 +1,24 @@
|
||||
type TFunc = (key: string, values?: Record<string, string | number>) => string;
|
||||
|
||||
/**
|
||||
* Compact style: "5m", "3h", "2d". Used anywhere space is tight
|
||||
* (comment lists, notifications, ad cards, message previews).
|
||||
* Pass a translator scoped to the "RelativeTime" namespace.
|
||||
* „kurz“: "5m", "3h", "2d" — wo wenig Platz ist (Kommentare, Mitteilungen,
|
||||
* Werbekarten, Nachrichten); Übersetzer mit Namespace "RelativeTime".
|
||||
* „ausführlich“: "vor 5 Minuten" — Beitragskarten im Feed; Übersetzer mit
|
||||
* justNow/minutesAgo/hoursAgo/daysAgo. Ab 7 Tagen das Datum.
|
||||
*/
|
||||
export function formatRelativeCompact(date: Date | string, t: TFunc): string {
|
||||
const diffMs = Date.now() - new Date(date).getTime();
|
||||
const diffMins = Math.floor(diffMs / 60000);
|
||||
const KEYS = {
|
||||
compact: ["minutes", "hours", "days"],
|
||||
verbose: ["minutesAgo", "hoursAgo", "daysAgo"],
|
||||
} as const;
|
||||
|
||||
export function formatRelative(date: Date | string, t: TFunc, style: keyof typeof KEYS = "compact"): string {
|
||||
const [minutesKey, hoursKey, daysKey] = KEYS[style];
|
||||
const diffMins = Math.floor((Date.now() - new Date(date).getTime()) / 60000);
|
||||
const diffHours = Math.floor(diffMins / 60);
|
||||
const diffDays = Math.floor(diffHours / 24);
|
||||
if (diffMins < 1) return t("justNow");
|
||||
if (diffMins < 60) return t("minutes", { count: diffMins });
|
||||
if (diffHours < 24) return t("hours", { count: diffHours });
|
||||
if (diffDays < 7) return t("days", { count: diffDays });
|
||||
return new Date(date).toLocaleDateString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Verbose style: "5 minutes ago", "3 hours ago". Used where there's
|
||||
* room to be explicit (main feed post cards).
|
||||
* Pass a translator with justNow/minutesAgo/hoursAgo/daysAgo keys.
|
||||
*/
|
||||
export function formatRelativeVerbose(date: Date | string, t: TFunc): string {
|
||||
const diffMs = Date.now() - new Date(date).getTime();
|
||||
const diffSecs = Math.floor(diffMs / 1000);
|
||||
const diffMins = Math.floor(diffSecs / 60);
|
||||
const diffHours = Math.floor(diffMins / 60);
|
||||
const diffDays = Math.floor(diffHours / 24);
|
||||
if (diffSecs < 60) return t("justNow");
|
||||
if (diffMins < 60) return t("minutesAgo", { count: diffMins });
|
||||
if (diffHours < 24) return t("hoursAgo", { count: diffHours });
|
||||
if (diffDays < 7) return t("daysAgo", { count: diffDays });
|
||||
if (diffMins < 60) return t(minutesKey, { count: diffMins });
|
||||
if (diffHours < 24) return t(hoursKey, { count: diffHours });
|
||||
if (diffDays < 7) return t(daysKey, { count: diffDays });
|
||||
return new Date(date).toLocaleDateString();
|
||||
}
|
||||
+7
-15
@@ -1,24 +1,16 @@
|
||||
import "server-only";
|
||||
import Stripe from "stripe";
|
||||
|
||||
// Lazy singleton — constructing eagerly at module scope crashes on
|
||||
// `STRIPE_SECRET_KEY` being unset, which previously took down the entire
|
||||
// module graph (including anything that transitively imports the full tRPC
|
||||
// appRouter, e.g. createTRPCCaller() on any public page) even when that
|
||||
// code path never touches Stripe at runtime. Get credentials at
|
||||
// Erst beim ersten Aufruf erzeugen: Eager bei Modul-Import stürzte ohne
|
||||
// STRIPE_SECRET_KEY der ganze Modulgraph ab (inkl. allem, was den tRPC-
|
||||
// appRouter importiert, z. B. createTRPCCaller() auf öffentlichen Seiten),
|
||||
// obwohl der Codepfad Stripe gar nicht braucht. Zugangsdaten:
|
||||
// dashboard.stripe.com → Developers → API keys.
|
||||
let stripeClient: Stripe | null = null;
|
||||
function getStripeClient(): Stripe {
|
||||
if (!stripeClient) {
|
||||
stripeClient = new Stripe(process.env.STRIPE_SECRET_KEY ?? "");
|
||||
}
|
||||
|
||||
export function getStripe(): Stripe {
|
||||
stripeClient ??= new Stripe(process.env.STRIPE_SECRET_KEY ?? "");
|
||||
return stripeClient;
|
||||
}
|
||||
|
||||
export const stripe = new Proxy({} as Stripe, {
|
||||
get(_target, prop, receiver) {
|
||||
return Reflect.get(getStripeClient(), prop, receiver);
|
||||
},
|
||||
});
|
||||
|
||||
export const STRIPE_WEBHOOK_SECRET = process.env.STRIPE_WEBHOOK_SECRET ?? "";
|
||||
@@ -2,7 +2,7 @@ import "server-only";
|
||||
import { z } from "zod";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { router, protectedProcedure } from "@/trpc/init";
|
||||
import { stripe } from "@/lib/stripe";
|
||||
import { getStripe } from "@/lib/stripe";
|
||||
import { isActiveSponsor } from "@/lib/sponsor";
|
||||
|
||||
const MIN_AMOUNT_CENTS = 200; // 2€ minimum
|
||||
@@ -54,7 +54,7 @@ export const sponsorRouter = router({
|
||||
|
||||
let stripeCustomerId = owner.stripeCustomerId;
|
||||
if (!stripeCustomerId) {
|
||||
const customer = await stripe.customers.create({
|
||||
const customer = await getStripe().customers.create({
|
||||
metadata: { ownerId: ctx.userId },
|
||||
});
|
||||
stripeCustomerId = customer.id;
|
||||
@@ -67,7 +67,7 @@ export const sponsorRouter = router({
|
||||
const appUrl = resolveAppUrl();
|
||||
const isSubscription = input.type === "SUBSCRIPTION";
|
||||
|
||||
const session = await stripe.checkout.sessions.create({
|
||||
const session = await getStripe().checkout.sessions.create({
|
||||
customer: stripeCustomerId,
|
||||
mode: isSubscription ? "subscription" : "payment",
|
||||
payment_method_types: isSubscription ? ["sepa_debit", "card"] : ["card"],
|
||||
@@ -102,7 +102,7 @@ export const sponsorRouter = router({
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "No active subscription to cancel." });
|
||||
}
|
||||
|
||||
const subscription = await stripe.subscriptions.update(owner.sponsorSubscriptionId, {
|
||||
const subscription = await getStripe().subscriptions.update(owner.sponsorSubscriptionId, {
|
||||
cancel_at_period_end: true,
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user