Skip to content

Commit

Permalink
refactor: improved error handling for cronjob
Browse files Browse the repository at this point in the history
  • Loading branch information
jakowenko committed Jun 22, 2023
1 parent b6a64bf commit ac4f1d6
Showing 1 changed file with 49 additions and 44 deletions.
93 changes: 49 additions & 44 deletions api/src/util/cron.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import prisma from '../util/prisma.util';
import Log from '../util/logger.util';
const { version } = require('../../package.json');

const { log } = new Log('cron');

const {
TELEMETRY,
Expand All @@ -36,58 +35,64 @@ export default {
new CronJob(`${DateTime.now().toFormat('m')} * * * *`, track).start();
},
transcript: async () => {
new CronJob(CRON, async () => {
const { cron } = state.get();
if (!cron) {
log.verbose('paused');
return;
}
const { log } = new Log('cron');
try {
new CronJob(CRON, async () => {
const { cron } = state.get();
if (!cron) {
log.verbose('paused');
return;
}

const recent = await prisma.image.findFirst({
where: {
createdAt: {
gt: new Date(Date.now() - 5 * 60 * 1000),
const recent = await prisma.image.findFirst({
where: {
createdAt: {
gte: new Date(Date.now() - 5 * 60 * 1000),
},
},
},
orderBy: {
createdAt: 'desc',
},
});

if (recent) {
log.verbose('skipped (image created within last 5 minutes)');
return;
}

await prisma.transcript.deleteMany({
where: {
createdAt: {
lt: new Date(Date.now() - MINUTES * 60 * 1000),
orderBy: {
createdAt: 'desc',
},
},
});
});

const transcriptIds = (
await prisma.transcript.findMany({
select: {
id: true,
},
if (recent) {
log.verbose('skipped (image created within last 5 minutes)');
return;
}

await prisma.transcript.deleteMany({
where: {
createdAt: {
gte: new Date(Date.now() - MINUTES * 60 * 1000),
lt: new Date(Date.now() - MINUTES * 60 * 1000),
},
},
})
).map(({ id }: { id: number }) => id);
});

if (transcriptIds.length < MINIMUM) {
log.info(
`${MINIMUM} transcript(s) needed within last ${MINUTES} minutes, found ${transcriptIds.length}`
);
return;
}
const transcriptIds = (
await prisma.transcript.findMany({
select: {
id: true,
},
where: {
createdAt: {
gte: new Date(Date.now() - MINUTES * 60 * 1000),
},
},
})
).map(({ id }: { id: number }) => id);

if (transcriptIds.length < MINIMUM) {
log.info(
`${MINIMUM} transcript(s) needed within last ${MINUTES} minutes, found ${transcriptIds.length}`
);
return;
}

emitter.emit('transcript.process', transcriptIds);
}).start();
emitter.emit('transcript.process', transcriptIds);
}).start();
} catch (error: any) {
log.error(error.message);
}
},
},
};

0 comments on commit ac4f1d6

Please sign in to comment.