Relay: improve types, DRY

This commit is contained in:
Alex Gleason 2023-08-12 14:41:07 -05:00
parent 075da543b0
commit b2f538ed94
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
1 changed files with 18 additions and 6 deletions

View File

@ -1,19 +1,25 @@
import { type Filter } from '@/deps.ts';
import { getFilters } from '@/db/events.ts';
import { jsonSchema } from '@/schema.ts';
import { clientMsgSchema, type ClientREQ } from '@/schemas/nostr.ts';
import type { AppController } from '@/app.ts';
import type { Filter } from '@/deps.ts';
import type { SignedEvent } from '@/event.ts';
/** Limit of events returned per-filter. */
const FILTER_LIMIT = 100;
type RelayMsg =
| ['EVENT', string, SignedEvent]
| ['NOTICE', string]
| ['EOSE', string];
function connectStream(socket: WebSocket) {
socket.onmessage = (e) => {
const result = jsonSchema.pipe(clientMsgSchema).safeParse(e.data);
if (!result.success) {
socket.send(JSON.stringify(['NOTICE', 'Invalid message.']));
send(['NOTICE', 'Invalid message.']);
return;
}
@ -23,17 +29,23 @@ function connectStream(socket: WebSocket) {
case 'REQ':
handleReq(clientMsg);
return;
default:
socket.send(JSON.stringify(['NOTICE', 'Unknown command.']));
case 'EVENT':
send(['NOTICE', 'EVENT not yet implemented.']);
return;
case 'CLOSE':
return;
}
};
async function handleReq([_, sub, ...filters]: ClientREQ) {
for (const event of await getFilters(prepareFilters(filters))) {
socket.send(JSON.stringify(['EVENT', sub, event]));
send(['EVENT', sub, event]);
}
socket.send(JSON.stringify(['EOSE', sub]));
send(['EOSE', sub]);
}
function send(msg: RelayMsg) {
socket.send(JSON.stringify(msg));
}
}