Scratch space for learning atproto app development
1import SqliteDb from 'better-sqlite3'
2import {
3 Kysely,
4 Migrator,
5 SqliteDialect,
6 Migration,
7 MigrationProvider,
8} from 'kysely'
9
10// Types
11
12export type DatabaseSchema = {
13 status: Status
14 auth_session: AuthSession
15 auth_state: AuthState
16}
17
18export type Status = {
19 authorDid: string
20 status: string
21 updatedAt: string
22 indexedAt: string
23}
24
25export type AuthSession = {
26 key: string
27 session: AuthSessionJson
28}
29
30export type AuthState = {
31 key: string
32 state: AuthStateJson
33}
34
35type AuthStateJson = string
36
37type AuthSessionJson = string
38
39// Migrations
40
41const migrations: Record<string, Migration> = {}
42
43const migrationProvider: MigrationProvider = {
44 async getMigrations() {
45 return migrations
46 },
47}
48
49migrations['001'] = {
50 async up(db: Kysely<unknown>) {
51 await db.schema
52 .createTable('status')
53 .addColumn('authorDid', 'varchar', (col) => col.primaryKey())
54 .addColumn('status', 'varchar', (col) => col.notNull())
55 .addColumn('updatedAt', 'varchar', (col) => col.notNull())
56 .addColumn('indexedAt', 'varchar', (col) => col.notNull())
57 .execute()
58 await db.schema
59 .createTable('auth_session')
60 .addColumn('key', 'varchar', (col) => col.primaryKey())
61 .addColumn('session', 'varchar', (col) => col.notNull())
62 .execute()
63 await db.schema
64 .createTable('auth_state')
65 .addColumn('key', 'varchar', (col) => col.primaryKey())
66 .addColumn('state', 'varchar', (col) => col.notNull())
67 .execute()
68 },
69 async down(db: Kysely<unknown>) {
70 await db.schema.dropTable('auth_state').execute()
71 await db.schema.dropTable('auth_session').execute()
72 await db.schema.dropTable('status').execute()
73 },
74}
75
76// APIs
77
78export const createDb = (location: string): Database => {
79 return new Kysely<DatabaseSchema>({
80 dialect: new SqliteDialect({
81 database: new SqliteDb(location),
82 }),
83 })
84}
85
86export const migrateToLatest = async (db: Database) => {
87 const migrator = new Migrator({ db, provider: migrationProvider })
88 const { error } = await migrator.migrateToLatest()
89 if (error) throw error
90}
91
92export type Database = Kysely<DatabaseSchema>