diff --git a/lib/db.js b/lib/db.js index 06443074..90e98b06 100644 --- a/lib/db.js +++ b/lib/db.js @@ -13,7 +13,10 @@ export function getDatabase(database, databaseType, fallback) { } if (!type) { - return getDatabase(fallback); + if (fallback) { + return getDatabase(fallback); + } + return null; } return type; diff --git a/lib/kafka.js b/lib/kafka.js index 987b9d25..39320728 100644 --- a/lib/kafka.js +++ b/lib/kafka.js @@ -34,11 +34,15 @@ const kafka = global.kafka || getClient(); let kafkaProducer = null; (async () => { - kafkaProducer = global.kakfaProducer || (await getProducer()); + if (kafka) { + kafkaProducer = global.kakfaProducer || (await getProducer()); + } if (process.env.NODE_ENV !== 'production') { global.kafka = kafka; - global.kakfaProducer = kafkaProducer; + if (kafka) { + global.kakfaProducer = kafkaProducer; + } } })(); diff --git a/lib/relational.js b/lib/relational.js index 28de7531..e5b9f2ce 100644 --- a/lib/relational.js +++ b/lib/relational.js @@ -7,7 +7,7 @@ import { POSTGRESQL, POSTGRESQL_DATE_FORMATS, } from 'lib/constants'; -import { getDatabase } from './db'; +import { getDatabase } from 'lib/db'; import moment from 'moment-timezone'; const options = { @@ -32,6 +32,7 @@ function getClient(options) { return prisma; } + const prisma = global.prisma || getClient(options); if (process.env.NODE_ENV !== 'production') { @@ -41,7 +42,7 @@ if (process.env.NODE_ENV !== 'production') { export { prisma }; export function getDateQuery(field, unit, timezone) { - const db = getDatabase(); + const db = getDatabase(process.env.DATABASE_URL); if (db === POSTGRESQL) { if (timezone) { @@ -61,6 +62,18 @@ export function getDateQuery(field, unit, timezone) { } } +export function getTimestampInterval(field) { + const db = getDatabase(process.env.DATABASE_URL); + + if (db === POSTGRESQL) { + return `floor(extract(epoch from max(${field}) - min(${field})))`; + } + + if (db === MYSQL) { + return `floor(unix_timestamp(max(${field})) - unix_timestamp(min(${field})))`; + } +} + export function getFilterQuery(table, column, filters = {}, params = []) { const query = Object.keys(filters).reduce((arr, key) => { const filter = filters[key]; @@ -151,7 +164,7 @@ export async function runQuery(query) { } export async function rawQuery(query, params = []) { - const db = getDatabase(process.env.DATABASE_URL, process.env.DATABASE_TYPE); + const db = getDatabase(process.env.DATABASE_URL); if (db !== POSTGRESQL && db !== MYSQL) { return Promise.reject(new Error('Unknown database.'));