Statusphere Feed Generator
at main 2.1 kB view raw
1import SqliteDb from 'better-sqlite3'; 2import { 3 Kysely, 4 Migrator, 5 SqliteDialect, 6 type Migration, 7 type MigrationProvider, 8} from 'kysely'; 9 10// Types 11 12export type DatabaseSchema = { 13 status: Status; 14 post: Post; 15}; 16 17export type Status = { 18 uri: string; 19 authorDid: string; 20 status: string; 21 createdAt: string; 22 indexedAt: string; 23}; 24 25export type Post = { 26 uri: string; 27 authorDid: string; 28 text: string; 29 createdAt: string; 30 indexedAt: string; 31}; 32 33// Migrations 34 35const migrations: Record<string, Migration> = {}; 36 37const migrationProvider: MigrationProvider = { 38 async getMigrations() { 39 return migrations; 40 }, 41}; 42 43migrations['001'] = { 44 async up(db: Kysely<unknown>) { 45 await db.schema 46 .createTable('status') 47 .addColumn('uri', 'varchar', (col) => col.primaryKey()) 48 .addColumn('authorDid', 'varchar', (col) => col.notNull()) 49 .addColumn('status', 'varchar', (col) => col.notNull()) 50 .addColumn('createdAt', 'varchar', (col) => col.notNull()) 51 .addColumn('indexedAt', 'varchar', (col) => col.notNull()) 52 .execute(); 53 await db.schema 54 .createTable('post') 55 .addColumn('uri', 'varchar', (col) => col.primaryKey()) 56 .addColumn('authorDid', 'varchar', (col) => col.notNull()) 57 .addColumn('text', 'varchar', (col) => col.notNull()) 58 .addColumn('createdAt', 'varchar', (col) => col.notNull()) 59 .addColumn('indexedAt', 'varchar', (col) => col.notNull()) 60 .execute(); 61 }, 62 async down(db: Kysely<unknown>) { 63 await db.schema.dropTable('status').execute(); 64 await db.schema.dropTable('post').execute(); 65 }, 66}; 67 68// APIs 69 70export const createDb = (location: string): Database => { 71 return new Kysely<DatabaseSchema>({ 72 dialect: new SqliteDialect({ 73 database: new SqliteDb(location), 74 }), 75 }); 76}; 77 78export const migrateToLatest = async (db: Database) => { 79 const migrator = new Migrator({ db, provider: migrationProvider }); 80 const { error } = await migrator.migrateToLatest(); 81 if (error) throw error; 82}; 83 84export type Database = Kysely<DatabaseSchema>;