initial commit
[browser-rts.git] / src / repository / base.ts
1 import { Knex } from 'knex';
2 import { db } from '../lib/db';
3
4 export class Repository<T> {
5         table: string;
6         db: Knex;
7         constructor(table: string) {
8                 this.table = table;
9                 this.db = db;
10         }
11
12         async Insert(data: any) {
13                 console.log('inserting', data);
14                 const row = await db<T>(this.table).insert(data, '*');
15                 return row.pop();
16         }
17
18         async FindOne(where: Record<string, any>): Promise<T> {
19                 const res = await db<T>(this.table).select('*').where(where);
20
21                 return res.pop() as T;
22         }
23
24         FindAll(where?: any) {
25                 if(where)
26                         return db<T>(this.table).select('*').where(where);
27                 else 
28                         return db<T>(this.table).select('*');
29         }
30
31         async Save(thing: Partial<T>, where?: any) {
32                 return db<T>(this.table).update(thing as any).where(where);
33         }
34
35         async Delete(where: any) {
36                 return db(this.table).where(where).delete();
37         }
38 }