relay: refactor into smaller functions

This commit is contained in:
Alex Gleason 2023-08-12 15:07:07 -05:00
parent b2f538ed94
commit 8e47c9dda2
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
2 changed files with 13 additions and 10 deletions

View File

@ -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));
}
}

View File

@ -51,6 +51,8 @@ type ClientREQ = z.infer<typeof clientReqSchema>;
type ClientEVENT = z.infer<typeof clientEventSchema>;
/** CLOSE message from client to relay. */
type ClientCLOSE = z.infer<typeof clientCloseSchema>;
/** Client message to a Nostr relay. */
type ClientMsg = z.infer<typeof clientMsgSchema>;
/** 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,