

1
Workerweb-spawnindex.jslocationHintMongoDBConnection.js~30%~2%try{}catch{}enableSql = trueenableSql = true[[migrations]]new_classesnew_sqlite_classesworkerd.mjswrangler dev -e test --port 8787chrome://inspectO2OO2Ofetch(request)export { MongoDBConnection } from "./MongoDBConnection.js";
export default {
async fetch(request, { MONGO_DB_CONNECTION, MONGO_DB_URI }) {
// FWIW, you’ll probably want to do an auth check or similar here, to prevent wasting resources on fuzzing attacks
// We can just forward the request straight onto the Durable Object
const id = MONGO_DB_CONNECTION.idFromName(MONGO_DB_URI);
const connection = MONGO_DB_CONNECTION.get(id, { locationHint: "apac" });
return await connection.fetch(request);
}
};import { DurableObject } from "cloudflare:workers";
import mongoose from "mongoose";
export class MongoDBConnection extends DurableObject {
connection;
constructor(ctx, env) {
super(ctx, env);
this.connection = mongoose.createConnection(env.MONGO_DB_URI, {
// Decrease the selection timeout from 30s (default) to 5s, so that if something breaks, we don't wait around for it.
serverSelectionTimeoutMS: 5000,
});
}
async fetch(request) {
// Wait for the connection to become available
await this.connection.asPromise();
// Do work here
return new Response("OK");
}
}