Skip to content

Commit

Permalink
Fix bad hourly start timestamp on chart data (#75)
Browse files Browse the repository at this point in the history
* Fix bad date string/timezone combo to AE query

* Remove formatDateTime and use dayjs#format instead
  • Loading branch information
benvinegar committed Apr 30, 2024
1 parent 26b539d commit e48cb06
Showing 1 changed file with 11 additions and 35 deletions.
46 changes: 11 additions & 35 deletions app/analytics/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,30 +42,6 @@ function accumulateCountsFromRowResult(
counts.views += Number(row.count);
}

/**
* Convert a Date object to YY-MM-DD HH:MM:SS
*/
function formatDateString(d: Date) {
function pad(n: number) {
return n < 10 ? "0" + n : n;
}
const dash = "-";
const colon = ":";
return (
d.getFullYear() +
dash +
pad(d.getMonth() + 1) +
dash +
pad(d.getDate()) +
" " +
pad(d.getHours()) +
colon +
pad(d.getMinutes()) +
colon +
pad(d.getSeconds())
);
}

function intervalToSql(interval: string, tz?: string) {
let intervalSql = "";
switch (interval) {
Expand Down Expand Up @@ -176,8 +152,8 @@ export class AnalyticsEngineAPI {
async getViewsGroupedByInterval(
siteId: string,
intervalType: "DAY" | "HOUR",
startDateTime: Date,
tz?: string,
startDateTime: Date, // start date/time in local timezone
tz?: string, // local timezone
) {
let intervalCount = 1;

Expand Down Expand Up @@ -206,24 +182,22 @@ export class AnalyticsEngineAPI {
// to generate empty buckets in JS (generateEmptyRowsOverInterval)
// and merge them with the results.

const utcStartDateTime = dayjs(startDateTime).tz(tz).utc();

const query = `
SELECT SUM(_sample_interval) as count,
/* interval start needs local timezone, e.g. 00:00 in America/New York means start of day in NYC */
toStartOfInterval(timestamp, INTERVAL '${intervalCount}' ${intervalType}, '${tz}') as _bucket,
/* format output date as UTC (otherwise will be users local TZ) */
toDateTime(_bucket, 'Etc/UTC') as bucket
toStartOfInterval(timestamp, INTERVAL '${intervalCount}' ${intervalType}) as bucket
FROM metricsDataset
WHERE timestamp > toDateTime('${formatDateString(startDateTime)}', '${tz}')
WHERE timestamp > toDateTime('${utcStartDateTime.format("YYYY-MM-DD HH:mm:ss")}')
AND ${ColumnMappings.siteId} = '${siteId}'
GROUP BY _bucket
ORDER BY _bucket ASC`;
GROUP BY bucket
ORDER BY bucket ASC`;

type SelectionSet = {
count: number;
_bucket: string;
bucket: string;
};

Expand All @@ -245,7 +219,9 @@ export class AnalyticsEngineAPI {
const rowsByDateTime = responseData.data.reduce(
(accum, row) => {
const utcDateTime = new Date(row["bucket"]);
const key = formatDateString(utcDateTime);
const key = dayjs(utcDateTime).format(
"YYYY-MM-DD HH:mm:ss",
);
accum[key] = Number(row["count"]);
return accum;
},
Expand Down

0 comments on commit e48cb06

Please sign in to comment.