Connect, collaborate, and grow with a community of TypeScript developers
refactor: improve URL shortener form (#1556)
Ayush Kumar Yadav144e48963d76
diff --git a/apps/web/src/app/share/[slug]/page.tsx b/apps/web/src/app/share/[slug]/page.tsxindex a33abc82..1547928e 100644--- a/apps/web/src/app/share/[slug]/page.tsx+++ b/apps/web/src/app/share/[slug]/page.tsx@@ -10,11 +10,12 @@ interface Props {export default async function Page({ params }: Props) {const { slug } = params;- const longURL = await getLongURL(slug);+ const url = await getLongURL(slug);- if (!longURL) return notFound();+ // If the URL does not exist or has expired, return a 404+ if (!url || (url.expiresAt && url.expiresAt <= new Date())) return notFound();await updateClick(slug);- return permanentRedirect(longURL);+ return permanentRedirect(url.originalUrl);}diff --git a/apps/web/src/app/share/_actions/create-url-with-slug/index.ts b/apps/web/src/app/share/_actions/create-url-with-slug/index.tsindex fa3246c6..791295b3 100644--- a/apps/web/src/app/share/_actions/create-url-with-slug/index.ts+++ b/apps/web/src/app/share/_actions/create-url-with-slug/index.ts@@ -5,7 +5,12 @@ import { getBaseUrl } from '~/utils/getBaseUrl';import { THREE_MONTHS } from '../increment-time';import { isAdmin } from '~/utils/auth-guards';-export async function createShortURLWithSlug(url: string, slug: string): Promise<string | null> {+export async function createShortURLWithSlug(+ url: string,+ slug: string,+ expiresAt = new Date(Date.now() + THREE_MONTHS),+ overwrite = false,+): Promise<string | null> {const session = await auth();const baseURL = getBaseUrl();if (!session) {@@ -23,20 +28,22 @@ export async function createShortURLWithSlug(url: string, slug: string): Promise},});- if (existingSlug) {+ if (existingSlug && !overwrite) {return null;}- await prisma.shortURL.create({- data: {+ await prisma.shortURL.upsert({+ where: {+ shortUrlSlug: slug,+ },+ update: {+ originalUrl: url,+ expiresAt,+ },+ create: {shortUrlSlug: slug,originalUrl: url,- expiresAt: new Date(Date.now() + THREE_MONTHS),- user: {- connect: {- id: session.user.id,- },- },+ expiresAt,},});diff --git a/apps/web/src/app/share/_actions/get-long-url/index.ts b/apps/web/src/app/share/_actions/get-long-url/index.tsindex b22ed7ed..9dabde46 100644--- a/apps/web/src/app/share/_actions/get-long-url/index.ts+++ b/apps/web/src/app/share/_actions/get-long-url/index.ts@@ -1,13 +1,12 @@import { prisma } from '@repo/db';+import type { ShortURL } from '@repo/db/types';-export async function getLongURL(slug: string): Promise<string | null> {+export async function getLongURL(slug: string): Promise<ShortURL | null> {const url = await prisma.shortURL.findUnique({where: {shortUrlSlug: slug,},});- if (url) {- return url.originalUrl;- }- return null;++ return url;}diff --git a/apps/web/src/app/share/_actions/increment-time.ts b/apps/web/src/app/share/_actions/increment-time.tsindex ede08459..1dab8fe5 100644--- a/apps/web/src/app/share/_actions/increment-time.ts+++ b/apps/web/src/app/share/_actions/increment-time.ts@@ -6,3 +6,5 @@ export const ONE_MONTH =30; // days (1 month)export const THREE_MONTHS = ONE_MONTH * 3;++export const ONE_YEAR = ONE_MONTH * 12;diff --git a/apps/web/src/app/share/_components/greet-user.tsx b/apps/web/src/app/share/_components/greet-user.tsxindex b2d44175..5e8dbe56 100644--- a/apps/web/src/app/share/_components/greet-user.tsx+++ b/apps/web/src/app/share/_components/greet-user.tsx@@ -3,7 +3,7 @@ import { auth } from '~/server/auth';export async function GreetUser() {const session = await auth();return (- <div className="flex flex-col items-center justify-center">+ <div className="flex flex-col items-center justify-center text-sm"><p>Welcome <span className="font-semibold">@{session?.user.name}</span></p>diff --git a/apps/web/src/app/share/_components/url-shortner-form.tsx b/apps/web/src/app/share/_components/url-shortener-form.tsxsimilarity index 52%rename from apps/web/src/app/share/_components/url-shortner-form.tsxrename to apps/web/src/app/share/_components/url-shortener-form.tsxindex 28e4c4d8..6ebda671 100644--- a/apps/web/src/app/share/_components/url-shortner-form.tsx+++ b/apps/web/src/app/share/_components/url-shortener-form.tsx@@ -17,26 +17,34 @@ import { z } from 'zod';import { useToast } from '@repo/ui/components/use-toast';import { createShortURLWithSlug } from '../_actions/create-url-with-slug';import { createShortURL } from '../_actions/create-url';-import { Clipboard, ExternalLink } from '@repo/ui/icons';-import { getBaseUrl } from '~/utils/getBaseUrl';+import { Clipboard, ExternalLink, Calendar as CalendarIcon } from '@repo/ui/icons';+import { format } from 'date-fns';+import { cn } from '@repo/ui/cn';+import { Calendar } from '@repo/ui/components/calendar';+import { Popover, PopoverContent, PopoverTrigger } from '@repo/ui/components/popover';+import { Checkbox } from '@repo/ui/components/checkbox';+import { ONE_YEAR, THREE_MONTHS } from '../_actions/increment-time';const FormSchema = z.object({url: z.string().url({message: 'Please enter a valid URL e.g. https://typehero.dev',}),slug: z.string().optional(),+ expireAt: z.date().optional(),+ overwrite: z.boolean().default(false).optional(),});-export function URLShortnerForm() {+export function URLShortenerForm() {const [shortURL, setShortURL] = React.useState<string | null>(null);const { toast } = useToast();- const baseURL = `${getBaseUrl()}/share`;const form = useForm<z.infer<typeof FormSchema>>({mode: 'onChange',resolver: zodResolver(FormSchema),defaultValues: {url: '',slug: '',+ expireAt: new Date(Date.now() + THREE_MONTHS),+ overwrite: true,},});@@ -55,28 +63,40 @@ export function URLShortnerForm() {async function onSubmit(data: z.infer<typeof FormSchema>) {setShortURL(null);if (data.slug && data.slug.length > 0) {- const shortURL = await createShortURLWithSlug(data.url, data.slug);- if (shortURL) {- toast({- title: 'Short URL created',- description: shortURL,- variant: 'success',- });- setShortURL(shortURL);- } else if (shortURL === null) {- toast({- title: `Slug '/${data.slug}' already exists`,- description: 'Please try another slug',- variant: 'destructive',- });- } else+ try {+ const shortURL = await createShortURLWithSlug(+ data.url,+ data.slug,+ data.expireAt,+ data.overwrite,+ );+ if (shortURL) {+ toast({+ title: 'Short URL created',+ description: shortURL,+ variant: 'success',+ });+ setShortURL(shortURL);+ } else {+ toast({+ title: `Slug '/${data.slug}' already exists`,+ description: 'Please try another slug',+ variant: 'destructive',+ });+ }+ } catch (error) {toast({title: 'Something went wrong',description: 'Error creating short URL',variant: 'destructive',});+ }} else {- const shortURL = await createShortURL(data.url);+ // create short url with auto-generated slug+ const shortURL = await createShortURL(data.url, {+ expiresAt: data.expireAt,+ forceNewUrl: data.overwrite,+ });if (shortURL) {toast({title: 'Short URL created',@@ -123,8 +143,8 @@ export function URLShortnerForm() {<FormLabel>Custom Slug (Optional)</FormLabel><FormControl><div className="flex items-center">- <p className="border-r-none rounded-l-lg border border-slate-400 bg-slate-100 p-[5.5px] px-3 text-lg dark:border-slate-800 dark:bg-slate-800">- {baseURL}/+ <p className="border-r-none text-from-foreground/50 rounded-l-lg border border-slate-400 bg-slate-100 p-[5.5px] px-3 font-light dark:border-slate-800 dark:bg-slate-800">+ share/</p><Inputplaceholder="virus-link"@@ -138,7 +158,63 @@ export function URLShortnerForm() {</FormItem>)}/>-+ <FormField+ control={form.control}+ name="expireAt"+ render={({ field }) => (+ <FormItem className="flex flex-col">+ <FormLabel>Expires At</FormLabel>+ <Popover>+ <PopoverTrigger asChild>+ <FormControl>+ <Button+ variant="outline"+ className={cn(+ 'w-[240px] pl-3 text-left font-normal',+ !field.value && 'text-muted-foreground',+ )}+ >+ {field.value ? format(field.value, 'PPP') : <span>Expires At</span>}+ <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />+ </Button>+ </FormControl>+ </PopoverTrigger>+ <PopoverContent className="w-auto p-0" align="start">+ <Calendar+ mode="single"+ selected={field.value}+ onSelect={field.onChange}+ disabled={(date) =>+ date < new Date() || date > new Date(Date.now() + ONE_YEAR * 2)+ }+ initialFocus+ />+ </PopoverContent>+ </Popover>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="overwrite"+ render={({ field }) => (+ <FormItem className="flex flex-row items-start space-x-3 space-y-0 rounded-md border p-4">+ <FormControl>+ <Checkbox+ checked={field.value}+ onCheckedChange={(checked: boolean) => field.onChange(checked)}+ />+ </FormControl>+ <div className="space-y-1 leading-none">+ <FormLabel>Overwrite existing url</FormLabel>+ <FormDescription>+ It will overwrite the url, if the slug already exists.+ </FormDescription>+ </div>+ </FormItem>+ )}+ /><Buttondisabled={!form.formState.isDirty || !form.formState.isValid || form.formState.isSubmitting@@ -151,7 +227,7 @@ export function URLShortnerForm() {</Button>{shortURL ? (<div className="flex w-full flex-col items-center gap-2 md:flex-row">- <div className="flex-grow rounded-xl border border-green-900 px-4 py-1.5">+ <div className="border-primary flex-grow rounded-xl border px-4 py-1.5"><span className="text-muted-foreground mr-1 text-sm">Short URL: </span><span className="text-sm">{shortURL}</span></div>@@ -160,10 +236,10 @@ export function URLShortnerForm() {<Clipboard className="mr-1 h-4 w-4" />Copy</Button>- <a href={shortURL}>+ <a href={shortURL} className="flex-shrink-0" target="_blank" rel="noopener"><Button size="sm" type="button" variant="link">Test URL- <ExternalLink className="ml-1 h-4 w-4" />+ <ExternalLink className="ml-1 h-4 w-4 flex-shrink-0" /></Button></a></div>diff --git a/apps/web/src/app/share/page.tsx b/apps/web/src/app/share/page.tsxindex 405679fc..591ff83c 100644--- a/apps/web/src/app/share/page.tsx+++ b/apps/web/src/app/share/page.tsx@@ -1,24 +1,27 @@import { isAdmin } from '~/utils/auth-guards';import { GreetUser } from './_components/greet-user';-import { URLShortnerForm } from './_components/url-shortner-form';+import { URLShortenerForm } from './_components/url-shortener-form';import { auth } from '~/server/auth';import { notFound } from 'next/navigation';+export const metadata = {+ title: 'URL Shortener | TypeHero - Admin',+ description: '.',+};+export default async function Home() {const session = await auth();if (!isAdmin(session)) {return notFound();}return (- <main className="relative flex h-screen w-screen items-center justify-center">- <div className="relative space-y-2 p-2">- <div className="z-10 rounded-xl border p-6 shadow">- <h1 className="text-primary/50 rounded-2xl p-4 text-2xl font-bold md:text-5xl">- TypeHero URL Shortner- </h1>- <GreetUser />- <URLShortnerForm />- </div>+ <main className="relative flex w-screen items-center justify-center">+ <div className="w-full max-w-xl rounded-xl border p-6 shadow">+ <h1 className="text-primary rounded-2xl p-1 text-center text-lg font-bold md:text-xl">+ TypeHero URL Shortener+ </h1>+ <GreetUser />+ <URLShortenerForm /></div></main>);diff --git a/apps/web/src/components/Navigation/index.tsx b/apps/web/src/components/Navigation/index.tsxindex ad053a62..62ffe885 100644--- a/apps/web/src/components/Navigation/index.tsx+++ b/apps/web/src/components/Navigation/index.tsx@@ -80,7 +80,7 @@ export async function Navigation() {{isAdminOrMod ? (<NavLink title="Challenge Playground" href="/challenge-playground" />) : null}- {isAdminRole ? <NavLink title="URL Shortner" href="/share" /> : null}+ {isAdminRole ? <NavLink title="URL Shortener" href="/share" /> : null}<SignOutLink className="px-0" /></>) : (@@ -211,7 +211,7 @@ async function LoginButton({<a className="block" href="/share"><DropdownMenuItem className="focus:bg-accent rounded-lg p-2 duration-300 focus:outline-none dark:hover:bg-neutral-700/50"><ExternalLink className="mr-2 h-4 w-4" />- <span>URL Shortner</span>+ <span>URL Shortener</span></DropdownMenuItem></a>) : null}