basic url short functionality

This commit is contained in:
Philipp Traber
2024-09-12 10:02:27 +02:00
parent 0cebfea362
commit e882565a71
19 changed files with 1151 additions and 246 deletions
+2
View File
@@ -34,3 +34,5 @@ yarn-error.log*
# typescript # typescript
*.tsbuildinfo *.tsbuildinfo
next-env.d.ts next-env.d.ts
.env
+12
View File
@@ -0,0 +1,12 @@
services:
db:
image: postgres:16
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: postgres
ports:
- "5432:5432"
volumes:
- ./.vol_db:/var/lib/postgresql/data
+12 -1
View File
@@ -1,4 +1,15 @@
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = {}; const nextConfig = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'www.google.com',
},
]
}
};
export default nextConfig; export default nextConfig;
+720 -102
View File
File diff suppressed because it is too large Load Diff
+9 -7
View File
@@ -9,18 +9,20 @@
"lint": "next lint" "lint": "next lint"
}, },
"dependencies": { "dependencies": {
"react": "^18", "@prisma/client": "^5.18.0",
"react-dom": "^18", "next": "^15.0.0-canary.135",
"next": "14.2.6" "ua-parser-js": "^1.0.38",
"zod": "^3.23.8"
}, },
"devDependencies": { "devDependencies": {
"typescript": "^5",
"@types/node": "^20", "@types/node": "^20",
"@types/react": "^18", "@types/react": "^18",
"@types/react-dom": "^18", "@types/react-dom": "^18",
"postcss": "^8",
"tailwindcss": "^3.4.1",
"eslint": "^8", "eslint": "^8",
"eslint-config-next": "14.2.6" "eslint-config-next": "14.2.6",
"postcss": "^8",
"prisma": "^5.18.0",
"tailwindcss": "^3.4.1",
"typescript": "^5"
} }
} }
+14
View File
@@ -0,0 +1,14 @@
import { PrismaClient } from '@prisma/client';
let prisma: PrismaClient;
if (process.env.NODE_ENV === 'production') {
prisma = new PrismaClient();
} else {
if (!global.prisma) {
global.prisma = new PrismaClient();
}
prisma = global.prisma;
}
export default prisma;
+32
View File
@@ -0,0 +1,32 @@
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model URL {
url_id Int @id @default(autoincrement())
original_url String @db.Text
short_code String @unique
created_at DateTime @default(now())
expires_at DateTime?
stats Stat[] // Relation to URL_Statistics
@@index([short_code])
}
model Stat {
stat_id Int @id @default(autoincrement())
url_id Int
accessed_at DateTime @default(now())
hashed_ip String? @db.VarChar(64)
user_agent String? @db.Text
// Foreign key relation to URLs
url URL @relation(fields: [url_id], references: [url_id])
@@index([url_id])
}
+77
View File
@@ -0,0 +1,77 @@
"use server"
import { z } from "zod";
import prisma from "../../prisma/prisma";
import { revalidatePath } from "next/cache";
export async function createUrl(prevState: any, fromData: FormData){
const schema = z.object({
original_url: z.string().url().max(1000),
short_code: z.string().min(1).max(100)
});
const data = schema.safeParse({
original_url: fromData.get("original_url"),
short_code: fromData.get("short_code")
});
console.log("Data received in backend:");
console.log(data);
if (!data.success){
return {
message: "Invalid data",
error: data.error.flatten().fieldErrors
};
}
await prisma.uRL.create({
data: {
original_url: data.data.original_url,
short_code: data.data.short_code
}
});
revalidatePath("/dash");
return {
message: "URL created",
};
}
export async function deleteUrl(prevState: any, fromData: FormData){
const schema = z.object({
url_id: z.coerce.number()
});
const data = schema.safeParse({
url_id: fromData.get("url_id")
});
console.log("Data received in backend:");
console.log(data);
console.log(data.error?.flatten().fieldErrors);
if (!data.success){
return {
message: "Invalid data",
error: data.error.flatten().fieldErrors
};
}
await prisma.uRL.delete({
where: {
url_id: data.data.url_id
}
});
revalidatePath("/dash");
return {
message: "URL deleted",
};
}
+31
View File
@@ -0,0 +1,31 @@
import prisma from "../../../prisma/prisma";
import { headers } from "next/headers";
import { notFound, redirect, RedirectType } from "next/navigation";
export default async function RedirectToUrl({ params }: { params: { url_shortcode: string } }) {
const url = await prisma.uRL.findUnique({
where: {
short_code: params.url_shortcode
}
});
if (!url) {
return notFound()
}
const requestHeaders = headers();
const userAgent = requestHeaders.get('user-agent') || 'unknown';
const ip = requestHeaders.get('x-forwarded-for') || 'unknown';
await prisma.stat.create({
data: {
url_id: url.url_id,
user_agent: userAgent,
hashed_ip: ip
}
});
redirect(url.original_url);
}
+28 -23
View File
@@ -2,32 +2,37 @@
@tailwind components; @tailwind components;
@tailwind utilities; @tailwind utilities;
:root {
--foreground-rgb: 0, 0, 0;
--background-start-rgb: 214, 219, 220;
--background-end-rgb: 255, 255, 255;
}
@media (prefers-color-scheme: dark) {
:root {
--foreground-rgb: 255, 255, 255;
--background-start-rgb: 0, 0, 0;
--background-end-rgb: 0, 0, 0;
}
}
body { body {
color: rgb(var(--foreground-rgb)); @apply text-gray-300 bg-gray-900 m-10
background: linear-gradient(
to bottom,
transparent,
rgb(var(--background-end-rgb))
)
rgb(var(--background-start-rgb));
} }
@layer utilities { h1 {
.text-balance { @apply text-5xl font-bold mb-6
text-wrap: balance;
} }
h2 {
@apply text-2xl font-bold mb-4
}
.form-group {
@apply mb-6;
}
.form-field-error {
@apply border-red-500;
}
.form-label-error {
@apply text-red-500;
}
form {
@apply w-full;
}
input {
@apply w-full appearance-none bg-gray-800 border border-gray-800 text-gray-300 py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-gray-700 rounded;
}
label {
@apply block uppercase tracking-wide text-xs font-bold mb-2;
}
button {
@apply rounded bg-green-600 hover:bg-green-700 text-white py-2 px-4 disabled:opacity-50
} }
+7 -107
View File
@@ -1,113 +1,13 @@
import Image from "next/image"; import Image from "next/image";
import Link from "next/link";
export default function Home() { export default function Home() {
return ( return (
<main className="flex min-h-screen flex-col items-center justify-between p-24"> (<>
<div className="z-10 w-full max-w-5xl items-center justify-between font-mono text-sm lg:flex"> <h1>Home</h1>
<p className="fixed left-0 top-0 flex w-full justify-center border-b border-gray-300 bg-gradient-to-b from-zinc-200 pb-6 pt-8 backdrop-blur-2xl dark:border-neutral-800 dark:bg-zinc-800/30 dark:from-inherit lg:static lg:w-auto lg:rounded-xl lg:border lg:bg-gray-200 lg:p-4 lg:dark:bg-zinc-800/30"> <p>This is a url shortner</p>
Get started by editing&nbsp; <Link href="~/dash">Dashboard</Link>
<code className="font-mono font-bold">src/app/page.tsx</code> </>
</p> )
<div className="fixed bottom-0 left-0 flex h-48 w-full items-end justify-center bg-gradient-to-t from-white via-white dark:from-black dark:via-black lg:static lg:size-auto lg:bg-none">
<a
className="pointer-events-none flex place-items-center gap-2 p-8 lg:pointer-events-auto lg:p-0"
href="https://vercel.com?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
By{" "}
<Image
src="/vercel.svg"
alt="Vercel Logo"
className="dark:invert"
width={100}
height={24}
priority
/>
</a>
</div>
</div>
<div className="relative z-[-1] flex place-items-center before:absolute before:h-[300px] before:w-full before:-translate-x-1/2 before:rounded-full before:bg-gradient-radial before:from-white before:to-transparent before:blur-2xl before:content-[''] after:absolute after:-z-20 after:h-[180px] after:w-full after:translate-x-1/3 after:bg-gradient-conic after:from-sky-200 after:via-blue-200 after:blur-2xl after:content-[''] before:dark:bg-gradient-to-br before:dark:from-transparent before:dark:to-blue-700 before:dark:opacity-10 after:dark:from-sky-900 after:dark:via-[#0141ff] after:dark:opacity-40 sm:before:w-[480px] sm:after:w-[240px] before:lg:h-[360px]">
<Image
className="relative dark:drop-shadow-[0_0_0.3rem_#ffffff70] dark:invert"
src="/next.svg"
alt="Next.js Logo"
width={180}
height={37}
priority
/>
</div>
<div className="mb-32 grid text-center lg:mb-0 lg:w-full lg:max-w-5xl lg:grid-cols-4 lg:text-left">
<a
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30"
target="_blank"
rel="noopener noreferrer"
>
<h2 className="mb-3 text-2xl font-semibold">
Docs{" "}
<span className="inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none">
-&gt;
</span>
</h2>
<p className="m-0 max-w-[30ch] text-sm opacity-50">
Find in-depth information about Next.js features and API.
</p>
</a>
<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30"
target="_blank"
rel="noopener noreferrer"
>
<h2 className="mb-3 text-2xl font-semibold">
Learn{" "}
<span className="inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none">
-&gt;
</span>
</h2>
<p className="m-0 max-w-[30ch] text-sm opacity-50">
Learn about Next.js in an interactive course with&nbsp;quizzes!
</p>
</a>
<a
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30"
target="_blank"
rel="noopener noreferrer"
>
<h2 className="mb-3 text-2xl font-semibold">
Templates{" "}
<span className="inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none">
-&gt;
</span>
</h2>
<p className="m-0 max-w-[30ch] text-sm opacity-50">
Explore starter templates for Next.js.
</p>
</a>
<a
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30"
target="_blank"
rel="noopener noreferrer"
>
<h2 className="mb-3 text-2xl font-semibold">
Deploy{" "}
<span className="inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none">
-&gt;
</span>
</h2>
<p className="m-0 max-w-[30ch] text-balance text-sm opacity-50">
Instantly deploy your Next.js site to a shareable URL with Vercel.
</p>
</a>
</div>
</main>
); );
} }
+48
View File
@@ -0,0 +1,48 @@
import Image from "next/image";
import prisma from "../../../../../prisma/prisma";
import DeleteUrlForm from "@/components/forms/deleteUrlForm";
import { notFound } from "next/navigation";
export default async function DetailedStats({ params }: { params: { url_shortcode: string } }) {
const url = await prisma.uRL.findUnique({
where: {
short_code: params.url_shortcode
}
});
const stats = await prisma.stat.findMany({
where: {
url_id: url?.url_id
}
});
if (!url) {
return notFound();
}
return (
<div>
<h2>Stats</h2>
<div className="flex items-center">
<div className=" h-10 w-10 mr-4 ">
<Image src={`https://www.google.com/s2/favicons?domain=${url?.original_url}`} alt="favicon" width={100} height={100} />
</div>
<div>
<p>Shortcode: {url?.short_code}</p>
<p><a className="underline" href={url?.original_url}>{url?.original_url}</a></p>
</div>
<div className="ml-auto">
<DeleteUrlForm url_id={url?.url_id} />
</div>
</div>
{stats.map((stat) => (<div className="my-5" key={stat.stat_id}>
<p>{stat.accessed_at.toDateString()}</p>
<p>{stat.user_agent}</p>
<p>{stat.hashed_ip}</p>
</div>))}
</div>
);
}
+16
View File
@@ -0,0 +1,16 @@
// layout for dashboard
import Link from 'next/link';
import React, { ReactNode } from 'react';
export default function Dashboard({ children }: { children: ReactNode }) {
return (
<div>
<Link href="/~/dash/">
<h1>Dashboard</h1>
</Link>
{children}
</div>
);
}
+23
View File
@@ -0,0 +1,23 @@
import React from 'react';
import prisma from '@/../prisma/prisma'
import CreateUrlForm from '@/components/forms/createUrlForm';
import UrlComponent from '@/components/UrlComponent';
export default async function Dashboard() {
const urls = await prisma.uRL.findMany();
return (<>
<h2>URLs</h2>
<div>
{urls.map((url) => (
<UrlComponent key={url.url_id} url={url}/>
))}
</div>
<h2 className='mt-11'>Create URL</h2>
<CreateUrlForm/>
</>
);
}
+12
View File
@@ -0,0 +1,12 @@
"use client"
import { useFormStatus } from "react-dom";
export default function SubmitButton({children}: {children?: React.ReactNode}) {
const { pending } = useFormStatus();
return (
<button disabled={pending} type="submit">
{children?children:"Submit"}
</button>
);
}
+33
View File
@@ -0,0 +1,33 @@
import React from 'react';
import type { URL as PrismaURL } from '@prisma/client';
import DeleteUrlForm from './forms/deleteUrlForm';
import Image from 'next/image';
import Link from 'next/link';
export default function UrlComponent({ url }: { url: PrismaURL }) {
return (
<Link href={`/~/dash/${url.short_code}`}>
<div className="w-full my-3 flex items-center hover:bg-slate-600 rounded p-1">
<div className="flex-shrink-0 h-8 w-8 flex items-center justify-center mr-4">
<Image
loading='lazy'
width={100}
height={100}
src={`https://www.google.com/s2/favicons?domain=${url.original_url}`}
alt="favicon"
/>
</div>
<div>
<p className="font-bold text-lg text-white">{url.short_code}</p>
<p className="text-sm text-gray-400">{url.original_url}</p>
</div>
<div className="ml-auto">
<DeleteUrlForm url_id={url.url_id} />
</div>
</div>
</Link>
);
}
+33
View File
@@ -0,0 +1,33 @@
"use client"
import { createUrl } from "@/actions/url_actions";
import { useActionState } from "react";
import SubmitButton from "../SubmitButton";
import { error } from "console";
export default function CreateUrlForm() {
const initialState = {
message: "",
error: {}
};
const [state, formAction] = useActionState(createUrl, initialState);
console.log(state);
return (
<form action={formAction}>
<div className="form-group">
<label htmlFor='original_url'>Original URL</label>
<input type='text' name='original_url' id='original_url' className={state.error?.original_url?"border-red-400":""}/>
<p className="form-label-error">{ state.error?.original_url }</p>
</div>
<div className="form-group">
<label htmlFor='short_code'>Short Code</label>
<input type='text' name='short_code' id='short_code' className={state.error?.short_code?"border-red-400":""}/>
<p className="form-label-error">{ state.error?.short_code }</p>
</div>
<p>{state.message}</p>
<SubmitButton/>
</form>
);
}
+22
View File
@@ -0,0 +1,22 @@
"use client"
import { deleteUrl } from "@/actions/url_actions";
import { useActionState } from "react";
import SubmitButton from "../SubmitButton";
export default function DeleteUrlForm({url_id}: {url_id: number}) {
const initialState = {
message: "",
error: {}
};
const [state, formAction] = useActionState(deleteUrl, initialState);
return (
<form action={formAction}>
<input type="hidden" name="url_id" value={url_id}/>
<SubmitButton>Delete</SubmitButton>
</form>
);
}
+19 -5
View File
@@ -1,6 +1,10 @@
{ {
"compilerOptions": { "compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"], "lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true, "allowJs": true,
"skipLibCheck": true, "skipLibCheck": true,
"strict": true, "strict": true,
@@ -18,9 +22,19 @@
} }
], ],
"paths": { "paths": {
"@/*": ["./src/*"] "@/*": [
} "./src/*"
]
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "target": "ES2017"
"exclude": ["node_modules"] },
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts"
],
"exclude": [
"node_modules"
]
} }