External Dependencies
In Infragate, functions can leverage external dependencies to extend their capabilities and perform complex operations.
The following is an example of a custom function that connects to a MongoDB database to retrieve and describe the schema of a specified database.
import { MongoClient } from "npm:mongodb@6.1.0";
interface Request { database: string; // Database name sampleSize?: number; // Number of documents to sample per collection (default = 10)}
const username = process.env.MONGODB_USERNAME;const password = process.env.MONGODB_PASSWORD;const hostname = process.env.MONGODB_HOSTNAME;
// Connection URIconst uri = `mongodb+srv://${username}:${password}@${hostname}/?retryWrites=true&w=majority&appName=Cluster0`;
let client: MongoClient = undefined;
export async function handler(request: Request): Promise<any> { const { database, sampleSize = 10 } = request;
if (!database) { return { error: "Missing 'database' field in request." }; }
try {
if (!client) { client = new MongoClient(uri); await client.connect(); console.log("Connected to MongoDB cluster"); }
const db = client.db(database); const collections = await db.listCollections().toArray(); const schemaInfo: Record<string, Record<string, string>> = {};
for (const col of collections) { const collection = db.collection(col.name); const docs = await collection.find({}).limit(sampleSize).toArray();
const fieldTypes: Record<string, Set<string>> = {};
// Only inspect top-level fields for (const doc of docs) { for (const [key, value] of Object.entries(doc)) { const type = Array.isArray(value) ? "array" : value === null ? "null" : typeof value === "object" ? "object" : typeof value;
if (!fieldTypes[key]) fieldTypes[key] = new Set(); fieldTypes[key].add(type); } }
// Merge all observed types into a string representation const mergedTypes: Record<string, string> = {}; for (const [field, types] of Object.entries(fieldTypes)) { mergedTypes[field] = Array.from(types).join(" | "); }
schemaInfo[col.name] = mergedTypes; }
return { database, schema: schemaInfo, }; } catch (error) { console.error("Error describing schema:", error); return { error: error.message }; }}