in functions/src/plugins/common.ts [90:133]
async init(github: GitHubAPI, repositories: Repository[]): Promise<void> {
await Promise.all(repositories.map(async repository => {
this.robot.log(`Starting init for repository "${repository.full_name}"`);
const [owner, repo] = repository.full_name.split('/');
const dbPRSnapshots = await this.pullRequests
.where('repository', '==', repository.id)
.where('state', '==', 'open')
.get();
// list of existing opened PRs in the db
const dbPRs = dbPRSnapshots.docs.map(doc => doc.id);
const ghPRs = await github.paginate(github.pullRequests.list({
owner,
repo,
state: 'open',
per_page: 100
}), pages => (pages as any as Github.AnyResponse).data) as Github.PullRequestsListResponse;
ghPRs.forEach(async pr => {
const index = dbPRs.indexOf(pr.id.toString());
if(index !== -1) {
dbPRs.splice(index, 1);
}
});
// update the state of all PRs that are no longer opened
if(dbPRs.length > 0) {
const batch = this.db.batch();
dbPRs.forEach(async id => {
batch.set(this.pullRequests.doc(id.toString()), {state: 'closed'}, {merge: true});
});
batch.commit().catch(err => {
this.robot.log.error(err);
throw err;
});
}
// add/update opened PRs
return Promise.all(ghPRs.map(pr => github.pullRequests.get({number: pr.number, owner, repo})
.then(res => this.updateDbPR(github, owner, repo, pr.number, repository.id, res.data))));
}));
}