A simple AtProto app to read pet.mewsse.link records on my PDS.
1import { SerializePlugin } from 'kysely-plugin-serialize'
2import { Kysely, Migrator, SqliteDialect } from 'kysely'
3import SqliteDb from 'better-sqlite3'
4
5import type { Migration, MigrationProvider } from 'kysely'
6import type { Blob, LegacyBlob } from '@atcute/lexicons'
7
8export type DatabaseSchema = {
9 links: Link,
10 revs: Rev
11}
12
13export type Embed = {
14 '$type': string,
15 url?: string,
16 html?: string,
17 alt?: string
18 } | null
19
20export type Link = {
21 rkey: string,
22 url: string,
23 title: string,
24 description: string | null,
25 embed: Embed,
26 nsfw: number,
27 createdAt: string,
28}
29
30export type Rev = {
31 rkey: string,
32 createdAt: string,
33}
34
35const migrations: Record<string, Migration> = {}
36const migrationProvider: MigrationProvider = {
37 async getMigrations() {
38 return migrations
39 },
40}
41
42migrations['001'] = {
43 async up(db: Kysely<any>) {
44 await db.schema
45 .createTable('links')
46 .addColumn('rkey', 'varchar', (col) => col.primaryKey())
47 .addColumn('url', 'varchar', (col) => col.notNull())
48 .addColumn('title', 'varchar', (col) => col.notNull())
49 .addColumn('description', 'varchar')
50 .addColumn('embed', 'varchar')
51 .addColumn('nsfw', 'integer')
52 .addColumn('createdAt', 'varchar', (col) => col.notNull())
53 .execute()
54
55 await db.schema
56 .createTable('revs')
57 .addColumn('rkey', 'varchar', (col) => col.primaryKey())
58 .addColumn('createdAt', 'varchar', (col) => col.notNull())
59 .execute()
60 },
61
62 async down(db: Kysely<any>) {
63 await db.schema.dropTable('links').execute()
64 await db.schema.dropTable('rev').execute()
65 },
66}
67
68export const createDb = (location: string): Database => {
69 return new Kysely<DatabaseSchema>({
70 dialect: new SqliteDialect({
71 database: new SqliteDb(location)
72 }),
73 plugins: [
74 new SerializePlugin(),
75 ],
76 })
77}
78
79export const migrateToLatest = async (db: Database) => {
80 const migrator = new Migrator({ db, provider: migrationProvider })
81 const { error } = await migrator.migrateToLatest()
82 if (error) throw error
83}
84
85export type Database = Kysely<DatabaseSchema>