Files
crates/server/index.ts
T
2022-08-01 00:05:55 +10:00

100 lines
3.0 KiB
TypeScript

import fs from 'fs/promises';
import _ from 'lodash';
import Bunyan from 'bunyan';
import { PrismaClient } from '@prisma/client'
import Promise from "bluebird";
import discogsService from './src/discogs';
import pgService from './src/pg';
import { logAxiosError } from './src/utils';
import createLog from './src/log';
async function start(log) {
const prisma = new PrismaClient();
const pg = pgService(log, prisma);
const discogs = discogsService(log, pg);
async function getBundles() {
const bundles = await pg.bundleCandidates();
bundles.forEach(b => {
const data = b.map(l => l.data) as any[];
const wants = b.map(l => l.wantId);
const total = data.reduce((acc, l) => acc + l.price.value, 0);
const items = data.map(l => ({
id: l.id,
description: l.release.description,
price: l.price.value,
condition: l.condition,
uri: l.uri,
}));
const username = data[0]?.seller.username
const seller = data[0]?.seller.id
const shipsFrom = data[0]?.ships_from;
const currency = data[0]?.price.currency;
const shipping = data[0]?.seller.shipping;
const mentionsAustralia = shipping.toLowerCase().includes('australia');
const mentionsWorldwide = shipping.toLowerCase().includes('world');
log.info({ count: b.length, currency, total, items, username, seller, shipsFrom, mentionsAustralia, mentionsWorldwide });
});
// return bundles;
}
const usernames = [
'vanderbabe',
'margh',
'jmcdermid1',
];
async function populateUserListings(user) {
log.info(user);
const wants = await discogs.wantlist(user);
// const latest = await discogs.wantlistLatest(user);
// if (wants.length !== latest.length)
log.info({ username: user.discogs, wantCount: wants.length });
return Promise.mapSeries(wants, async want => {
const listings = await discogs.listings(want);
const populated = listings.filter(l => l);
log.info({ id: want.id, release: want.release, populated: populated.length, total: listings.length });
return populated;
});
}
await Promise.mapSeries(usernames, async u => {
const user = await discogs.user(u)
return populateUserListings(user);
});
return getBundles();
}
async function run() {
const log = createLog();
process.on('SIGTERM', () => {
log.debug('SIGTERM received, exiting');
process.exit(0);
});
try {
const r = await start(log)
// log.info('done syncing', { totalListings: r.flat().length });
log.info(r);
setTimeout(run, 60 * 1000);
} catch (e) {
if (e.message === 'rate limited') {
log.info('rate limited, trying again in 60s');
return setTimeout(run, 60 * 1000);
}
log.error(e);
process.exit(1);
}
}
run();