From 22dbddb5d3bab6e0ea79beaa7eca4d1c4cf0c1df Mon Sep 17 00:00:00 2001 From: "P. Reis" Date: Thu, 13 Jun 2024 14:21:01 -0300 Subject: [PATCH] refactor: zap amount parsed with zod, change zapped_by fields name --- src/controllers/api/statuses.ts | 11 ++++------- src/utils/stats.ts | 12 +++++++----- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/src/controllers/api/statuses.ts b/src/controllers/api/statuses.ts index 4945e3b..7b9e82c 100644 --- a/src/controllers/api/statuses.ts +++ b/src/controllers/api/statuses.ts @@ -545,6 +545,7 @@ const zapController: AppController = async (c) => { const zappedByController: AppController = async (c) => { const id = c.req.param('id'); const store = await Storages.db(); + const amountSchema = z.coerce.number().int().nonnegative().catch(0); const events: DittoEvent[] = (await store.query([{ kinds: [9735], '#e': [id], limit: 100 }])).map((event) => { const zapRequest = event.tags.find(([name]) => name === 'description')?.[1]; @@ -560,17 +561,13 @@ const zappedByController: AppController = async (c) => { const results = (await Promise.all( events.map(async (event) => { - const amount = event.tags.find(([name]) => name === 'amount')?.[1]; - const onlyDigits = /^\d+$/; - if (!amount || !onlyDigits.test(amount)) return; - + const amount = amountSchema.parse(event.tags.find(([name]) => name === 'amount')?.[1]); const comment = event?.content ?? ''; - const account = event?.author ? await renderAccount(event.author) : await accountFromPubkey(event.pubkey); return { - zap_comment: comment, - zap_amount: Number(amount), + comment, + amount, account, }; }), diff --git a/src/utils/stats.ts b/src/utils/stats.ts index 8f0b550..e6001d1 100644 --- a/src/utils/stats.ts +++ b/src/utils/stats.ts @@ -1,7 +1,8 @@ import { NostrEvent, NStore } from '@nostrify/nostrify'; import { Kysely, UpdateObject } from 'kysely'; - import { SetRequired } from 'type-fest'; +import { z } from 'zod'; + import { DittoTables } from '@/db/DittoTables.ts'; import { findQuoteTag, findReplyTag, getTagSet } from '@/utils/tags.ts'; import { Conf } from '@/config.ts'; @@ -140,19 +141,20 @@ async function handleEvent9735(kysely: Kysely, event: NostrEvent): const id = event.tags.find(([name]) => name === 'e')?.[1]; if (!id) return; - let amount = '0'; + const amountSchema = z.coerce.number().int().nonnegative().catch(0); + let amount = 0; try { const zapRequest = JSON.parse(event.tags.find(([name]) => name === 'description')?.[1]!) as NostrEvent; - amount = zapRequest.tags.find(([name]) => name === 'amount')?.[1]!; + amount = amountSchema.parse(zapRequest.tags.find(([name]) => name === 'amount')?.[1]); + if (amount <= 0) return; } catch { return; } - if (amount === '0' || !amount || (/^\d+$/).test(amount) === false) return; await updateEventStats( kysely, id, - ({ zaps_amount }) => ({ zaps_amount: Math.max(0, zaps_amount + Number(amount)) }), + ({ zaps_amount }) => ({ zaps_amount: Math.max(0, zaps_amount + amount) }), ); }