Skip to content

Instantly share code, notes, and snippets.

@mayankchoubey
Last active June 30, 2021 21:32
Show Gist options
  • Save mayankchoubey/b6bbef0f70a92402e00f87a32571e2f1 to your computer and use it in GitHub Desktop.
Save mayankchoubey/b6bbef0f70a92402e00f87a32571e2f1 to your computer and use it in GitHub Desktop.
URL shortener - utils.ts & constants.ts
export const PORT=80;
export const ROUTE_SHORTEN='/shorten';
export const HTTP_METHOD_GET='GET';
export const HTTP_METHOD_POST='POST';
export const HEADER_LOCATION='location';
export const QUERY_PARAM_TARGET='target';
export const URL_CODE_LENGTH=8;
export const SERVICE_DOMAIN='http://sho.rt/';
import {Status} from "https://deno.land/std/http/http_status.ts";
import {HEADER_LOCATION, URL_CODE_LENGTH, SERVICE_DOMAIN} from "./constants.ts";
export function sendResponseCode(resp:any, code:number) {
resp(new Response(undefined, {status: code}));
}
export function sendResponseShortenedUrl(resp:any, shortCode:string) {
resp(new Response(JSON.stringify({shortUrl: SERVICE_DOMAIN+shortCode}),
{status: Status.OK,
headers: {[HEADER_CONTENT_TYPE]: 'application/json'}
}));
}
export async function sendResponseRedirect(resp:any, target:string) {
await resp(new Response(undefined, {
status: Status.Found,
headers: new Headers({[HEADER_LOCATION]: target})
}));
}
export function getId() {
var arr = new Uint8Array(URL_CODE_LENGTH/2)
crypto.getRandomValues(arr);
const toHex=(d:any)=>d.toString(16).padStart(2, "0");
return Array.from(arr, toHex).join('')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment