Skip to content

Instantly share code, notes, and snippets.

@mayankchoubey
Created October 15, 2023 03:23
Show Gist options
  • Save mayankchoubey/c4646c6c9797d9d14c054b044422f2c6 to your computer and use it in GitHub Desktop.
Save mayankchoubey/c4646c6c9797d9d14c054b044422f2c6 to your computer and use it in GitHub Desktop.
Bun - Elysia URL shortener service in PostgreSQL
import { shorten } from "./service.js";
export async function handleRequest(ctx) {
if (!(ctx.body && ctx.body.srcUrl)) {
ctx.set.status = 400;
return { errMsg: "Parameter 'srcUrl' is missing" };
}
const srcUrl = ctx.body.srcUrl;
if (srcUrl.length > 250) {
ctx.set.status = 400;
return {
errMsg: "Parameter 'srcUrl' must not be more than 250 characters",
};
}
if (!(srcUrl.startsWith("http://") || srcUrl.startsWith("https://"))) {
ctx.set.status = 400;
return { errMsg: "Parameter 'srcUrl' must start with http:// or https://" };
}
const shortenedUrl = await shorten(srcUrl);
if (!shortenedUrl) {
ctx.set.status = 500;
return { errMsg: "Failed to shorten" };
}
return { srcUrl, shortenedUrl };
}
import { DataTypes, Sequelize } from "sequelize";
const dbUser = process.env.dbUser;
const dbUserPass = process.env.dbUserPass;
const dbName = process.env.dbName;
const sequelize = new Sequelize(
`postgres://${dbUser}:${dbUserPass}@localhost:5432/${dbName}`,
{
logging: false,
pool: {
max: 10,
min: 10,
},
},
);
await sequelize.authenticate();
const ShortenedUrl = sequelize.define("shortenedurl", {
id: {
type: DataTypes.STRING,
primaryKey: true,
},
srcurl: DataTypes.STRING,
created: DataTypes.DATE,
lastaccessed: DataTypes.DATE,
}, {
timestamps: false,
});
export async function save(id, srcUrl) {
await ShortenedUrl.create({
id,
srcurl: srcUrl,
created: new Date(),
lastaccessed: new Date(),
});
return true;
}
import { Elysia } from "elysia";
import { handleRequest } from "./controller.js";
const app = new Elysia();
app.post("/shorten", handleRequest);
app.listen({
port: 3000,
});
import { nanoid } from "nanoid";
import { save } from "./db.js";
const baseUrl = "http://test.short/";
export async function shorten(srcUrl) {
if (!srcUrl) {
return;
}
const urlId = nanoid(10);
const shortenedUrl = `${baseUrl}${urlId}`;
const dbStatus = await save(urlId, srcUrl);
return dbStatus ? shortenedUrl : undefined;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment