mirror of
https://github.com/aljazceru/ditto.git
synced 2026-01-06 23:24:22 +01:00
Refactor db.ts to use kysely statements
This commit is contained in:
39
src/db/events.ts
Normal file
39
src/db/events.ts
Normal 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
27
src/db/users.ts
Normal 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 };
|
||||
Reference in New Issue
Block a user