You install Kysely in a project using:
npm i kysely
Depending on the kind of database you’ll use (Postgres, MySQL, SQLite), you need to install another library.
In our case we’ll use Postgres, so we also need:
npm i pg
Now in your project create a db.ts (or db.js) file in the src folder, and add:
import { Kysely, PostgresDialect } from 'kysely'
import pg from 'pg'
const { Pool } = pg
const DATABASE_URL = process.env.DATABASE_URL
let dialect
try {
dialect = new PostgresDialect({
pool: new Pool({
connectionString: DATABASE_URL
}),
})
} catch (e) {
console.error(e)
}
export const db = new Kysely({
dialect,
})
We get the DATABASE_URL environment variable using process.env.DATABASE_URL, which is what we do in Hono.
It might differ on other frameworks, for example in Astro we do import.meta.env.DATABASE_URL.
You need to add this to the .env file if you’re working locally (and remember, you never push this “secrets file” to Git - add this to .gitignore).
Something like this, which represents the connection URL to the database (yours will differ depending on the setup):
DATABASE_URL=postgresql://postgres@127.0.0.1/database-name
Now in any file we can import the db object, which is the Kysely instance:
import { db } from './db'
and we can use it to interact with the database, running queries.
We’ll see how in the next lesson.
Lessons in this unit:
| 0: | Introduction |
| 1: | ▶︎ Installing Kysely |
| 2: | Select queries |
| 3: | Inserting data |
| 4: | Deleting data |
| 5: | Updating data |
| 6: | Joins |