All files / server/services/examples examples-repository.ts

92.85% Statements 26/28
75% Branches 9/12
100% Functions 9/9
100% Lines 23/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 44 45 46 47 48 49 50          5x 5x 5x 5x     2x 2x       1x 1x       1x 1x 1x 1x 1x 1x       1x 1x 1x 1x                 1x 1x 52x 52x 52x      
import { BuiltInProvider } from "./built-in-provider";
import { HttpProvider } from "./http-provider";
import { manifestToCatalog, type ExampleRecord, type ExamplesSnapshot } from "./examples-schema";
 
export class ExamplesRepository {
  private readonly builtInProvider = new BuiltInProvider();
  private readonly httpProvider = new HttpProvider();
  private initialized: Promise<void> | null = null;
  private snapshot: ExamplesSnapshot | null = null;
 
  async initialize(): Promise<void> {
    this.initialized ??= this.refresh();
    await this.initialized;
  }
 
  async getCatalog() {
    await this.initialize();
    return manifestToCatalog(this.snapshot!);
  }
 
  async getExample(id: string) {
    await this.initialize();
    const example = this.snapshot!.examples.find((candidate) => candidate.id === id);
    Iif (!example) return null;
    const main = example.files.find((file) => file.name === example.main);
    const remaining = example.files.filter((file) => file !== main);
    return { ...example, files: main ? [main, ...remaining] : example.files };
  }
 
  private async refresh(): Promise<void> {
    const builtins = await this.builtInProvider.getExamples();
    const remote = await this.httpProvider.getExamples();
    const examples = [...builtins, ...(remote?.examples ?? [])];
    this.snapshot = {
      status: remote?.status ?? "builtin",
      stale: remote?.stale ?? false,
      examples: deduplicateExamples(examples),
    };
  }
}
 
function deduplicateExamples(examples: ExampleRecord[]): ExampleRecord[] {
  const ids = new Set<string>();
  return examples.filter((example) => {
    Iif (ids.has(example.id)) return false;
    ids.add(example.id);
    return true;
  });
}