74 lines
2.5 KiB
TypeScript
74 lines
2.5 KiB
TypeScript
import { EventEmitter } from 'node:events';
|
|
import { setTimeout } from 'timers/promises';
|
|
|
|
import type Log from 'bunyan';
|
|
import type { Want } from '@prisma/client';
|
|
|
|
import { Pg } from './pg';
|
|
import { wantDetails } from './utils';
|
|
import routerAuth from './routers/router.auth';
|
|
|
|
export enum Events {
|
|
WantsAdded = 'WantsAdded',
|
|
Sync = 'Sync',
|
|
ListingsUpdated = 'ListingsUpdated',
|
|
Connection = 'Connection',
|
|
}
|
|
|
|
export default function createEvents(log: Log, pg: Pg, discogs, offers) {
|
|
const events = new EventEmitter({ captureRejections: true });
|
|
const connections = new Map();
|
|
|
|
async function populateListings(want: Want) {
|
|
try {
|
|
const listings = await discogs.listings(want);
|
|
return listings;
|
|
} catch (e) {
|
|
if (e.message === 'rate limited') {
|
|
log.warn('rate limited, trying again in 60s');
|
|
await setTimeout(60 * 1000);
|
|
return populateListings(want);
|
|
}
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
events.on('error', function eventError(e) {
|
|
log.error('event error', e);
|
|
});
|
|
|
|
async function updateWantListings(wants: Want[]) {
|
|
for (const want of wants) {
|
|
const listings = await populateListings(want);
|
|
log.info({ listings: listings.length, ...wantDetails(want) }, 'listings added');
|
|
events.emit(Events.ListingsUpdated);
|
|
}
|
|
|
|
log.info({ wants: wants.length }, 'finished syncing');
|
|
}
|
|
|
|
events.on(Events.WantsAdded, async function wantsAdded(wants: Want[]) {
|
|
log.info({ event: Events.WantsAdded, wants: wants.map(w => wantDetails(w)) }, 'starting listings population');
|
|
await updateWantListings(wants);
|
|
log.info({ event: Events.WantsAdded, wants: wants.map(w => wantDetails(w)) }, 'finished populating listings');
|
|
events.emit(Events.ListingsUpdated);
|
|
});
|
|
|
|
events.on(Events.Sync, async function sync() {
|
|
const wants = await pg.wantsToSync();
|
|
log.info({ event: Events.Sync, wants: wants.length });
|
|
await updateWantListings(wants);
|
|
events.emit(Events.ListingsUpdated);
|
|
});
|
|
|
|
events.on(Events.ListingsUpdated, async function listingsUpdated() {
|
|
const updatedOffers = await offers.generate()
|
|
log.debug({ offers: updatedOffers.length }, 'offers up to date');
|
|
});
|
|
|
|
events.on(Events.Connection, async function onConnection({ ws, id }) {
|
|
connections.set(id, ws);
|
|
})
|
|
|
|
return events;
|
|
} |