UNPKG

@developers-joyride/shortify

Version:

High performance URL shortener library with multi-database support (MongoDB, SQLite, PostgreSQL, MySQL)

118 lines (95 loc) 2.98 kB
import Shortify, { DatabaseConfig } from "../src/index"; // Example 1: Using MongoDB (original way - backward compatible) async function exampleWithMongoDB() { console.log("=== MongoDB Example ==="); const shortify = Shortify.createWithMongo( "https://short.ly", "mongodb://localhost:27017/shortify", { maxRetries: 3, retryDelay: 2000 } ); await shortify.connect(); const result = await shortify.shorten( "https://www.example.com/very-long-url-that-needs-shortening" ); console.log("Shortened URL:", result.shortUrl); const originalUrl = await shortify.resolve(result.urlId); console.log("Original URL:", originalUrl); await shortify.disconnect(); } // Example 2: Using SQLite async function exampleWithSQLite() { console.log("\n=== SQLite Example ==="); const dbConfig: DatabaseConfig = { type: "sqlite", database: "./shortify.db", maxRetries: 3, retryDelay: 2000, }; const shortify = new Shortify("https://short.ly", dbConfig); await shortify.connect(); const result = await shortify.shorten( "https://www.example.com/another-long-url" ); console.log("Shortened URL:", result.shortUrl); const stats = await shortify.getStats(result.urlId); console.log("URL Stats:", stats); await shortify.disconnect(); } // Example 3: Using MongoDB with new configuration format async function exampleWithMongoDBNew() { console.log("\n=== MongoDB (New Format) Example ==="); const dbConfig: DatabaseConfig = { type: "mongodb", connectionString: "mongodb://localhost:27017/shortify", maxRetries: 3, retryDelay: 2000, }; const shortify = new Shortify("https://short.ly", dbConfig); await shortify.connect(); const result = await shortify.shorten( "https://www.example.com/third-long-url", { urlLength: 6, expiresInDays: 30, } ); console.log("Shortened URL:", result.shortUrl); console.log("Expires at:", result.expiresAt); await shortify.disconnect(); } // Example 4: Error handling async function exampleWithErrorHandling() { console.log("\n=== Error Handling Example ==="); try { // This will throw an error because PostgreSQL adapter is not implemented yet const dbConfig: DatabaseConfig = { type: "postgresql", host: "localhost", port: 5432, database: "shortify", username: "user", password: "password", }; const shortify = new Shortify("https://short.ly", dbConfig); } catch (error) { console.log( "Expected error:", error instanceof Error ? error.message : String(error) ); } } // Run all examples async function runExamples() { try { await exampleWithMongoDB(); await exampleWithSQLite(); await exampleWithMongoDBNew(); await exampleWithErrorHandling(); } catch (error) { console.error("Error running examples:", error); } } // Only run if this file is executed directly if (require.main === module) { runExamples(); }