@developers-joyride/shortify
Version:
High performance URL shortener library with multi-database support (MongoDB, SQLite, PostgreSQL, MySQL)
56 lines (50 loc) • 1.26 kB
text/typescript
import mongoose, { Document, Schema } from "mongoose";
export interface IUrl extends Document {
urlId: string; // The shortened URL ID
originalUrl: string; // The original long URL
shortUrl: string; // The complete shortened URL
clicks: number; // Track number of clicks/redirects
createdAt: Date; // When the shortened URL was created
expiresAt?: Date; // Optional expiration date
}
const urlSchema = new Schema<IUrl>(
{
urlId: {
type: String,
required: true,
unique: true,
},
originalUrl: {
type: String,
required: true,
},
shortUrl: {
type: String,
required: true,
},
clicks: {
type: Number,
required: true,
default: 0,
},
createdAt: {
type: Date,
default: Date.now,
},
expiresAt: {
type: Date,
default: null,
},
},
{
timestamps: true,
}
);
// Add indexes for high-performance lookups
urlSchema.index({ originalUrl: 1 });
// Export the model
export const Url = mongoose.model<IUrl>("Url", urlSchema);
// Function to create a model with custom collection name
export function createUrlModel(collectionName: string = "urls") {
return mongoose.model<IUrl>(collectionName, urlSchema, collectionName);
}