From e27b047f65e4431ec6f863bea99dda7ea86b7321 Mon Sep 17 00:00:00 2001 From: Khairul Hidayat Date: Sat, 13 Apr 2024 16:04:32 +0700 Subject: [PATCH] feat: initial features --- .bun-version | 1 + .env.example | 2 + .gitignore | 179 +++++++++++++++++++++++++++++++++ README.md | 42 ++++++++ bun.lockb | Bin 0 -> 3461 bytes index.ts | 20 ++++ lib/database.ts | 18 ++++ lib/utils.ts | 5 + package.json | 19 ++++ routers/cebol.tsx | 63 ++++++++++++ routers/index.tsx | 29 ++++++ storage/.gitkeep | 0 tsconfig.json | 28 ++++++ types/link.ts | 7 ++ views/layouts/layout.tsx | 35 +++++++ views/pages/home.tsx | 22 ++++ views/pages/not-found.tsx | 15 +++ views/sections/create-link.tsx | 25 +++++ views/sections/links.tsx | 47 +++++++++ 19 files changed, 557 insertions(+) create mode 100644 .bun-version create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 README.md create mode 100755 bun.lockb create mode 100644 index.ts create mode 100644 lib/database.ts create mode 100644 lib/utils.ts create mode 100644 package.json create mode 100644 routers/cebol.tsx create mode 100644 routers/index.tsx create mode 100644 storage/.gitkeep create mode 100644 tsconfig.json create mode 100644 types/link.ts create mode 100644 views/layouts/layout.tsx create mode 100644 views/pages/home.tsx create mode 100644 views/pages/not-found.tsx create mode 100644 views/sections/create-link.tsx create mode 100644 views/sections/links.tsx diff --git a/.bun-version b/.bun-version new file mode 100644 index 0000000..32e7334 --- /dev/null +++ b/.bun-version @@ -0,0 +1 @@ +v1.1.3 \ No newline at end of file diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..53ed7de --- /dev/null +++ b/.env.example @@ -0,0 +1,2 @@ +# Static assets/page directory +SERVE_STATIC= diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4dba737 --- /dev/null +++ b/.gitignore @@ -0,0 +1,179 @@ +# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore + +# Logs + +logs +_.log +npm-debug.log_ +yarn-debug.log* +yarn-error.log* +lerna-debug.log* +.pnpm-debug.log* + +# Caches + +.cache + +# Diagnostic reports (https://nodejs.org/api/report.html) + +report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json + +# Runtime data + +pids +_.pid +_.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover + +lib-cov + +# Coverage directory used by tools like istanbul + +coverage +*.lcov + +# nyc test coverage + +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) + +.grunt + +# Bower dependency directory (https://bower.io/) + +bower_components + +# node-waf configuration + +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) + +build/Release + +# Dependency directories + +node_modules/ +jspm_packages/ + +# Snowpack dependency directory (https://snowpack.dev/) + +web_modules/ + +# TypeScript cache + +*.tsbuildinfo + +# Optional npm cache directory + +.npm + +# Optional eslint cache + +.eslintcache + +# Optional stylelint cache + +.stylelintcache + +# Microbundle cache + +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history + +.node_repl_history + +# Output of 'npm pack' + +*.tgz + +# Yarn Integrity file + +.yarn-integrity + +# dotenv environment variable files + +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# parcel-bundler cache (https://parceljs.org/) + +.parcel-cache + +# Next.js build output + +.next +out + +# Nuxt.js build / generate output + +.nuxt +dist + +# Gatsby files + +# Comment in the public line in if your project uses Gatsby and not Next.js + +# https://nextjs.org/blog/next-9-1#public-directory-support + +# public + +# vuepress build output + +.vuepress/dist + +# vuepress v2.x temp and cache directory + +.temp + +# Docusaurus cache and generated files + +.docusaurus + +# Serverless directories + +.serverless/ + +# FuseBox cache + +.fusebox/ + +# DynamoDB Local files + +.dynamodb/ + +# TernJS port file + +.tern-port + +# Stores VSCode versions used for testing VSCode extensions + +.vscode-test + +# yarn v2 + +.yarn/cache +.yarn/unplugged +.yarn/build-state.yml +.yarn/install-state.gz +.pnp.* + +# IntelliJ based IDEs +.idea + +# Finder (MacOS) folder config +.DS_Store + +storage/* +!.gitkeep +public/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..5915d47 --- /dev/null +++ b/README.md @@ -0,0 +1,42 @@ +# Cebol + +URL Shortener + +## Setup + +To install dependencies: + +```bash +bun install +``` + +### Development: + +```bash +bun dev +``` + +### Production: + +Build: + +```bash +bun run build +``` + +Start: + +```bash +bun run start +``` + +or with pm2 + +``` +bun install -g pm2 +pm2 start bun --name cebol -- run start +``` + +--- + +This project was created using `bun init` in bun v1.0.33. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime. diff --git a/bun.lockb b/bun.lockb new file mode 100755 index 0000000000000000000000000000000000000000..7924ad6b917f7e702266a40aec895b8aad9f5d8b GIT binary patch literal 3461 zcmd5;X;4#F6n?>gnA)bp0NO=OM8GXC3yTpWMW&^WbSzkm;?{=v5`rNK?>$hKN*EPs zl@6s8tQ{+YTB>yvMs4c~j!UuFsY@Me-I!t2TK7R}>i|6`c^Bfe#fO`I^rSm*K3ak1f=)6*Ach8`TVZCc84zcKq0RYmRj zH_azX0)8J^`@@>t^%agbei^hWa9z3W4rEvA}4v^M?Deg4j}kbFpUH}7RDC_*1;Pict1!y z2Jm@ zXUny0{|saKq&z+Uw!BcUG2;HpI2>YrlW^+k%XX9=znP^O$Dcth)wYWA zGe0$zTFVBROFH7Kn!*C!Ob*|>@AJO~3~|o$)4asSJPhitPuTWr<3}k~slhR_318Lx z*mlp_xXXi=)WOADRP)Nu<2MY9Pc0~t-6?FFIy<9g=Gaijp8HkRdxDN0+R|||e|t!C zn>7BkEU)lPwAOKU-TPVRiaz{B&OEA~Hl)&n7wbt(d|+Wf^0D)kdQm?rCr~3B-c)yxnb5Oc}e}Txz+vw%ZdvpAIKLEy;9%q!Ry&) zVxEgJzZ$ys>YM~dy0p{saLYw$(uGyieKSvnbzcx`R;}0?JUV#698Dsh(ipgFd6G0t zDJ|8H+PkrMd+VYc`fU$h>^oxOu%y+Ku5IAsC0mlSKB*a@cLwUyBW@j;)bd*EgB*VA zgt~h9)ud0SpBSawzkE$D23=A9<&2^Op_tx~n(&u$^DT4oN6JBG+oZ4r$Im+o`)!wnKeR zw6Y0!`;(Cx6aO^1^|K>A%@O(~W{2>?JS=#Lj$@6q#m4altCc2lgHB-?CRV0V$v8_M zV>gYLMam3Ti`iy3dHf-Db-N7@iv4_7;2aEs0ZpRIj?lyc^gl?j#`ylicMbLm{)Ul9 zE8u5)!GrP0fn3Og9E1yhyCsB6$XlYDtBIbUt%buy_vEF1{BWpeh%R|iv>=LB(I6?1 z0G|+LTVCq+QV}k!vg30)3Tx&ro@M( zLT1agQ7xh+FLVt>Q37^L5LVD5Pz&{cm4f1P9Smn=Ee<};^;HR~IGyJmT#Qo5GG+_M zv$?d*k(t5KcGj#!`Kna7oFbCe&=E9m&g&z-mlRMaxUoKJ4We-7+OiLLPmF+e#k)8n zqLD+Ox7imm!q>%IA9Ou2K)0AvxXbR{32+NQp;HKrq(Wr2ZK1_zdE!Al!+^$fs&I8u gl { + db.exec( + `CREATE TABLE IF NOT EXISTS links ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + alias TEXT NOT NULL UNIQUE, + url TEXT NOT NULL, + clicks INTEGER DEFAULT 0, + createdAt DATETIME DEFAULT CURRENT_TIMESTAMP + )` + ); +}; + +export default db; diff --git a/lib/utils.ts b/lib/utils.ts new file mode 100644 index 0000000..32d5ae2 --- /dev/null +++ b/lib/utils.ts @@ -0,0 +1,5 @@ +import crypto from "node:crypto"; + +export const randomChars = (length = 8) => { + return crypto.randomBytes(length / 2).toString("hex"); +}; diff --git a/package.json b/package.json new file mode 100644 index 0000000..6c517dc --- /dev/null +++ b/package.json @@ -0,0 +1,19 @@ +{ + "name": "cebol", + "module": "index.ts", + "type": "module", + "scripts": { + "dev": "bun run --watch index.ts", + "build": "bun build index.ts --outdir ./dist --minify --target=bun", + "start": "bun run dist/index.js" + }, + "devDependencies": { + "@types/bun": "latest" + }, + "peerDependencies": { + "typescript": "^5.0.0" + }, + "dependencies": { + "hono": "^4.2.3" + } +} \ No newline at end of file diff --git a/routers/cebol.tsx b/routers/cebol.tsx new file mode 100644 index 0000000..d922cca --- /dev/null +++ b/routers/cebol.tsx @@ -0,0 +1,63 @@ +import { Hono } from "hono"; +import HomePage from "../views/pages/home"; +import LinksSection from "../views/sections/links"; +import db from "../lib/database"; +import { randomChars } from "../lib/utils"; +import type { Link } from "../types/link"; + +const router = new Hono(); + +router.get("/", (c) => { + const links = db + .query("SELECT * FROM links ORDER BY id DESC") + .all() as Link[]; + return c.html(); +}); + +router.post("/", async (c) => { + let message = "Link created successfully!"; + let isSuccess = true; + + const body = (await c.req.parseBody()) as any; + const alias: string = body.alias?.length > 0 ? body.alias : randomChars(4); + const url: string = !body.url.startsWith("http") + ? `https://${body.url}` + : body.url; + const aliasUrl = `rul.sh/${alias}`; + + try { + const stmt = db.query( + "INSERT INTO links (alias, url) VALUES (?, ?) RETURNING id" + ); + const result = stmt.get(alias, url) as any; + if (!result?.id) { + } + } catch (err) { + message = (err as Error).message; + isSuccess = false; + + if (message.includes("UNIQUE constraint failed: links.alias")) { + message = "Alias is used!"; + } + } + + return c.html( +
+

{message}

+ {isSuccess && } +
+ ); +}); + +router.delete("/:id", (c) => { + const id = c.req.param("id"); + const stmt = db.query("DELETE FROM links WHERE id = ?"); + stmt.run(id); + + const links = db + .query("SELECT * FROM links ORDER BY id DESC") + .all() as Link[]; + return c.html(); +}); + +export default router; diff --git a/routers/index.tsx b/routers/index.tsx new file mode 100644 index 0000000..6abf473 --- /dev/null +++ b/routers/index.tsx @@ -0,0 +1,29 @@ +import { Hono } from "hono"; +import cebol from "./cebol"; +import db from "../lib/database"; +import type { Link } from "../types/link"; +import NotFoundPage from "../views/pages/not-found"; + +const router = new Hono(); + +router.route("/cebol", cebol); + +router.get("/:alias", (c) => { + const alias = c.req.param("alias"); + const link = db + .query("SELECT * FROM links WHERE alias = ? LIMIT 1") + .get(alias) as Link; + + if (!link) { + return c.html(, 404); + } + + db.query("UPDATE links SET clicks = clicks + 1 WHERE id = ?").run(link.id); + return c.redirect(link.url); +}); + +router.get("*", (c) => { + return c.redirect("/cebol"); +}); + +export default router; diff --git a/storage/.gitkeep b/storage/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..16631dd --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + // Enable latest features + "lib": ["ESNext"], + "target": "ESNext", + "module": "ESNext", + "moduleDetection": "force", + "jsx": "react-jsx", + "jsxImportSource": "hono/jsx", + "allowJs": true, + + // Bundler mode + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "noEmit": true, + + // Best practices + "strict": true, + "skipLibCheck": true, + "noFallthroughCasesInSwitch": true, + + // Some stricter flags (disabled by default) + "noUnusedLocals": false, + "noUnusedParameters": false, + "noPropertyAccessFromIndexSignature": false + } +} diff --git a/types/link.ts b/types/link.ts new file mode 100644 index 0000000..c1b8582 --- /dev/null +++ b/types/link.ts @@ -0,0 +1,7 @@ +export type Link = { + id: string; + alias: string; + url: string; + clicks: number; + createdAt: Date; +}; diff --git a/views/layouts/layout.tsx b/views/layouts/layout.tsx new file mode 100644 index 0000000..ffbdd2b --- /dev/null +++ b/views/layouts/layout.tsx @@ -0,0 +1,35 @@ +import type { FC, PropsWithChildren } from "hono/jsx"; + +type Props = PropsWithChildren<{ + title?: string; +}>; + +const Layout: FC = ({ children, title }) => { + return ( + + + + + + + {title || "Cebol"} + + +