Refactor db.ts to use kysely statements

This commit is contained in:
Alex Gleason
2023-08-07 00:50:12 -05:00
parent ecc9db86dd
commit 3cb5f91d3b
8 changed files with 141 additions and 110 deletions

39
src/db/events.ts Normal file
View File

@@ -0,0 +1,39 @@
import { type Filter, type Insertable } from '@/deps.ts';
import { type SignedEvent } from '@/event.ts';
import { db, type TagRow } from '../db.ts';
function insertEvent(event: SignedEvent): Promise<void> {
return db.transaction().execute(async (trx) => {
await trx.insertInto('events')
.values({
...event,
tags: JSON.stringify(event.tags),
})
.executeTakeFirst();
const tags = event.tags.reduce<Insertable<TagRow>[]>((results, tag) => {
if (['p', 'e', 'q', 'd', 't', 'proxy'].includes(tag[0])) {
results.push({
event_id: event.id,
tag: tag[0],
value_1: tag[1] || null,
value_2: tag[2] || null,
value_3: tag[3] || null,
});
}
return results;
}, []);
await trx.insertInto('tags')
.values(tags)
.execute();
});
}
function getFilter<K extends number = number>(_filter: Filter<K>) {
// TODO
}
export { getFilter, insertEvent };

27
src/db/users.ts Normal file
View File

@@ -0,0 +1,27 @@
import { type Insertable } from '@/deps.ts';
import { db, type UserRow } from '../db.ts';
/** Adds a user to the database. */
function insertUser(user: Insertable<UserRow>) {
return db.insertInto('users').values(user).execute();
}
/**
* Finds a single user based on one or more properties.
*
* ```ts
* await findUser({ username: 'alex' });
* ```
*/
function findUser(user: Partial<Insertable<UserRow>>) {
let query = db.selectFrom('users').selectAll();
for (const [key, value] of Object.entries(user)) {
query = query.where(key as keyof UserRow, '=', value);
}
return query.executeTakeFirst();
}
export { findUser, insertUser };