summaryrefslogtreecommitdiff
path: root/Homework/cs5260/consumer/dao/keys/S3WidgetKeyGenerator.ts
blob: 2e4c2546cfa559510518e49595c175a7c559d2cd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { WidgetT } from "@/shared/schema";

export class S3WidgetKeyGenerator {
  private prefix: string = "";
  private owner: string = "";
  private widgetId: string = "";

  public withPrefix(prefix: string): S3WidgetKeyGenerator {
    this.prefix = prefix;
    return this;
  }

  public withOwner(owner: string): S3WidgetKeyGenerator {
    this.owner = owner;
    return this;
  }

  public withWidgetId(widgetId: string): S3WidgetKeyGenerator {
    this.widgetId = widgetId;
    return this;
  }

  public build(): string {
    const parts = [
      this.prefix,
      this.owner.replaceAll(" ", "-").toLowerCase(),
      this.widgetId,
    ];
    if (parts.some((part) => !part || !part.match(/^[a-zA-Z0-9!\-_.*'()]+$/))) {
      throw new Error("Invalid Key Specification");
    }
    return parts.join("/");
  }

  public fromWidget(widget: WidgetT) {
    const keyBuilder = new S3WidgetKeyGenerator();
    return keyBuilder
      .withPrefix(this.prefix)
      .withOwner(widget.owner)
      .withWidgetId(widget.id)
      .build();
  }
}