aboutsummaryrefslogtreecommitdiff
path: root/src/metadata.ts
blob: 1eb7f1ac51dee410e4043dcae320cb0dcedab5cd (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
44
45
46
47
48
49
50
51
52
53
54
import { Db } from "mongodb";

/** //FIXME fix document schema
 * Rather than using branches as the core, this should be adopted into the following document model:
 * repo:
 *  - org
 *  - name
 *  - token
 *  - branches: {
 *      [branchname]: {
 *        head
 *      }
 *    }
 */
export interface Branch {
  org: string;
  repo: string;
  name: string;
  head: string;
}

class Metadata {
  database: Db;

  constructor(client: Db) {
    this.database = client;
  }

  async getHeadCommit(
    org: string,
    repo: string,
    branch: string
  ): Promise<string> {
    const result = await this.database
      .collection<Branch>("branch")
      .findOne({ org, repo, name: branch });

    if (result !== null) {
      return result.head;
    } else {
      throw Error("Branch not found");
    }
  }

  async updateBranch(branch: Branch): Promise<boolean> {
    const { head, ...matcher } = branch;
    const { result } = await this.database
      .collection<Branch>("branch")
      .replaceOne(matcher, branch, { upsert: true });
    return result.ok === 1;
  }
}

export default Metadata;