aboutsummaryrefslogtreecommitdiff
path: root/src/metadata.ts
blob: a25e8bfd5d9d707c296d7c2ae92cc8b1a4585c9f (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
55
56
57
58
59
60
61
62
63
64
65
import { Db } from "mongodb";
import winston from "winston";

import logger_config from "./util/logger";

/** //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;
}
const logger = winston.createLogger(logger_config("META"));

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) {
      logger.debug(
        "Found commit %s for ORB %s/%s/%s",
        result.head,
        org,
        repo,
        branch
      );
      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;