-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpush-subscription.repository.ts
131 lines (115 loc) · 3.57 KB
/
push-subscription.repository.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import * as retry from 'async-retry'
import {injectable, postConstruct} from 'inversify'
import {createPool, Pool, RowDataPacket} from 'mysql2/promise'
import {PushSubscription} from 'web-push'
import {Config} from '@libs/config'
import {InternalPushSubscription} from '@libs/schema'
import {Id, Timestamp} from '@libs/types'
enum Column {
Id = 'id',
Endpoint = 'endpoint',
AuthKey = 'auth_key',
P256dhKey = 'p256hd_key',
UserId = 'user_id',
SubscribedAt = 'subscribed_at',
}
@injectable()
export class PushSubscriptionRepository {
private pool!: Pool
private isInitialized = false
private isConnected = false
private tableName = 'push_subscriptions'
constructor(private config: Config) {}
@postConstruct()
async initialize() {
this.pool = createPool({
host: this.config.get('MYSQL_HOST'),
port: Number(this.config.get('MYSQL_PORT')),
user: this.config.get('MYSQL_USER'),
password: this.config.get('MYSQL_PASSWORD'),
database: this.config.get('MYSQL_DATABASE'),
})
this.pool.on('connection', connection => {
this.isConnected = true
connection.on('end', () => {
this.isConnected = false
this.isInitialized = false
})
})
const upsertEventsTable = `
CREATE TABLE IF NOT EXISTS \`${this.tableName}\` (
${Column.Id} VARCHAR(255) NOT NULL,
${Column.Endpoint} VARCHAR(255) NOT NULL,
${Column.AuthKey} VARCHAR(255) NOT NULL,
${Column.P256dhKey} VARCHAR(255) NOT NULL,
${Column.UserId} VARCHAR(255) NOT NULL,
${Column.SubscribedAt} BIGINT NOT NULL,
PRIMARY KEY (${Column.Id})
) ENGINE=InnoDB;
`
const connection = await this.getConnection(true)
await connection.query(upsertEventsTable)
connection.release()
this.isInitialized = true
console.log('push subscription repository initialized')
}
// TODO check userId
async create(sub: PushSubscription, userId: string) {
const query = `
INSERT INTO \`${this.tableName}\`
(${Column.Id}, ${Column.Endpoint}, ${Column.AuthKey}, ${Column.P256dhKey}, ${Column.UserId}, ${Column.SubscribedAt})
VALUES
(?, ?, ?, ?, ?, ?);
`
const connection = await this.getConnection()
const id = Id.generate()
await connection.query(query, [
id.toString(),
sub.endpoint,
sub.keys.auth,
sub.keys.p256dh,
userId,
Timestamp.now().toNumber(),
])
}
async getAll() {
const query = `
SELECT *
FROM \`${this.tableName}\`
ORDER BY ${Column.SubscribedAt} ASC;
`
const connection = await this.getConnection()
const result = await connection.query(query)
connection.release()
const rows = result[0] as RowDataPacket
return rows.map(this.deserialize) as InternalPushSubscription[]
}
async isHealthy() {
return this.isInitialized && this.isConnected
}
async disconnect() {
await this.pool.end()
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private deserialize(row: any): InternalPushSubscription {
return {
id: row[Column.Id],
endpoint: row[Column.Endpoint],
authKey: row[Column.AuthKey],
p256dhKey: row[Column.P256dhKey],
userId: row[Column.UserId],
subscribedAt: row[Column.SubscribedAt],
}
}
private async getConnection(skipInitCheck = false) {
if (!this.isInitialized && !skipInitCheck) {
await retry(() => {
if (!this.isInitialized) throw new Error()
})
}
const connection = await retry(() => {
return this.pool.getConnection()
})
return connection
}
}