From 0834274166e4b494f86effc95cce18cc899f765c Mon Sep 17 00:00:00 2001 From: joe fleming Date: Thu, 1 Nov 2018 19:40:38 -0700 Subject: [PATCH] feat: add cron support --- bin/index.js | 30 +++++++++++++++++++++++++++--- src/lib/data-source.mjs | 1 + 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/bin/index.js b/bin/index.js index f0d4f4f..db3a754 100644 --- a/bin/index.js +++ b/bin/index.js @@ -1,23 +1,47 @@ /* eslint no-global-assign: 0 no-console: 0 */ require = require('esm')(module); const getopts = require('getopts'); +const cron = require('node-cron'); const mod = require('../src/index.mjs').default; +const logger = require('../src/lib/logger.mjs').default; -const { index, ...elasticsearch } = getopts(process.argv.slice(2), { +const { index, interval, ...elasticsearch } = getopts(process.argv.slice(2), { string: ['host', 'log'], alias: { h: 'host', l: 'log', i: 'index', + t: 'interval', }, default: { host: 'localhost:9200', log: 'error', index: 'adsb-data', + interval: 0, }, }); -mod(index, { elasticsearch }).catch(err => { +function handleError(err) { console.error(err); process.exit(1); -}); +} + +async function fetchAndIndex() { + return mod(index, { elasticsearch }); +} + +async function run() { + // initial kickoff + await fetchAndIndex().catch(handleError); + + if (interval === 0) return; + + // scheduled running + logger.debug(`Starting cron (${interval}s)...`); + cron.schedule(`${interval} * * * * *`, () => { + logger.debug('Running cron...'); + fetchAndIndex(); + }); +} + +run().catch(handleError); diff --git a/src/lib/data-source.mjs b/src/lib/data-source.mjs index 8fdb4f7..ebb3005 100644 --- a/src/lib/data-source.mjs +++ b/src/lib/data-source.mjs @@ -17,6 +17,7 @@ function getIndexName(index) { export async function createIndex(client, index) { const realIndex = getIndexName(index); + return client.indices .create({ index: realIndex,