-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthor.service.ts
443 lines (397 loc) · 18.4 KB
/
author.service.ts
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
import { authorNameSchema } from "./author.shape";
import { SitemapItem } from "./types";
import { supabase } from "./supabase.server";
import { packageIdSchema } from "./package.shape";
import { slog } from "../modules/observability.server";
import { PackageService } from "./package.service";
import { uniqBy } from "es-toolkit";
import { Tables } from "./supabase.types.generated";
import TTLCache from "@isaacs/ttlcache";
import { format, hoursToMilliseconds } from "date-fns";
type CacheKey = "sitemap-items" | "count-authors";
type CacheValue = SitemapItem[] | number;
export class AuthorService {
private static cache = new TTLCache<CacheKey, CacheValue>({
ttl: hoursToMilliseconds(6),
});
private static readonly sitemapDivisor = 1000;
/**
*
* @param authorName
* @returns
*/
static async getAuthorDetailsByName(authorName: string) {
authorNameSchema.parse(authorName);
const author = await supabase
.from("authors")
.select("*")
.eq("name", authorName)
.maybeSingle();
if (author.error || !author.data) {
return null;
}
const authorPackages = (
(await PackageService.getPackagesByAuthorId(author.data.id)) || []
)
.map((pkg) => ({
package: pkg.package as unknown as {
id: number;
name: string;
title: string;
description: string;
},
roles: pkg.roles,
}))
// Deduplicate packages by ID
.filter(
(pkg, index, self) =>
index ===
self.findIndex((other) => other.package.id === pkg.package.id),
);
const packageIds = uniqBy(
authorPackages.map((pkg) => pkg.package.id),
(id) => id,
);
const otherAuthors = await Promise.all(
packageIds.map((id) =>
this.getAuthorsByPackageId(id).then((authors) =>
authors
?.filter(
({ author: otherAuthor }) => author.data!.id !== otherAuthor.id,
)
.map(({ author }) => author),
),
),
).then((authors) =>
uniqBy(authors.flat(), (author) => author).filter(
(author, index, self) =>
author &&
index === self.findIndex((other) => other?.id === author.id),
),
);
const description = this.generateAuthorDescription(
authorName,
authorPackages.map((pkg) => pkg.package.name),
otherAuthors.map((author) => author?.name || "").filter(Boolean),
);
return {
authorName,
packages: authorPackages,
otherAuthors,
description,
};
}
/**
*
* @param packageId
* @returns
*/
static async getAuthorsByPackageId(packageId: number) {
packageIdSchema.parse(packageId);
const { data, error } = await supabase
.from("author_cran_package")
.select(
`
author:author_id (*),
roles,
package_id
`,
)
.eq("package_id", packageId);
if (error) {
slog.error("Error in getAuthorsByPackageId", error);
return null;
}
if (!data) {
return [];
}
return data as unknown as Array<{
roles: string[] | null;
package_id: number;
author: Tables<"authors">;
}>;
}
/**
*
* @param authorId
* @returns
*/
static async checkAuthorExistsByName(authorName: string) {
authorNameSchema.parse(authorName);
const { count, error } = await supabase
.from("authors")
.select("id", { count: "exact", head: true })
.eq("name", authorName);
if (error) {
slog.error("Error in checkAuthorExistsByName", error);
return false;
}
return count === 1;
}
/**
*
* @returns
*/
static async getAllSitemapAuthors(): Promise<SitemapItem[]> {
const cached = this.cache.get("sitemap-items") as SitemapItem[] | undefined;
if (cached) {
return cached;
}
const countRes = await supabase
.from("authors")
.select("id,name", { count: "exact", head: true });
if (countRes.error) {
slog.error("Error in getAllSitemapAuthors", countRes.error);
return [];
}
const chunks = Math.ceil((countRes.count ?? 0) / this.sitemapDivisor);
const sitemapItems: SitemapItem[] = [];
// Sequentially fetch all the chunks to avoid hitting the rate limit,
// and no Promise.all to not stress the server too much.
for (let i = 0; i < chunks; i++) {
const { data, error } = await supabase
.from("authors")
.select("name,_last_scraped_at")
.range(i * this.sitemapDivisor, (i + 1) * this.sitemapDivisor - 1);
if (error) {
slog.error("Error in getAllSitemapAuthors", error);
return [];
}
data.forEach((item) => {
sitemapItems.push([
this.sanitizeSitemapName(item.name),
format(new Date(item._last_scraped_at), "yyyy-MM-dd"),
]);
});
}
this.cache.set("sitemap-items", sitemapItems);
return sitemapItems;
}
static async getTotalAuthorsCount(): Promise<number> {
const cached = this.cache.get("count-authors") as number | undefined;
if (cached) {
return cached;
}
const { count, error } = await supabase
.from("authors")
.select("id", { count: "exact", head: true });
if (error) {
slog.error("Error in getAuthorsCount", error);
return 0;
}
this.cache.set("count-authors", count ?? 0);
return count ?? 0;
}
/**
*
* @param query
* @param options
* @returns
*/
static async searchAuthors(query: string, options?: { limit?: number }) {
const { limit = 8 } = options || {};
const [fts, exact] = await Promise.all([
supabase.rpc("find_closest_authors", {
search_term: query,
result_limit: limit,
max_levenshtein_distance: 8,
}),
supabase
.from("authors")
.select("id,name")
.ilike("name", query)
.maybeSingle(),
]);
if (fts.error) {
slog.error("Error in searchAuthors", fts.error);
throw fts.error;
}
if (exact.error) {
slog.error("Error in searchAuthors", exact.error);
throw exact.error;
}
const lexical = fts.data;
if (exact.data) {
lexical.unshift({
id: exact.data.id,
name: exact.data.name,
levenshtein_distance: 0,
});
}
return uniqBy(lexical, (author) => author.id);
}
/**
*
* @param name
* @returns
*/
private static sanitizeSitemapName(name: string) {
let next = name.trim();
if (next.startsWith(`"`)) next = next.slice(1);
if (next.endsWith(`"`)) next = next.slice(0, -1);
if (next.startsWith("'")) next = next.slice(1);
if (next.endsWith("'")) next = next.slice(0, -1);
if (next.endsWith(",")) next = next.slice(0, -1);
return next.trim();
}
private static generateAuthorDescription(
authorName: string,
packages: string[],
otherAuthors: string[],
): string {
const packageCount = packages.length;
const otherAuthorCount = otherAuthors.length;
let packageDescription = "";
let authorDescription = "";
// Helper function to join author names naturally with 'and'
function joinAuthors(authors: string[]): string {
if (authors.length === 0) return "";
if (authors.length === 1) return authors[0];
return `${authors.slice(0, -1).join(", ")} and ${authors[authors.length - 1]}`;
}
// Helper function to randomly select from an array of strings
function getRandomDescription(descriptions: string[]): string {
return descriptions[Math.floor(Math.random() * descriptions.length)];
}
// Generate package description
if (packageCount === 1) {
const descriptions = [
`${authorName} has worked on just 1 package so far. But hey, every journey starts with a single step, right? This package might just be the beginning of something legendary!`,
`${authorName} is starting small with 1 package. Rome wasn't built in a day, and neither is a great portfolio!`,
`With 1 package under their belt, ${authorName} is just getting started. Great things often have humble beginnings!`,
];
packageDescription = getRandomDescription(descriptions);
} else if (packageCount === 2) {
const descriptions = [
`${authorName} has worked on 2 packages so far. Two's company, but it looks like ${authorName} is just getting warmed up!`,
`Two packages down, and ${authorName} is picking up steam. Just getting started!`,
`${authorName} has got 2 packages done. They say good things come in pairs, and this could be the start of a streak!`,
];
packageDescription = getRandomDescription(descriptions);
} else if (packageCount === 3) {
const descriptions = [
`${authorName} has worked on 3 packages. Three's a charm, and it seems like ${authorName} is finding their stride!`,
`Three packages in, and ${authorName} is just getting started. Momentum is building!`,
`${authorName} has completed 3 packages. That's enough to show some serious dedication!`,
];
packageDescription = getRandomDescription(descriptions);
} else if (packageCount === 4) {
const descriptions = [
`${authorName} has worked on 4 packages. That's some solid dedication, and ${authorName} is starting to build a nice little portfolio!`,
`Four packages in the books! ${authorName} is on a roll and showing no signs of slowing down.`,
`${authorName} has completed 4 packages, and it looks like they're just getting started. Keep an eye out for more!`,
];
packageDescription = getRandomDescription(descriptions);
} else if (packageCount === 5) {
const descriptions = [
`${authorName} has worked on 5 packages. High five to ${authorName}! That's a respectable number of projects!`,
`Five packages done, and ${authorName} is proving to be a force to be reckoned with.`,
`${authorName} has hit 5 packages. That's some impressive dedication right there!`,
];
packageDescription = getRandomDescription(descriptions);
} else if (packageCount > 5 && packageCount <= 10) {
const descriptions = [
`${authorName} has been quite busy, working on ${packageCount} packages. You could say ${authorName} is on a coding spree! Keep up the great work!`,
`${authorName} has worked on ${packageCount} packages so far. That's a lot of coding! Clearly, ${authorName} is on a mission.`,
`With ${packageCount} packages completed, ${authorName} is proving to be quite the prolific developer. Keep it up!`,
];
packageDescription = getRandomDescription(descriptions);
} else if (packageCount > 10 && packageCount <= 15) {
const descriptions = [
`${authorName} has worked on ${packageCount} packages so far. Wow, ${authorName} is really cranking out the code—this is dedication on another level!`,
`Impressive! ${authorName} has worked on ${packageCount} packages, showing some serious commitment to the craft.`,
`${authorName} has ${packageCount} packages under their belt. That's not just dedication, it's a passion for coding!`,
];
packageDescription = getRandomDescription(descriptions);
} else if (packageCount > 15 && packageCount <= 20) {
const descriptions = [
`${authorName} has worked on ${packageCount} packages. That's an impressive feat! ${authorName} must have some serious passion for coding.`,
`With ${packageCount} packages completed, ${authorName} is showing some serious coding chops. The future looks bright!`,
`${authorName} has put out ${packageCount} packages—clearly, they're unstoppable. Keep those packages coming!`,
];
packageDescription = getRandomDescription(descriptions);
} else if (packageCount > 20) {
const descriptions = [
`${authorName} has been on fire, working on ${packageCount} packages to date. Honestly, does ${authorName} even sleep? This is some serious dedication!`,
`${authorName} has completed over ${packageCount} packages! The dedication here is off the charts—clearly a coding superstar!`,
`${authorName} has worked on ${packageCount} packages, which is nothing short of amazing. Who needs sleep when you've got code to write?`,
];
packageDescription = getRandomDescription(descriptions);
} else {
packageDescription = `${authorName} hasn't worked on any packages yet, but stay tuned! Great things often start with a bit of patience.`;
}
// Generate author collaboration description
if (otherAuthorCount === 0) {
const descriptions = [
` A true lone wolf! ${authorName} prefers to code solo, blazing their own trail through the wilderness of software development.`,
` ${authorName} is going solo on this one. No distractions, just pure, undiluted coding power!`,
` No other authors involved—${authorName} likes to fly solo, and it shows in their work!`,
];
authorDescription = getRandomDescription(descriptions);
} else if (otherAuthorCount === 1) {
const descriptions = [
` ${authorName} has collaborated with 1 other author: ${joinAuthors(otherAuthors)}. Just the two of them, like a dynamic duo, making magic happen!`,
` ${authorName} worked with ${joinAuthors(otherAuthors)} on this project. A perfect partnership for some great results!`,
` One collaborator: ${joinAuthors(otherAuthors)}. ${authorName} knows how to pick the right partner to get the job done!`,
];
authorDescription = getRandomDescription(descriptions);
} else if (otherAuthorCount === 2) {
const descriptions = [
` ${authorName} has worked alongside 2 other authors: ${joinAuthors(otherAuthors)}. A trio of talent! Three heads are better than one, after all.`,
` ${authorName} teamed up with ${joinAuthors(otherAuthors)}. Three developers tackling the challenge together—what could be better?`,
` Three minds working as one—${authorName} and ${joinAuthors(otherAuthors)} brought their skills together for a stellar outcome.`,
];
authorDescription = getRandomDescription(descriptions);
} else if (otherAuthorCount === 3) {
const descriptions = [
` ${authorName} has worked with 3 other authors: ${joinAuthors(otherAuthors)}. Four brilliant minds coming together—what could go wrong?`,
` ${authorName} and their 3 collaborators—${joinAuthors(otherAuthors)}—made a fantastic team. Four is definitely not a crowd when it comes to coding!`,
` Working with 3 others, ${authorName} and ${joinAuthors(otherAuthors)} showed that teamwork makes the dream work!`,
];
authorDescription = getRandomDescription(descriptions);
} else if (otherAuthorCount === 4) {
const descriptions = [
` ${authorName} has collaborated with 4 other authors: ${joinAuthors(otherAuthors)}. Five people, five different ideas—sounds like a lot of fun!`,
` ${authorName} worked with 4 other talented individuals—${joinAuthors(otherAuthors)}. Five coders, one goal, endless possibilities!`,
` Four collaborators joined ${authorName} on this project, making for a team of five. With ${joinAuthors(otherAuthors)}, the possibilities were endless!`,
];
authorDescription = getRandomDescription(descriptions);
} else if (otherAuthorCount === 5) {
const descriptions = [
` ${authorName} has worked alongside 5 other authors: ${joinAuthors(otherAuthors)}. Six people coding together—it's like a party, but with more bugs and commits!`,
` ${authorName} and 5 others—${joinAuthors(otherAuthors)}—teamed up to tackle the challenge. A party of six, ready to conquer the code!`,
` With 5 collaborators, ${authorName} and ${joinAuthors(otherAuthors)} brought the energy of a six-person team to the project. It was an adventure!`,
];
authorDescription = getRandomDescription(descriptions);
} else if (otherAuthorCount > 5 && otherAuthorCount <= 10) {
const descriptions = [
` ${authorName} has joined forces with over ${otherAuthorCount} authors, making it a true team effort. Imagine all those brainstorming sessions—must've been epic!`,
` ${authorName} worked with ${otherAuthorCount} other authors. That's a lot of creative energy! No wonder the results were fantastic.`,
` Collaborating with ${otherAuthorCount} other authors, ${authorName} experienced the power of teamwork. The more, the merrier—especially in coding!`,
];
authorDescription = getRandomDescription(descriptions);
} else if (otherAuthorCount > 10 && otherAuthorCount <= 15) {
const descriptions = [
` ${authorName} has worked with ${otherAuthorCount} other authors. That's a whole squad of coders! It must be like managing a small battalion of creativity and caffeine.`,
` ${authorName} teamed up with ${otherAuthorCount} others, making it a large and lively crew of coders. The synergy must have been amazing!`,
` ${authorName} collaborated with ${otherAuthorCount} other developers. That's like an entire class of coding geniuses coming together!`,
];
authorDescription = getRandomDescription(descriptions);
} else if (otherAuthorCount > 15 && otherAuthorCount <= 20) {
const descriptions = [
` ${authorName} has collaborated with ${otherAuthorCount} other authors. That's a huge network of talent—imagine all those lines of communication and brilliant ideas flying around!`,
` With ${otherAuthorCount} collaborators, ${authorName} was part of a truly massive undertaking. It takes a village to code something great!`,
` ${authorName} and ${otherAuthorCount} other talented individuals worked together, forming a powerhouse of developers. That's some serious talent!`,
];
authorDescription = getRandomDescription(descriptions);
} else if (otherAuthorCount > 20) {
const descriptions = [
` ${authorName} has collaborated with a whopping ${otherAuthorCount} other authors. It's basically a small army of coders! Who knew package development could be such a social event?`,
` ${authorName} worked with over ${otherAuthorCount} collaborators. That's a huge group of developers—almost like a coding festival!`,
` ${authorName} teamed up with ${otherAuthorCount} other developers, making this project a gigantic collaborative effort. The coding world is a better place for it!`,
];
authorDescription = getRandomDescription(descriptions);
}
return packageDescription + authorDescription;
}
}