INTEGRITY Документация

node-postgres (pg)

node-postgres ↗ (pg) представляет собой широко используемый драйвер PostgreSQL для приложений на Node.js. В этом примере показано, как использовать node-postgres вместе с Cloudflare Hyperdrive в приложении на Workers.

Установите node-postgres драйвер:

npm i pg@>8.16.3

При использовании TypeScript установите пакет типов:

npm i -D @types/pg

Добавьте необходимые флаги совместимости Node.js и привязку Hyperdrive в свой wrangler.jsonc файле:

{
	// 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>"

Создайте новый Client экземпляр и передайте 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 });
		}
	},
};