INTEGRITY Dokumentace

node-postgres (pg)

node-postgres ↗ (pg) je široce používaný ovladač PostgreSQL pro aplikace Node.js. Tento příklad ukazuje, jak použít node-postgres s Cloudflare Hyperdrive v aplikaci Workers.

Nainstalujte node-postgres ovladač:

npm i pg@>8.16.3

Pokud používáte TypeScript, nainstalujte balíček typů:

npm i -D @types/pg

Přidejte potřebné příznaky kompatibility s Node.js a vazbu Hyperdrive do svého wrangler.jsonc soubor:

{
	// required for database drivers to function
	"compatibility_flags": [
		"nodejs_compat"
	],
	// Set this to today's date
	"compatibility_date": "2026-08-28",
	"hyperdrive": [
		{
			"binding": "HYPERDRIVE",
			"id": "<your-hyperdrive-id-here>"
		}
	]
}
compatibility_flags = [ "nodejs_compat" ]
# Set this to today's date
compatibility_date = "2026-08-28"

[[hyperdrive]]
binding = "HYPERDRIVE"
id = "<your-hyperdrive-id-here>"

Vytvořte nový Client instance a předejte Hyperdrive connectionString:

// filepath: src/index.ts
import { Client } from "pg";

export default {
	async fetch(
		request: Request,
		env: Env,
		ctx: ExecutionContext,
	): Promise<Response> {
		// Create a new client instance for each request. Hyperdrive maintains the
		// underlying database connection pool, so creating a new client is fast.
		const client = new Client({
			connectionString: env.HYPERDRIVE.connectionString,
		});

		try {
			// Connect to the database
			await client.connect();

			// Perform a simple query
			const result = await client.query("SELECT * FROM pg_tables");

			return Response.json({
				success: true,
				result: result.rows,
			});
		} catch (error: any) {
			console.error("Database error:", error.message);

			return new Response("Internal error occurred", { status: 500 });
		}
	},
};