Skip to content

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

  1. Keep the factory at module scope; connect inside fetch.
  2. Pass URI from secrets/bindings, never hardcode.
  3. Prefer Atlas with SRV strings.
  4. Push indexes from CI, not from the Worker.
  5. Tune maxPoolSize for your concurrency and Atlas tier.

Released under the MIT License. · llms.txt