-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
1188 lines (1105 loc) · 32.9 KB
/
server.js
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const mongoose = require("mongoose");
const { readFile } = require("fs/promises");
const { Octokit, RequestError } = require("octokit");
const fs = require("fs");
const { newLogger } = require("./utils/logger.js");
// loggers
const cronLogger = newLogger("cron");
const dbLogger = newLogger("db");
const ioLogger = newLogger("io");
const octokitLogger = newLogger("github");
const Organization = require("./models/organization");
const User = require("./models/user");
const Stat = require("./models/stat");
const listDirPath = "./lists";
const getBlockedRepos = () => {
const blockedRepos = [];
// read the file as a utf-8 encoded string
fs.readFile(`${listDirPath}/blocked-repos.txt`, "utf-8", (err, data) => {
if (err) {
// handle the error
ioLogger.error(JSON.stringify(err));
return;
}
// split the data into an array of names
const repoNames = data.split("\n");
repoNames.forEach(repoName => {
blockedRepos.push(repoName);
});
});
return blockedRepos;
};
const getBlockedUsers = () => {
const blockedUsers = [];
// read the file as a utf-8 encoded string
fs.readFile(`${listDirPath}/blocked-users.txt`, "utf-8", (err, data) => {
if (err) {
// handle the error
ioLogger.error(JSON.stringify(err));
return;
}
// split the data into an array of names
const usernames = data.split("\n");
usernames.forEach(username => {
blockedUsers.push(username);
});
});
return blockedUsers;
};
const getMembers = async () => {
const members = await readFile(`${listDirPath}/members.txt`, "utf8")
.then(data => {
const members = [];
// split the data into an array of names
const usernames = data.split("\n");
for (const username of usernames) {
members.push(username);
}
return members;
})
.catch(error =>
ioLogger.error(`Could not read the members file: ${error}`)
);
return members;
};
const blockedRepos = getBlockedRepos();
const blockedUsers = getBlockedUsers();
require("dotenv").config({
path: "./.env",
});
const octokit = new Octokit({
auth: process.env.GITHUB_ACCESS_TOKEN,
});
const ConnectToDB = async () => {
let DB_URL =
"mongodb://" +
process.env.DATABASE_HOST +
":" +
process.env.DATABASE_PORT +
"/" +
process.env.DATABASE_NAME;
if (process.env.NODE_ENV !== "development") {
// DB_URL
// mongodb://username:password@host:port/database
DB_URL =
"mongodb+srv://" +
process.env.DATABASE_USER +
":" +
process.env.DATABASE_PASSWORD +
"@" +
process.env.DATABASE_HOST +
"/" +
process.env.DATABASE_NAME +
"?authSource=admin&tls=" +
process.env.TLS_ENABLED +
"&tlsCAFile=" +
process.env.CA_PATH +
"";
}
cronLogger.info(`Log Level: ${cronLogger.level}`);
cronLogger.info(`Run Mode: ${process.env.RUN_MODE}`);
cronLogger.info(`lists Path: ${listDirPath}`);
await mongoose.connect(DB_URL);
dbLogger.info("Connected to the database");
dbLogger.info(`Database Host: ${mongoose.connection.host}`);
dbLogger.info(`Database Name: ${mongoose.connection.name}`);
dbLogger.info(`Database Port: ${mongoose.connection.port}`);
console.log("============================================");
};
const isRepoBlocked = _repoName => {
for (const repo of blockedRepos) {
return _repoName === repo;
}
};
const isUserBlocked = _username => {
for (const user of blockedUsers) {
return _username === user;
}
};
const isInJordan = _location => {
if (!_location) {
return false;
}
const locationKeyWords = [
"Irbid",
"Aqaba",
"Al-Karak",
"Amman",
"Madaba",
"Zarqa",
"Al-Zarqa",
"AlSalt",
"Ajloun",
"Al-Mafraq",
"Maan",
"Jerash",
"AlKarak",
];
let locationFound = false;
_location = _location.toLowerCase();
if (_location === "jordan") {
locationFound = true;
} else {
locationKeyWords.forEach(key => {
key = key.toLowerCase();
if (_location.includes(key) && !locationFound) {
locationFound = true;
}
});
}
return locationFound;
};
const SaveUsersToDB = async _usersData => {
for (const user of _usersData) {
if (!isUserBlocked(user.login)) {
let userExists = await User.exists({ username: user.login });
if (!userExists) {
let newUser = new User({
username: user.login,
avatar_url: user.avatarUrl,
name: user.name,
location: user.location,
bio: user.bio,
company: user.company,
isHireable: user.isHireable,
github_profile_url: user.url,
user_createdAt: user.createdAt,
});
await newUser.save();
dbLogger.debug(
`User: ${newUser.username} and the location is ${newUser.location} was saved to DB`
);
} else {
if (isInJordan(user.location)) {
await User.updateOne(
{ username: user.login },
{
avatar_url: user.avatarUrl,
name: user.name,
location: user.location,
github_profile_url: user.url,
bio: user.bio,
company: user.company,
}
);
} else {
await User.deleteOne({ username: user.login });
dbLogger.debug(
`User ${user.name} has been removed due to the location not being jordan`
);
}
}
}
}
};
const ExtractUsersFromGithub = async () => {
let locationsToSearch = [
"Jordan",
"Amman",
"Aqaba",
"Madaba",
"Irbid",
"Zarqa",
"Jerash",
"Al-Karak",
"Maan",
"Ajloun",
];
let extractedUsers = [];
for (let index = 0; index < locationsToSearch.length; index++) {
let endCursor = null;
let hasNextPage = true;
while (hasNextPage) {
try {
let pageCursor = endCursor === null ? `${endCursor}` : `"${endCursor}"`;
let result = await octokit.graphql(
`{
search(query: "location:${locationsToSearch[index]} type:user", type: USER, first: 100, after: ${pageCursor}) {
nodes {
... on User {
login
avatarUrl
name
location
bio
url
company
isHireable
createdAt
}
}
pageInfo {
endCursor
hasNextPage
}
}
}`
);
let newUsers = await result.search.nodes;
for (const user of newUsers) {
if (isInJordan(user.location)) {
extractedUsers = [...extractedUsers, user];
}
}
hasNextPage = await result.search.pageInfo.hasNextPage;
endCursor = await result.search.pageInfo.endCursor;
} catch (error) {
if (error instanceof RequestError) {
octokitLogger.error(error.message);
throw error;
} else {
octokitLogger.error(error);
throw error;
}
}
}
}
await SaveUsersToDB(extractedUsers);
};
const GetUsersFromDB = async (_filter = {}, _fields, _sort = {}) => {
const results = await User.find(_filter, _fields).sort(_sort);
const documents = results;
return documents;
};
const CleanDatabase = async () => {
cronLogger.info("Database cleanup...");
const users = await GetUsersFromDB({}, "username");
// Create an empty array to group the users we want to delete
const usersToDelete = [];
for (const user of users) {
try {
let result = await octokit.graphql(
`{
user(login: "${user.username}") {
location
}
}`
);
const userLocation = await result.user.location;
if (!isInJordan(userLocation)) {
// If the user location is not in jordan add it to the delete list
usersToDelete.push(user._id);
cronLogger.debug(
`User ${user.username} has been added to the delete list duo location not being in jordan`
);
}
} catch (error) {
if (error.errors[0].type == "NOT_FOUND") {
octokitLogger.debug(`The user ${user.username} was not found`);
// If the user was not found in github add it to the delete list
usersToDelete.push(user._id);
cronLogger.info(
"User has been added to the delete list duo not being found"
);
} else {
octokitLogger.error(error);
throw err;
}
}
}
try {
// Delete all the users in the delete list in one single query
await User.deleteMany({
_id: {
$in: usersToDelete,
},
});
} catch (error) {
dbLogger.error("Could not delete users: ", error);
}
cronLogger.info("Database cleanup finished");
};
const GetUserCommitContributionFromDB = async _username => {
let user = await User.findOne(
{ username: _username },
"commit_contributions"
);
let userCommits = user.commit_contributions;
return userCommits;
};
const ExtractContributionsForUser = async _user => {
try {
let commitsContributions = await GetUserCommitContributionFromDB(
_user.username
);
let commits = [];
let newResult = {
repositoryName: "",
starsCount: 0,
url: "",
commits: commits,
};
let response = await octokit.graphql(`{
user(login: "${_user.username}") {
contributionsCollection {
commitContributionsByRepository {
contributions(first: 100) {
nodes {
commitCount
occurredAt
repository {
id
name
stargazerCount
isPrivate
url
}
}
}
}
}
}
}`);
let data =
response.user.contributionsCollection.commitContributionsByRepository;
for (const contribution of data) {
let nodes = contribution.contributions.nodes;
for (const node of nodes) {
if (!node.repository.isPrivate) {
let commitObj = {
commitCount: node.commitCount,
occurredAt: node.occurredAt,
};
newResult = {
repositoryName: node.repository.name,
starsCount: node.repository.stargazerCount,
url: node.repository.url,
commits: [...commits, commitObj],
};
if (!isRepoBlocked(newResult.repositoryName)) {
let repositoryExists = commitsContributions.some(
x => x.url === node.repository.url
);
if (repositoryExists) {
let objToUpdate = commitsContributions.find(
element => element.url === node.repository.url
);
let commitExists = objToUpdate.commits.some(
x => x.occurredAt == node.occurredAt
);
objToUpdate["starsCount"] = node.repository.stargazerCount;
if (!commitExists) {
objToUpdate.commits = [...objToUpdate.commits, commitObj];
}
} else {
commitsContributions.push(newResult);
}
}
}
}
}
return commitsContributions;
} catch (error) {
if (error?.errors) {
if (error?.errors[0]?.type === "NOT_FOUND") {
octokitLogger.debug(`The user ${_user.username} was not found`);
await User.deleteOne({ username: _user.username });
} else {
octokitLogger.error(error?.errors);
throw error;
}
} else if (error instanceof RequestError) {
octokitLogger.error(error.message);
throw error;
} else {
cronLogger.error(error);
throw error;
}
}
};
const GetUserIssueContributionFromDB = async _user => {
let user = await User.findOne({ username: _user }, "issue_contributions");
let userIssues = user?.issue_contributions;
if (userIssues) {
return userIssues;
} else {
return [];
}
};
const GetUserPrContributionFromDB = async _username => {
let user = await User.findOne({ username: _username }, "pr_contributions");
let userPrs = user?.pr_contributions;
if (userPrs) {
return userPrs;
} else {
return [];
}
};
const extractPrContributionForUser = async _user => {
let prContributions = await GetUserPrContributionFromDB(_user.username);
let pullRequests = [];
let newResult = {
repositoryName: "",
starsCount: 0,
url: "",
pullRequests: pullRequests,
};
try {
let response = await octokit.graphql(`
{
user(login: "${_user.username}") {
contributionsCollection {
pullRequestContributionsByRepository {
contributions(first: 100) {
nodes {
occurredAt
pullRequest {
repository {
id
name
isPrivate
stargazerCount
url
}
}
}
}
}
}
}
}`);
let data =
response.user.contributionsCollection
.pullRequestContributionsByRepository;
for (const contribution of data) {
let nodes = contribution.contributions.nodes;
for (const node of nodes) {
if (!node.pullRequest.repository.isPrivate) {
let prObj = {
occurredAt: node.occurredAt,
};
newResult = {
repositoryName: node.pullRequest.repository.name,
starsCount: node.pullRequest.repository.stargazerCount,
url: node.pullRequest.repository.url,
pullRequests: [...pullRequests, prObj],
};
if (!isRepoBlocked(newResult.repositoryName)) {
let repositoryExists = prContributions.some(
x => x.url === newResult.url
);
if (repositoryExists) {
let objToUpdate = prContributions.find(
element => element.url === newResult.url
);
let prExists = objToUpdate.pullRequests.some(
x => x.occurredAt == node.occurredAt
);
objToUpdate["starsCount"] =
node.pullRequest.repository.stargazerCount;
if (!prExists) {
objToUpdate.pullRequests = [...objToUpdate.pullRequests, prObj];
}
} else {
prContributions.push(newResult);
}
}
}
}
}
return prContributions;
} catch (error) {
if (error?.errors) {
if (error?.errors[0]?.type === "NOT_FOUND") {
await User.deleteOne({ username: _user.username });
} else {
octokitLogger.error(error?.errors);
throw error;
}
} else if (error instanceof RequestError) {
octokitLogger.error(error.message);
throw error;
} else {
cronLogger.error(error);
throw error;
}
}
};
const GetUserCodeReviewContributionFromDB = async _username => {
let user = await User.findOne(
{ username: _username },
"code_review_contributions"
);
let userCodeReviews = user?.code_review_contributions;
if (userCodeReviews) {
return userCodeReviews;
} else {
return [];
}
};
const extractCodeReviewContributionForUser = async _user => {
let codeReviewContributions = await GetUserCodeReviewContributionFromDB(
_user.username
);
let codeReviews = [];
let newResult = {
repositoryName: "",
starsCount: 0,
url: "",
codeReviews: codeReviews,
};
try {
let response = await octokit.graphql(`
{
user(login: "${_user.username}") {
contributionsCollection {
pullRequestReviewContributionsByRepository {
contributions(first: 100) {
nodes {
occurredAt
repository {
id
name
isPrivate
stargazerCount
url
}
}
}
}
}
}
}`);
let data =
response.user.contributionsCollection
.pullRequestReviewContributionsByRepository;
for (const contribution of data) {
let nodes = contribution.contributions.nodes;
for (const node of nodes) {
if (!node.repository.isPrivate) {
let codeReviewObj = {
occurredAt: node.occurredAt,
};
newResult = {
repositoryName: node.repository.name,
starsCount: node.repository.stargazerCount,
url: node.repository.url,
codeReviews: [...codeReviews, codeReviewObj],
};
if (!isRepoBlocked(newResult.repositoryName)) {
let repositoryExists = codeReviewContributions.some(
x => x.url === newResult.url
);
if (repositoryExists) {
let objToUpdate = codeReviewContributions.find(
element => element.url === newResult.url
);
let prExists = objToUpdate.codeReviews.some(
x => x.occurredAt == node.occurredAt
);
objToUpdate["starsCount"] = node.repository.stargazerCount;
if (!prExists) {
objToUpdate.codeReviews = [
...objToUpdate.codeReviews,
codeReviewObj,
];
}
} else {
codeReviewContributions.push(newResult);
}
}
}
}
}
return codeReviewContributions;
} catch (error) {
if (error?.errors) {
if (error?.errors[0]?.type === "NOT_FOUND") {
await User.deleteOne({ username: _user.username });
} else {
octokitLogger.error(error?.errors);
throw error;
}
} else if (error instanceof RequestError) {
octokitLogger.error(error.message);
throw error;
} else {
cronLogger.error(error);
throw error;
}
}
};
const extractIssuesContributionsForUser = async _user => {
let issuesContributions = await GetUserIssueContributionFromDB(
_user.username
);
let endCursor = null;
let hasNextPage = true;
let issues = [];
while (hasNextPage) {
try {
let pageCursor = endCursor === null ? `${endCursor}` : `"${endCursor}"`;
let response = await octokit.graphql(`{
user(login: "${_user.username}") {
contributionsCollection {
issueContributions(first: 100, after: ${pageCursor}) {
nodes {
occurredAt
issue {
repository {
id
name
stargazerCount
isPrivate
url
}
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
}
}`);
let data = response.user.contributionsCollection.issueContributions.nodes;
for (const contribution of data) {
const issue = contribution.issue;
if (!issue.repository.isPrivate) {
let IssueObj = {
occurredAt: contribution.occurredAt,
};
const newResult = {
repositoryName: issue.repository.name,
starsCount: issue.repository.stargazerCount,
url: issue.repository.url,
issues: [...issues, IssueObj],
};
if (!isRepoBlocked(newResult.repositoryName)) {
let repositoryExists = issuesContributions.some(
x => x.url === newResult.url
);
if (repositoryExists) {
let objToUpdate = issuesContributions.find(
element => element.url === newResult.url
);
let issueExists = objToUpdate.issues.some(
x => x.occurredAt == contribution.occurredAt
);
objToUpdate["starsCount"] = newResult.starsCount;
if (!issueExists) {
objToUpdate.issues = [...objToUpdate.issues, IssueObj];
}
} else {
issuesContributions.push(newResult);
}
}
}
}
hasNextPage =
response.user.contributionsCollection.issueContributions.pageInfo
.hasNextPage;
endCursor =
response.user.contributionsCollection.issueContributions.pageInfo
.endCursor;
} catch (error) {
if (error?.errors) {
if (error?.errors[0]?.type === "NOT_FOUND") {
await User.deleteOne({ username: _user.username });
hasNextPage = false;
} else {
octokitLogger.error(error?.errors);
throw error;
}
} else if (error instanceof RequestError) {
octokitLogger.error(error.message);
throw error;
} else {
cronLogger.error(error);
throw error;
}
}
}
return issuesContributions;
};
const SaveUserContributionsToDB = async () => {
let users = await GetUsersFromDB({}, "username");
for (const user of users) {
cronLogger.debug(`Updating user ${user.username}...`);
let userCommits = await ExtractContributionsForUser(user);
let userIssues = await extractIssuesContributionsForUser(user);
let userPullRequests = await extractPrContributionForUser(user);
let userCodeReviews = await extractCodeReviewContributionForUser(user);
try {
await User.updateOne(
{ username: user.username },
{
commit_contributions: userCommits,
issue_contributions: userIssues,
pr_contributions: userPullRequests,
code_review_contributions: userCodeReviews,
}
);
cronLogger.debug(`Finished updating user ${user.username}`);
} catch (err) {
dbLogger.error(`Could not update ${user.username} contributions: ${err}`);
throw err;
}
}
};
const SaveOrganizationsToDB = async _organizations => {
for (const org of _organizations) {
let orgExists = await Organization.exists({ username: org.login });
if (!orgExists) {
let newOrg = new Organization({
username: org.login,
avatar_url: org.avatarUrl,
name: org.name,
location: org.location,
github_profile_url: org.url,
organization_createdAt: org.createdAt,
});
await newOrg.save();
dbLogger.debug(
`Organization: ${newOrg.username} and the location is ${newOrg.location} was saved to DB`
);
} else {
dbLogger.debug(`Organization: ${org.login} Exists`);
}
}
};
const GetOrganizationRepoFromDB = async _organization => {
let org = await Organization.findOne(
{ username: _organization },
"repositories"
);
let orgRepos = org.repositories;
return orgRepos;
};
const SaveOrganizationsRepositoriesToDB = async () => {
let organizations = await Organization.find({}, "username");
for (const org of organizations) {
try {
let orgRepos = await ExtractOrganizationRepositoriesFromGithub(org);
await Organization.updateOne(
{ username: org.username },
{ repositories: orgRepos }
);
dbLogger.debug(`Organization: ${org.username}, Repositories Added`);
} catch (err) {
dbLogger.error(`Could not update ${org.username} repositories: ${err}`);
throw err;
}
}
};
const ExtractOrganizationsFromGithub = async () => {
let locationsToSearch = [
"Jordan",
"Amman",
"Aqaba",
"Madaba",
"Irbid",
"Zarqa",
"Jerash",
"Al-Karak",
"Maan",
"Ajloun",
];
let extractedOrganizations = [];
for (let index = 0; index < locationsToSearch.length; index++) {
let endCursor = null;
let hasNextPage = true;
while (hasNextPage) {
let pageCursor = endCursor === null ? `${endCursor}` : `"${endCursor}"`;
let result = await octokit.graphql(
`{
search(query: "location:${locationsToSearch[index]} type:org", type: USER, first: 100, after: ${pageCursor}) {
nodes {
... on Organization {
id
login
avatarUrl
name
location
url
createdAt
}
}
pageInfo {
endCursor
hasNextPage
}
}
}`
);
let newOrg = await result.search.nodes;
for (const org of newOrg) {
if (isInJordan(org.location)) {
extractedOrganizations = [...extractedOrganizations, org];
}
}
hasNextPage = await result.search.pageInfo.hasNextPage;
endCursor = await result.search.pageInfo.endCursor;
}
}
await SaveOrganizationsToDB(extractedOrganizations);
};
const ExtractOrganizationRepositoriesFromGithub = async _organization => {
let organizationRepositories = await GetOrganizationRepoFromDB(
_organization.username
);
let endCursor = null;
let hasNextPage = true;
while (hasNextPage) {
try {
let pageCursor = endCursor === null ? `${endCursor}` : `"${endCursor}"`;
let response = await octokit.graphql(`{
organization(login: "${_organization.username}") {
repositories(privacy: PUBLIC, first: 100, after: ${pageCursor}) {
nodes {
name
stargazerCount
}
pageInfo {
endCursor
hasNextPage
}
}
}
}`);
endCursor = await response.organization.repositories.pageInfo.endCursor;
let data = response.organization.repositories.nodes;
for (const repo of data) {
let newResult = {
name: repo.name,
starsCount: repo.stargazerCount,
};
let repositoryExists = organizationRepositories.some(
x => x.name == repo.name
);
if (repositoryExists) {
let objToUpdate = organizationRepositories.find(
element => element.name == repo.name
);
objToUpdate.starsCount = repo.stargazerCount;
} else {
organizationRepositories.push(newResult);
}
}
hasNextPage = await response.organization.repositories.pageInfo
.hasNextPage;
} catch (err) {
if (err.errors[0].type == "NOT_FOUND") {
octokitLogger.debug(
`The organization ${_organization.username} was not found`
);
await Organization.deleteOne({ username: _organization.username });
// if the request failed exit the loop
hasNextPage = false;
} else {
octokitLogger.error(err);
throw err;
}
}
}
return organizationRepositories;
};
const UpdateOrganizationsInfo = async () => {
const orgs = await Organization.find({});
for (const org of orgs) {
const orgCreatedAt = await ExtractOrganizationCreateDate(org.username);
if (orgCreatedAt) {
await Organization.updateOne(
{ username: org.username },
{ organization_createdAt: orgCreatedAt }
);
}
}
};
const ExtractOrganizationCreateDate = async _orgUsername => {
try {
let response = await octokit.graphql(`{
organization(login: "${_orgUsername}") {
createdAt
}
}`);
return response.organization.createdAt;
} catch (err) {
if ((err.type = "NOT_FOUND")) {
dbLogger.debug(`The organization ${_orgUsername} was not found`);
await Organization.deleteOne({ username: _orgUsername });
}
}
};
const ExtractOrganizationMembers = async _orgUsername => {
try {
let response = await octokit.graphql(`{
organization(login: "${_orgUsername}") {
membersWithRole(first: 100) {
nodes {
id
login