Recipe: Cloudflare Workers
Setup
typescript
// src/db/schemas.ts
import { defineSchema, s } from "mondel";
export const userSchema = defineSchema("users", {
timestamps: true,
fields: {
email: s.string().required().email(),
name: s.string(),
},
});
export const schemas = [userSchema] as const;typescript
// src/db/client.ts
import { createClient, type SchemasToClient } from "mondel";
import { schemas } from "./schemas";
export type DbClient = SchemasToClient<typeof schemas>;
// Module scope: cheap factory, no TCP yet
export const connect = createClient({
serverless: true,
schemas,
validation: "strict",
});typescript
// src/index.ts
import { connect } from "./db/client";
export interface Env {
MONGODB_URI: string;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const db = await connect(env.MONGODB_URI, { maxPoolSize: 5 });
try {
if (request.method === "GET") {
const users = await db.users.findMany({}, { limit: 50 });
return Response.json(users);
}
return new Response("Method not allowed", { status: 405 });
} finally {
await db.close();
}
},
};Practices
- Keep the factory at module scope; connect inside
fetch. - Pass URI from secrets/bindings, never hardcode.
- Prefer Atlas with SRV strings.
- Push indexes from CI, not from the Worker.
- Tune
maxPoolSizefor your concurrency and Atlas tier.
