0.1.2Updated 23 days ago
import { AssetStoreBase, type UploadableDataTypes } from "./asset_store_base.ts";

export interface MemoryStoreOptions {
  /** Duration in milliseconds */
  expires_after: number
}

export class MemoryStore extends AssetStoreBase {
  readonly expires_after: number;

  constructor(namespace: string, options?: MemoryStoreOptions) {
    super(namespace);
    this.expires_after = options?.expires_after || 300_000; // 5 minutes
  }

  override async Upload(key: string, data: UploadableDataTypes): Promise<string> {
    key = this.stripped_key(key);

    await this.ToArrayBuffer(key, data);
    if(this.expires_after > 0) {
      setTimeout(() => {
        this.Delete(key);
      }, this.expires_after);
    }

    return this.namespaced_key(key);
  }

  override Get(key: string) {
    key = this.stripped_key(key);

    if(this.cache.has(key)) return this.cache.get(key);

    return null;
  }

  override Info(key: string) {
    key = this.stripped_key(key);

    if(!this.cache.has(key)) return {
      size: 0,
      etag: key,
      lastModified: new Date(0),
      type: "null"
    };

    return {
      size: this.cache.get(key)!.byteLength,
      lastModified: new Date(),
      etag: key,
      type: "application/octet-stream"
    };
  }

  override Delete(key: string) {
    key = this.stripped_key(key);

    this.cache.delete(key);

    return;
  }
}