|
1 | 1 | /*
|
2 | 2 | * Fetch users from the Stack Exchange API
|
3 | 3 | */
|
4 |
| -import { LruCache } from '../utils' |
| 4 | +import { Cache, LruCache } from '../utils' |
5 | 5 | import { StackExchangeAPI } from '../seAPI'
|
6 | 6 | import { minimalUserFilter, seAPIKey, userAPICacheSize } from '../constants'
|
7 | 7 |
|
8 |
| -import { DeletedUser, ExistingUser, User } from './classes' |
| 8 | +import { DeletedUser, ExistingUser, JSONLoadable, User } from './classes' |
9 | 9 |
|
10 |
| -type JSONUser = Parameters<(typeof ExistingUser)['fromJSON']>[0] |
11 |
| -const apiCache = new LruCache<number, User>(userAPICacheSize) |
12 |
| -const api = new StackExchangeAPI(seAPIKey) |
| 10 | +type UserFetcherOptions = { |
| 11 | + api: StackExchangeAPI |
| 12 | + cache: Cache<User['user_id'], User> |
| 13 | + missingAssumeDeleted: boolean |
| 14 | +} |
13 | 15 |
|
14 |
| -// Fetch users and yield User objects in the same order they are listed in the argument |
15 |
| -export async function* fetchUsers( |
16 |
| - userIds: number[], |
17 |
| - missingAssumeDeleted = false |
18 |
| -): AsyncGenerator<User, void, undefined> { |
19 |
| - // split into still-cached and to-be-fetched uids |
20 |
| - let toFetch: number[] = [] |
21 |
| - const cached = new Map( |
22 |
| - userIds.reduce((resolved, uid) => { |
23 |
| - const user = apiCache.get(uid) |
24 |
| - if (user) return [...resolved, [uid, user]] |
25 |
| - toFetch.push(uid) |
26 |
| - return resolved |
27 |
| - }, [] as [number, User][]) |
28 |
| - ) |
29 |
| - // fetch the remaining uids in batches of 100 |
30 |
| - while (toFetch.length > 0) { |
31 |
| - const queryIds = toFetch.splice(0, 100) |
32 |
| - toFetch = toFetch.splice(100) |
33 |
| - const results = await api.fetch<JSONUser>( |
34 |
| - `/users/{ids}`, |
35 |
| - { ids: queryIds }, |
36 |
| - { filter: minimalUserFilter } |
37 |
| - ) |
| 16 | +export class UserFetcher< |
| 17 | + UserType extends JSONLoadable<User> = typeof ExistingUser, |
| 18 | + MissingUser extends User = DeletedUser |
| 19 | +> { |
| 20 | + private readonly api: StackExchangeAPI |
| 21 | + private readonly cache: Cache<User['user_id'], User> |
| 22 | + readonly missingAssumeDeleted: boolean = false |
| 23 | + |
| 24 | + constructor( |
| 25 | + private readonly UserClass: UserType, |
| 26 | + private readonly MissingClass: new (userId: User['user_id']) => MissingUser, |
| 27 | + options: UserFetcherOptions |
| 28 | + ) { |
| 29 | + this.api = options.api |
| 30 | + this.cache = options.cache |
| 31 | + this.missingAssumeDeleted = options.missingAssumeDeleted |
| 32 | + } |
| 33 | + |
| 34 | + static withDefaultClasses( |
| 35 | + options: Partial<UserFetcherOptions> = {} |
| 36 | + ): UserFetcher { |
| 37 | + const config: UserFetcherOptions = { |
| 38 | + api: options.api || new StackExchangeAPI(seAPIKey), |
| 39 | + cache: |
| 40 | + options.cache || new LruCache<User['user_id'], User>(userAPICacheSize), |
| 41 | + missingAssumeDeleted: |
| 42 | + options.missingAssumeDeleted === undefined |
| 43 | + ? false |
| 44 | + : options.missingAssumeDeleted, |
| 45 | + } |
| 46 | + return new UserFetcher(ExistingUser, DeletedUser, config) |
| 47 | + } |
| 48 | + |
| 49 | + /** Fetch users and yield User objects in the same order they are listed in the argument */ |
| 50 | + async *users( |
| 51 | + userIds: InstanceType<UserType>['user_id'][] |
| 52 | + ): AsyncIterableIterator<User> { |
| 53 | + const toFetch: number[] = [] |
38 | 54 | const byUserId = new Map(
|
39 |
| - results.map((user) => [user.user_id, ExistingUser.fromJSON(user)]) |
| 55 | + userIds.reduce((resolved, uid) => { |
| 56 | + const user = this.cache.get(uid) |
| 57 | + if (user === undefined) toFetch.push(uid) |
| 58 | + return user !== undefined ? [...resolved, [uid, user]] : resolved |
| 59 | + }, [] as [User['user_id'], User][]) |
40 | 60 | )
|
41 |
| - const lastFetched = userIds.indexOf(queryIds[queryIds.length - 1]) + 1 |
42 |
| - yield* userIds.splice(0, lastFetched).reduce((mapped, uid) => { |
43 |
| - let user = cached.get(uid) || byUserId.get(uid) |
44 |
| - if (user === undefined && missingAssumeDeleted) { |
45 |
| - user = new DeletedUser(uid) |
| 61 | + if (toFetch.length > 0) { |
| 62 | + const apiResults = this.api.fetchAll<Parameters<UserType['fromJSON']>[0]>( |
| 63 | + '/users/{ids}', |
| 64 | + { ids: toFetch }, |
| 65 | + { filter: minimalUserFilter } |
| 66 | + ) |
| 67 | + for await (const jsonUser of apiResults) { |
| 68 | + const user = this.UserClass.fromJSON(jsonUser) |
| 69 | + this.cache.put(user.user_id, user) |
| 70 | + byUserId.set(user.user_id, user) |
46 | 71 | }
|
47 |
| - if (user) apiCache.put(uid, user) |
48 |
| - return user ? [...mapped, user] : mapped |
49 |
| - }, []) |
50 |
| - userIds = userIds.splice(lastFetched) |
| 72 | + } |
| 73 | + const get = this.missingAssumeDeleted |
| 74 | + ? (uid: number) => byUserId.get(uid) || this.missingUser(uid) |
| 75 | + : (uid: number) => byUserId.get(uid) |
| 76 | + for (const uid of userIds) { |
| 77 | + const user = get(uid) |
| 78 | + if (user) yield user |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + private missingUser(userId: User['user_id']): MissingUser { |
| 83 | + const missing = new this.MissingClass(userId) |
| 84 | + this.cache.put(missing.user_id, missing) |
| 85 | + return missing |
51 | 86 | }
|
52 |
| - // yield any remaining cached users |
53 |
| - yield* userIds.map( |
54 |
| - (uid) => |
55 |
| - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
56 |
| - apiCache.get(uid)! |
57 |
| - ) |
58 | 87 | }
|
0 commit comments