Kysely
Kysely 是一个 类型安全
和 自动完成友好
的 TypeScript SQL 查询构造器。
它允许开发人员使用流畅的 API 构建 SQL 查询语句。它还有助于利用 TypeScript 检测查询中的错误。
一个小示例
在接下来的示例中,我们使用 Kysely 查询构造器来从数据库中获取用户信息:
import { Kysely, PostgresDialect } from 'kysely';
interface User { id: number; name: string; email: string;}
interface Post { id: number; title: string; content: string; authorId: number;}
interface DB { users: User; posts: Post;}
const db = new Kysely < DB > ({ dialect: new PostgresDialect({ pool: new Pool({ host: process.env.DATABASE_HOST, database: process.env.DATABASE_DB, user: process.env.DATABASE_USER, password: process.env.DATABASE_PASSWORD, port: Number(process.env.DATABASE_PORT), }), }),});
const user = db .selectFrom('users') .where('id', 1) .select(['id', 'name', 'email']) .executeTakeFirst();
Kysely 使用 DB
接口来输入查询结果。因此,TypeScript 将 user
变量定义为 User | undefined
(因为查询可能返回空结果)。
Kysely 会将查询结果以类型安全的方式返回。例如,如果我们尝试去查询一个在 user
类型中不存在的字段 foo
,则会出现 TypeScript 错误:
const user = db .selectFrom('users') .where('id', 1) // Type Error: Argument of type 'string[]' is not assignable to parameter of type 'SelectExpression<DB, "users">'. .select(['id', 'name', 'email', 'foo']) .executeTakeFirst();
错误消息不是很清楚,但它有助于检测错误并防止运行时错误。
更多的特性在视频中呈现
实用资源
- Kysely Docs https://kysely.dev/docs/intro
- Kysely GitHub https://github.com/kysely-org/kysely
- Kysely API Docs https://kysely-org.github.io/kysely-apidoc/
- Kysely Code Examples https://kysely.dev/docs/category/examples