Skip to content

Instantly share code, notes, and snippets.

@qvgk
Last active October 15, 2024 03:31
Show Gist options
  • Save qvgk/3bcab40b0891470448d188f4bbcc0943 to your computer and use it in GitHub Desktop.
Save qvgk/3bcab40b0891470448d188f4bbcc0943 to your computer and use it in GitHub Desktop.
HD Example Two
// Dependencies
import { Hono } from "jsr:@hono/hono";
// Create App
const app = new Hono(); // Creates a new Hono instance.
// Time Conversion Function
// This function converts seconds to a readable time.
// Ex. 312312 = 3d 14h 45m 12s
function formatTime(seconds: number): string {
if (seconds <= 0) return "0s";
const units: [number, string][] = [
[86400, "d"],
[3600, "h"],
[60, "m"],
[1, "s"],
];
let result = "";
for (const [divisor, suffix] of units) {
if (seconds >= divisor) {
const value = Math.floor(seconds / divisor);
result += `${value}${suffix} `;
seconds %= divisor;
}
}
return result.trim();
}
// Route (/)
app.get("/timeconvert", (c) => {
// Query
const query = c.req.query("seconds"); // Gets the 'seconds' query in the URL.
if (!query) {
return c.text("400 Bad Request", 400); // Returns 400 if query is missing.
}
// Convert Query to Num
const QueryAsNum = Number(query); // Changes the query from String to Number.
// Return Time
const formatted_time = formatTime(QueryAsNum); // Runs the format time function with the query.
return c.json({ // Returns JSON with success as true, and the text being the formatted time.
success: true,
text: formatted_time,
});
});
// Serve App
Deno.serve(app.fetch); // Serves the Hono instance via Deno.Serve
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment