浏览代码

fix(server): time buckets (#4498)

Jason Rasmussen 1 年之前
父节点
当前提交
1890c0ab6b
共有 1 个文件被更改,包括 9 次插入10 次删除
  1. 9 10
      server/src/infra/repositories/asset.repository.ts

+ 9 - 10
server/src/infra/repositories/asset.repository.ts

@@ -29,7 +29,8 @@ const truncateMap: Record<TimeBucketSize, string> = {
   [TimeBucketSize.MONTH]: 'month',
   [TimeBucketSize.MONTH]: 'month',
 };
 };
 
 
-const TIME_BUCKET_COLUMN = 'localDateTime';
+const dateTrunc = (options: TimeBucketOptions) =>
+  `(date_trunc('${truncateMap[options.size]}', ("localDateTime" at time zone 'UTC')) at time zone 'UTC')::timestamptz`;
 
 
 @Injectable()
 @Injectable()
 export class AssetRepository implements IAssetRepository {
 export class AssetRepository implements IAssetRepository {
@@ -478,25 +479,23 @@ export class AssetRepository implements IAssetRepository {
   }
   }
 
 
   getTimeBuckets(options: TimeBucketOptions): Promise<TimeBucketItem[]> {
   getTimeBuckets(options: TimeBucketOptions): Promise<TimeBucketItem[]> {
-    const truncateValue = truncateMap[options.size];
+    const truncated = dateTrunc(options);
 
 
     return this.getBuilder(options)
     return this.getBuilder(options)
       .select(`COUNT(asset.id)::int`, 'count')
       .select(`COUNT(asset.id)::int`, 'count')
-      .addSelect(`date_trunc('${truncateValue}', "${TIME_BUCKET_COLUMN}" at time zone 'UTC')`, 'timeBucket')
-      .groupBy(`date_trunc('${truncateValue}', "${TIME_BUCKET_COLUMN}" at time zone 'UTC')`)
-      .orderBy(`date_trunc('${truncateValue}', "${TIME_BUCKET_COLUMN}" at time zone 'UTC')`, 'DESC')
+      .addSelect(truncated, 'timeBucket')
+      .groupBy(truncated)
+      .orderBy(truncated, 'DESC')
       .getRawMany();
       .getRawMany();
   }
   }
 
 
   getByTimeBucket(timeBucket: string, options: TimeBucketOptions): Promise<AssetEntity[]> {
   getByTimeBucket(timeBucket: string, options: TimeBucketOptions): Promise<AssetEntity[]> {
-    const truncateValue = truncateMap[options.size];
+    const truncated = dateTrunc(options);
     return (
     return (
       this.getBuilder(options)
       this.getBuilder(options)
-        .andWhere(`date_trunc('${truncateValue}', "${TIME_BUCKET_COLUMN}" at time zone 'UTC') = :timeBucket`, {
-          timeBucket,
-        })
+        .andWhere(`${truncated} = :timeBucket`, { timeBucket })
         // First sort by the day in localtime (put it in the right bucket)
         // First sort by the day in localtime (put it in the right bucket)
-        .orderBy(`date_trunc('day', "${TIME_BUCKET_COLUMN}" at time zone 'UTC')`, 'DESC')
+        .orderBy(truncated, 'DESC')
         // and then sort by the actual time
         // and then sort by the actual time
         .addOrderBy('asset.fileCreatedAt', 'DESC')
         .addOrderBy('asset.fileCreatedAt', 'DESC')
         .getMany()
         .getMany()