forked from wangziqi/gongxue-base
feat: add crm webhook worker
This commit is contained in:
50
apps/worker/src/index.ts
Normal file
50
apps/worker/src/index.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { closePool } from './db.js';
|
||||
import { config } from './config.js';
|
||||
import { processCrmBatch } from './jobs/crm.js';
|
||||
|
||||
function hasArg(name: string) {
|
||||
return process.argv.includes(name);
|
||||
}
|
||||
|
||||
function argValue(name: string, fallback = '') {
|
||||
const index = process.argv.indexOf(name);
|
||||
return index >= 0 ? process.argv[index + 1] || fallback : fallback;
|
||||
}
|
||||
|
||||
async function runOnce() {
|
||||
const job = argValue('--job', 'crm');
|
||||
if (job !== 'crm') {
|
||||
throw new Error(`Unsupported worker job: ${job}`);
|
||||
}
|
||||
const result = await processCrmBatch();
|
||||
console.log(`[worker] crm batch processed=${result.processed} sent=${result.sent} failed=${result.failed} retrying=${result.retrying} discarded=${result.discarded}`);
|
||||
}
|
||||
|
||||
async function runLoop() {
|
||||
console.log('[worker] started');
|
||||
let stopped = false;
|
||||
const stop = () => {
|
||||
stopped = true;
|
||||
};
|
||||
process.once('SIGINT', stop);
|
||||
process.once('SIGTERM', stop);
|
||||
|
||||
while (!stopped) {
|
||||
try {
|
||||
await runOnce();
|
||||
} catch (error) {
|
||||
console.error('[worker] job failed', error);
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, config.crmPollIntervalMs));
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
if (hasArg('--loop')) {
|
||||
await runLoop();
|
||||
} else {
|
||||
await runOnce();
|
||||
}
|
||||
} finally {
|
||||
await closePool();
|
||||
}
|
||||
Reference in New Issue
Block a user