webpush: replace old subscriptions in transaction

This commit is contained in:
Alex Gleason 2024-10-14 14:31:33 -05:00
parent 94cf3b2931
commit b3928bac45
No known key found for this signature in database
GPG key ID: 7211D1F99744FBB7

View file

@ -42,9 +42,9 @@ export const pushSubscribeController: AppController = async (c) => {
return c.json({ error: 'Unauthorized' }, 401); return c.json({ error: 'Unauthorized' }, 401);
} }
const [_, bech32] = match; const [_, accessToken] = match;
if (!bech32.startsWith('token1')) { if (!accessToken.startsWith('token1')) {
return c.json({ error: 'Unauthorized' }, 401); return c.json({ error: 'Unauthorized' }, 401);
} }
@ -59,18 +59,28 @@ export const pushSubscribeController: AppController = async (c) => {
const { subscription, data } = result.data; const { subscription, data } = result.data;
const { id } = await kysely const pubkey = await signer.getPublicKey();
.insertInto('push_subscriptions') const tokenHash = await getTokenHash(accessToken as `token1${string}`);
.values({
pubkey: await signer.getPublicKey(), const { id } = await kysely.transaction().execute(async (trx) => {
token_hash: await getTokenHash(bech32 as `token1${string}`), await trx
endpoint: subscription.endpoint, .deleteFrom('push_subscriptions')
p256dh: subscription.keys.p256dh, .where('token_hash', '=', tokenHash)
auth: subscription.keys.auth, .execute();
data,
}) return trx
.returning('id') .insertInto('push_subscriptions')
.executeTakeFirstOrThrow(); .values({
pubkey,
token_hash: tokenHash,
endpoint: subscription.endpoint,
p256dh: subscription.keys.p256dh,
auth: subscription.keys.auth,
data,
})
.returning('id')
.executeTakeFirstOrThrow();
});
return c.json({ return c.json({
id, id,