commit e27b047f65e4431ec6f863bea99dda7ea86b7321 Author: Khairul Hidayat Date: Sat Apr 13 16:04:32 2024 +0700 feat: initial features 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 0000000..7924ad6 Binary files /dev/null and b/bun.lockb differ diff --git a/index.ts b/index.ts new file mode 100644 index 0000000..5c769ee --- /dev/null +++ b/index.ts @@ -0,0 +1,20 @@ +import { Hono } from "hono"; +import { serveStatic } from "hono/bun"; +import router from "./routers/index"; +import { initDb } from "./lib/database"; + +initDb(); + +const app = new Hono(); + +if (process.env.SERVE_STATIC) { + app.use( + serveStatic({ + root: process.env.SERVE_STATIC, + }) + ); +} + +app.route("/", router); + +export default app; diff --git a/lib/database.ts b/lib/database.ts new file mode 100644 index 0000000..96298c9 --- /dev/null +++ b/lib/database.ts @@ -0,0 +1,18 @@ +import { Database } from "bun:sqlite"; + +const dbPath = process.cwd() + "/storage/database.sqlite"; +const db = new Database(dbPath); + +export const initDb = () => { + 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"} + + +