Matthew Raymer
1 year ago
5 changed files with 97 additions and 24 deletions
@ -0,0 +1,58 @@ |
|||
import { Database } from 'sqlite3'; |
|||
|
|||
export class DBService { |
|||
private db: Database; |
|||
|
|||
constructor() { |
|||
this.db = new Database('subscriptions.db', (err) => { |
|||
if (err) { |
|||
console.error("Failed to connect to the database:", err); |
|||
return; |
|||
} |
|||
console.log("Connected to SQLite database"); |
|||
this.createTable(); |
|||
}); |
|||
} |
|||
|
|||
private createTable() { |
|||
const createSubscriptionsTableSQL = ` |
|||
CREATE TABLE IF NOT EXISTS subscriptions ( |
|||
id INTEGER PRIMARY KEY AUTOINCREMENT, |
|||
endpoint TEXT NOT NULL, |
|||
keys_p256dh TEXT NOT NULL, |
|||
keys_auth TEXT NOT NULL |
|||
); |
|||
`;
|
|||
|
|||
this.db.run(createSubscriptionsTableSQL, (err) => { |
|||
if (err) throw err; |
|||
console.log("Subscriptions table ready"); |
|||
}); |
|||
} |
|||
|
|||
saveSubscription(endpoint: string, keys_p256dh: string, keys_auth: string) { |
|||
return new Promise<void>((resolve, reject) => { |
|||
const insertSQL = `INSERT INTO subscriptions (endpoint, keys_p256dh, keys_auth) VALUES (?, ?, ?)`; |
|||
this.db.run(insertSQL, [endpoint, keys_p256dh, keys_auth], function(err) { |
|||
if (err) { |
|||
reject(new Error(`Failed to insert subscription: ${err.message}`)); |
|||
return; |
|||
} |
|||
resolve(); |
|||
}); |
|||
}); |
|||
} |
|||
|
|||
getSubscriptions(): Promise<Array<any>> { |
|||
return new Promise((resolve, reject) => { |
|||
const selectSQL = `SELECT * FROM subscriptions`; |
|||
this.db.all(selectSQL, [], (err, rows) => { |
|||
if (err) { |
|||
reject(new Error(`Failed to retrieve subscriptions: ${err.message}`)); |
|||
return; |
|||
} |
|||
resolve(rows); |
|||
}); |
|||
}); |
|||
} |
|||
} |
@ -0,0 +1,29 @@ |
|||
import { DBService } from './db.js'; |
|||
|
|||
export interface Subscription { |
|||
endpoint: string; |
|||
keys: { |
|||
p256dh: string; |
|||
auth: string; |
|||
}; |
|||
} |
|||
|
|||
export class SubscriptionService { |
|||
private dbService: DBService; |
|||
|
|||
constructor() { |
|||
this.dbService = new DBService(); |
|||
} |
|||
|
|||
async addSubscription(subscription: Subscription): Promise<void> { |
|||
await this.dbService.saveSubscription( |
|||
subscription.endpoint, |
|||
subscription.keys.p256dh, |
|||
subscription.keys.auth |
|||
); |
|||
} |
|||
|
|||
async fetchSubscriptions(): Promise<Subscription[]> { |
|||
return this.dbService.getSubscriptions(); |
|||
} |
|||
} |
@ -1,18 +0,0 @@ |
|||
export type Subscription = { |
|||
endpoint: string; |
|||
keys: { |
|||
p256dh: string; |
|||
auth: string; |
|||
}; |
|||
}; |
|||
|
|||
let subscriptions: Subscription[] = []; |
|||
|
|||
export function saveSubscription(sub: Subscription) { |
|||
subscriptions.push(sub); |
|||
} |
|||
|
|||
export function getSubscriptions(): Subscription[] { |
|||
return subscriptions; |
|||
} |
|||
|
Loading…
Reference in new issue