diff --git a/src/controllers/nostr/relay.ts b/src/controllers/nostr/relay.ts index 5a797ff..eb4a983 100644 --- a/src/controllers/nostr/relay.ts +++ b/src/controllers/nostr/relay.ts @@ -1,6 +1,6 @@ import { getFilters } from '@/db/events.ts'; import { jsonSchema } from '@/schema.ts'; -import { clientMsgSchema, type ClientREQ } from '@/schemas/nostr.ts'; +import { type ClientMsg, clientMsgSchema, type ClientREQ } from '@/schemas/nostr.ts'; import type { AppController } from '@/app.ts'; import type { Filter } from '@/deps.ts'; @@ -17,17 +17,17 @@ type RelayMsg = function connectStream(socket: WebSocket) { socket.onmessage = (e) => { const result = jsonSchema.pipe(clientMsgSchema).safeParse(e.data); - - if (!result.success) { + if (result.success) { + handleClientMsg(result.data); + } else { send(['NOTICE', 'Invalid message.']); - return; } + }; - const clientMsg = result.data; - - switch (clientMsg[0]) { + function handleClientMsg(msg: ClientMsg) { + switch (msg[0]) { case 'REQ': - handleReq(clientMsg); + handleReq(msg); return; case 'EVENT': send(['NOTICE', 'EVENT not yet implemented.']); @@ -35,7 +35,7 @@ function connectStream(socket: WebSocket) { case 'CLOSE': return; } - }; + } async function handleReq([_, sub, ...filters]: ClientREQ) { for (const event of await getFilters(prepareFilters(filters))) { @@ -45,7 +45,7 @@ function connectStream(socket: WebSocket) { } function send(msg: RelayMsg) { - socket.send(JSON.stringify(msg)); + return socket.send(JSON.stringify(msg)); } } diff --git a/src/schemas/nostr.ts b/src/schemas/nostr.ts index 96344a2..e5bdb81 100644 --- a/src/schemas/nostr.ts +++ b/src/schemas/nostr.ts @@ -51,6 +51,8 @@ type ClientREQ = z.infer; type ClientEVENT = z.infer; /** CLOSE message from client to relay. */ type ClientCLOSE = z.infer; +/** Client message to a Nostr relay. */ +type ClientMsg = z.infer; /** Kind 0 content schema. */ const metaContentSchema = z.object({ @@ -68,6 +70,7 @@ const jsonMetaContentSchema = jsonSchema.pipe(metaContentSchema).catch({}); export { type ClientCLOSE, type ClientEVENT, + type ClientMsg, clientMsgSchema, type ClientREQ, filterSchema,