All files / src/reporter github.ts

0% Statements 0/16
100% Branches 0/0
0% Functions 0/9
0% Lines 0/15

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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68                                                                                                                                       
export interface Comment {
  id: number;
  message: string;
  user: string;
  url: string;
}
 
export class GitHubCiClient {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  private headersInit: Record<string, string> = {
    "User-Agent": "AutoRest CI",
  };
 
  constructor(
    private githubRepo: string,
    githubTokenOfCI: string,
  ) {
    this.headersInit["Authorization"] = "token " + githubTokenOfCI;
  }
 
  public async getComments(pr: number): Promise<Comment[]> {
    const res = await fetch(`https://api.github.com/repos/${this.githubRepo}/issues/${pr}/comments`, {
      headers: this.headersInit,
    });
    const comments = JSON.parse(await res.text());
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    return comments.map((x: any) => {
      return { id: x.id, message: x.body, user: x.user.login, url: x.html_url };
    });
  }
 
  public async getCommentsWithIndicator(pr: number, indicator: string): Promise<Comment[]> {
    return (await this.getComments(pr)).filter((comment) => comment.message.startsWith(indicator));
  }
 
  public async setComment(id: number, message: string): Promise<void> {
    await fetch(`https://api.github.com/repos/${this.githubRepo}/issues/comments/${id}`, {
      body: JSON.stringify({ body: message }),
      headers: this.headersInit,
      method: "POST",
    });
  }
 
  public async deleteComment(id: number): Promise<void> {
    await fetch(`https://api.github.com/repos/${this.githubRepo}/issues/comments/${id}`, {
      headers: this.headersInit,
      method: "DELETE",
    });
  }
 
  public async tryDeleteComment(id: number): Promise<void> {
    try {
      await this.deleteComment(id);
    } catch (_) {
      //.
    }
  }
 
  public async createComment(pr: number, message: string): Promise<number> {
    const res = await fetch(`https://api.github.com/repos/${this.githubRepo}/issues/${pr}/comments`, {
      body: JSON.stringify({ body: message }),
      headers: this.headersInit,
      method: "POST",
    });
    return JSON.parse(await res.text()).id;
  }
}