refactor: create abstract class

This commit is contained in:
kawamataryo
2024-11-20 20:07:44 +09:00
parent 20b04b9322
commit a14e5395e5
3 changed files with 61 additions and 38 deletions

View File

@@ -0,0 +1,37 @@
import { MESSAGE_NAME_TO_QUERY_PARAM_MAP } from "~lib/constants";
import type { CrawledUserInfo, MessageName } from "~types";
export abstract class AbstractService {
messageName: MessageName;
crawledUsers: Set<string>;
constructor(messageName: string) {
this.messageName = messageName as MessageName;
this.crawledUsers = new Set();
}
abstract extractUserData(userCell: Element): CrawledUserInfo;
getCrawledUsers(): CrawledUserInfo[] {
const userCells = Array.from(
document.querySelectorAll(
MESSAGE_NAME_TO_QUERY_PARAM_MAP[this.messageName],
),
);
const users = Array.from(userCells).map((userCell) =>
this.extractUserData(userCell),
)
.filter((user) => {
const isNewUser = !this.crawledUsers.has(user.accountName);
if (isNewUser) {
this.crawledUsers.add(user.accountName);
}
return isNewUser;
});
return users;
}
abstract performScrollAndCheckEnd(): Promise<boolean>;
}

View File

@@ -1,20 +1,11 @@
import { MESSAGE_NAMES } from "~lib/constants";
import { BSKY_DOMAIN, MESSAGE_NAME_TO_QUERY_PARAM_MAP } from "~lib/constants";
import { wait } from "~lib/utils";
import type { CrawledUserInfo, MessageName } from "~types";
import { AbstractService } from "./abstractService";
import type { CrawledUserInfo } from "~types";
export class XService {
// 対象のdomを取得する処理
messageName: MessageName;
crawledUsers: Set<string>;
constructor(messageName: string) {
// TODO: add type check
this.messageName = messageName as MessageName;
this.crawledUsers = new Set();
}
private extractUserData(userCell: Element): CrawledUserInfo {
export class XService extends AbstractService {
extractUserData(userCell: Element): CrawledUserInfo {
const anchors = Array.from(userCell.querySelectorAll("a"));
const [avatarEl, displayNameEl] = anchors;
const accountName = avatarEl?.getAttribute("href")?.replace("/", "");
@@ -39,25 +30,6 @@ export class XService {
};
}
getCrawledUsers(): CrawledUserInfo[] {
const userCells = Array.from(
document.querySelectorAll(
MESSAGE_NAME_TO_QUERY_PARAM_MAP[this.messageName],
),
);
const users = userCells
.map((userCell) => this.extractUserData(userCell))
.filter((user) => !this.crawledUsers.has(user.accountName));
this.crawledUsers = new Set([
...this.crawledUsers,
...users.map((user) => user.accountName),
]);
return users;
}
async performScrollAndCheckEnd(): Promise<boolean> {
const isListMembersPage =
this.messageName === MESSAGE_NAMES.SEARCH_BSKY_USER_ON_LIST_MEMBERS_PAGE;