如何将我的PostgreSQL数据库连接到Sveltekit并运行查询?

7

我还在学习Web开发基础知识,所以请耐心等待 :)

我正在尝试将我的Postgres数据库连接到我的Web应用程序。根据这篇文章,我已经设置了如下的hooks.js连接:

export const handle = async ({event, resolve}) => {
  event.locals = {
    user: 'me',
    host: 'localhost',
    database: 'test',
    password: 'password',
    port: 1234,
  }
  const response = await resolve(event)
  return response;
}

我现在正在尝试设置我的终端节点。如何在终端节点中访问我的数据库并设置查询?感谢您提前回复或任何见解。


https://dev59.com/c6z2oIgBc1ULPQZFbBwL#70799801 - IVO GELOV
2个回答

6

我认为你缺少了一个连接到数据库的部分。从你上面提供的代码片段来看,似乎你尝试通过局部变量传递数据库连接信息,但是你需要传递的是数据库连接本身

首先,你需要一个Postgres客户端。你可以使用任何一个你想用的,我会向你展示在这里找到的postgresjs包可能是什么样子的连接。

hooks.js

import postgres from 'postgres';

export const handle = async ({event, resolve}) => {
  const sql = postgres('postgres://username:password@host:port/database');

  event.locals = {
    sql: sql
  };
  const response = await resolve(event);
  return response;
};

您需要在连接字符串中填写数据库信息,就像上面一样,但现在您的端点将可以访问包含SQL连接的locals对象。

接下来:

yourendpoint.js

export async function get({ locals }) {
  // destructure to get the sql connection
  const { sql } = locals;

  // Do work with the connection
  // different connection libraries will do this in different ways
  // postgres.js uses tagged template literals,
  // and you pass in sql statements
  const result = await sql`SELECT name, age FROM users`;

  // Now you have a result object that contains the query response
  // Do what you need to do from here

  ... code to work with result ... 
};

您需要发送响应等其他内容的其余部分在Sveltekit文档中有记录。重要的是,您正在hooks.js文件中设置连接,然后将其与请求一起传递给端点处理程序。这样可以将设置逻辑集中在一个地方。
此外,如果您不熟悉用于JavaScript的Postgres库,请尝试一些库。postgres.js旨在简单明了,pg也是如此。您还可以升级到为您提供更多功能的库,例如sequelizeprisma
我个人非常喜欢Prisma,但我鼓励您进行实验并找到最适合自己的库。

3

我建议不要将数据库凭据放在event.locals中,因为它是用于请求特定信息的,而你的凭据与每个单独的请求无关。来自SvelteKit文档

有两个可选的钩子文件:

src/hooks.server.ts — 应用程序的服务器钩子

src/hooks.client.ts — 应用程序的客户端钩子

这些模块中的代码将在应用程序启动时运行,非常适合用于初始化数据库客户端等操作。

我从这里修改了连接方式,如下所示:

// lib/db.ts
import { Pool } from "pg";

/**
 * Create a new connection pool to the database.
 */
const pool = new Pool({
  database: import.meta.env.POSTGRES_DB || "postgres",
  user: import.meta.env.POSTGRES_USERNAME || "postgres",
  host: import.meta.env.POSTGRES_HOST || "localhost",
  port: Number(import.meta.env.POSTGRES_PORT || 5432),
});

/**
 * Connect to the PostgreSQL database.
 * @returns {Promise<import("pg").Client>} A new client from the connection pool.
 */
export const connectToDB = async () => await pool.connect();

然后,您可以将其导入到您的hooks.server.ts文件中,以便在事件中使用数据库连接。
import { connectToDB } from "$lib/db";
import type { Handle } from "@sveltejs/kit";

export const handle = (async ({ event, resolve }) => {
  const dbconn = await connectToDB();
  event.locals = { dbconn };

  const response = await resolve(event);
  dbconn.release();

  return response;
}) satisfies Handle;

1
谢谢!hooks.server.ts - 一个在服务器上运行一次的东西 - 正是我正在寻找的。我添加了一段来自Svelte文档的引用,证实这是最佳位置。 - mikemaccana

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接