Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cheerio type fix #591

Merged
merged 4 commits into from
Aug 16, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix: correctly derive the type definitions of cheerio's Elements, `…
…TagElement`s, etc.
UNIDY2002 committed Aug 16, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
commit 41fbcd4ab97dc70b8cb29da8e8fc479287929c22
12 changes: 6 additions & 6 deletions packages/thu-info-lib/src/lib/basics.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import cheerio from "cheerio";
import type {ElementType} from "domelementtype";
import type {DataNode, Element} from "domhandler";
import {getCsrfToken, roamingWrapperWithMocks} from "./core";
import {
ASSESSMENT_BASE_URL,
@@ -56,9 +58,7 @@ import {CalendarData} from "../models/schedule/calendar";
import {Invoice} from "../models/home/invoice";
import {Classroom, ClassroomState, ClassroomStateResult, ClassroomStatus} from "../models/home/classroom";

type Cheerio = ReturnType<typeof cheerio>;
type Element = Cheerio[number];
type TagElement = Element & {type: "tag"};
type TagElement = Element & {type: ElementType.Tag};

export const webVPNTitle = "<title>清华大学WebVPN</title>";
export const systemMessage = "time out用户登陆超时或访问内容不存在。请重试";
@@ -244,7 +244,7 @@ export const getAssessmentList = (
getCheerioText(element, 5),
getCheerioText(element, 9) === "是",
href,
],
] as [string, boolean, string],
];
})
.get();
@@ -425,7 +425,7 @@ export const getClassroomState = (
.filter((it) => it.type === "tag" && it.tagName === "tr")
.map((tr) => {
const name =
((tr as TagElement).children[1] as TagElement).children[2].data?.trim() ??
(((tr as TagElement).children[1] as TagElement).children[2] as DataNode).data?.trim() ??
"";
const status = (tr as TagElement).children
.slice(3)
@@ -521,7 +521,7 @@ export const getBankPayment = async (
const $ = cheerio.load(result);
const titles = $("div strong")
.map((_, e) => {
const text = (e as TagElement).children[0].data?.trim();
const text = ((e as TagElement).children[0] as DataNode).data?.trim();
if (text === undefined) {
return undefined;
}
15 changes: 8 additions & 7 deletions packages/thu-info-lib/src/lib/cr.ts
Original file line number Diff line number Diff line change
@@ -20,6 +20,8 @@ import {
} from "../constants/strings";
import {uFetch} from "../utils/network";
import cheerio from "cheerio";
import type {ElementType} from "domelementtype";
import type {DataNode, Element} from "domhandler";
import {
CoursePlan,
CrPrimaryOpenInfo,
@@ -52,10 +54,9 @@ import {
MOCK_SEARCH_COURSE_PRIORITY_META,
MOCK_SELECTED_COURSES,
} from "../mocks/cr";
import TagElement = cheerio.TagElement;
import Element = cheerio.Element;
import TextElement = cheerio.TextElement;
type TagElement = Element & {type: ElementType.Tag};
import dayjs from "dayjs";
import {CheerioAPI} from "cheerio";

export const getCrTimetable = (helper: InfoHelper): Promise<CrTimetable[]> => roamingWrapperWithMocks(
helper,
@@ -152,7 +153,7 @@ export const getCrAvailableSemesters = async (helper: InfoHelper): Promise<CrSem
const $ = await crFetch((helper.graduate() ? CR_TREE_YJS_URL : CR_TREE_URL) + baseSemIdRes[1]).then(cheerio.load);
return $("option").toArray().map((e) => ({
id: (e as TagElement).attribs.value,
name: ((e as TagElement).children[0] as TextElement).data?.trim(),
name: ((e as TagElement).children[0] as DataNode).data?.trim(),
} as CrSemester));
},
MOCK_AVAILABLE_SEMESTERS,
@@ -198,8 +199,8 @@ const getText = (e: Element, index: number) => {
return cheerio((e as TagElement).children[index]).text().trim();
};

const parseFooter = ($: cheerio.Root) => {
const footerText = (($("p.yeM").toArray()[0] as TagElement).children[5].data as string).trim().replace(/,/g, "");
const parseFooter = ($: CheerioAPI) => {
const footerText = ((($("p.yeM").toArray()[0] as TagElement).children[5] as DataNode).data as string).trim().replace(/,/g, "");
const regResult = /第 (\d+) ?页 \/ 共 (\d+) 页(共 (\d+) 条记录)/.exec(footerText);
if (regResult === null || regResult.length !== 4) {
throw new CrError("cannot parse cr remaining footer data");
@@ -500,7 +501,7 @@ export const searchCoursePriorityMeta = async (
const pad = $(".pad");
return {
curr: pad.find("font").text(),
next: (pad[0] as TagElement).children[5].data?.trim() ?? "",
next: ((pad[0] as TagElement).children[5] as DataNode).data?.trim() ?? "",
};
},
MOCK_SEARCH_COURSE_PRIORITY_META,
8 changes: 4 additions & 4 deletions packages/thu-info-lib/src/lib/dorm.ts
Original file line number Diff line number Diff line change
@@ -10,15 +10,15 @@ import {
CHANGE_HOME_PASSWORD_URL,
} from "../constants/strings";
import cheerio from "cheerio";
import type {ElementType} from "domelementtype";
import type {Element} from "domhandler";
import {generalGetPayCode} from "../utils/alipay";
import {getCheerioText} from "../utils/cheerio";
import {InfoHelper} from "../index";
import {uFetch} from "../utils/network";
import {MOCK_DORM_SCORE_BASE64, MOCK_ELE_PAY_RECORD, MOCK_ELE_REMAINDER} from "../mocks/dorm";
import {DormAuthError, EleError} from "../utils/error";
type Cheerio = ReturnType<typeof cheerio>;
type Element = Cheerio[number];
type TagElement = Element & {type: "tag"};
type TagElement = Element & {type: ElementType.Tag};

export const getDormScore = (helper: InfoHelper, dormPassword: string): Promise<string> =>
roamingWrapperWithMocks(
@@ -85,7 +85,7 @@ export const getElePayRecord = async (
.map((index, element) => [
(element as TagElement).children
.filter((it) => it.type === "tag" && it.tagName === "td")
.map((it) => getCheerioText(it, 1)),
.map((it) => getCheerioText(it, 1)) as [string, string, string, string, string, string],
])
.get();
},
6 changes: 3 additions & 3 deletions packages/thu-info-lib/src/lib/library.ts
Original file line number Diff line number Diff line change
@@ -41,6 +41,8 @@ import {
weightedValidityAndId,
} from "../models/home/library";
import cheerio from "cheerio";
import type {ElementType} from "domelementtype";
import type {Element} from "domhandler";
import {getCheerioText} from "../utils/cheerio";
import dayjs from "dayjs";
import {InfoHelper} from "../index";
@@ -58,9 +60,7 @@ import {
LoginError,
} from "../utils/error";

type Cheerio = ReturnType<typeof cheerio>;
type Element = Cheerio[number];
type TagElement = Element & {type: "tag"};
type TagElement = Element & {type: ElementType.Tag};

const fetchJson = (
url: string,
4 changes: 3 additions & 1 deletion packages/thu-info-lib/src/lib/sports.ts
Original file line number Diff line number Diff line change
@@ -19,7 +19,9 @@ import {
import {SportsIdInfo, SportsReservationRecord, SportsResource, SportsResourcesInfo} from "../models/home/sports";
import {MOCK_RECORDS, MOCK_RESOURCES} from "../mocks/sports";
import cheerio from "cheerio";
import TagElement = cheerio.TagElement;
import type {ElementType} from "domelementtype";
import type {Element} from "domhandler";
type TagElement = Element & {type: ElementType.Tag};
import {generalGetPayCode} from "../utils/alipay";
import {getCheerioText} from "../utils/cheerio";
import {LibError, SportsError} from "../utils/error";
2 changes: 1 addition & 1 deletion packages/thu-info-lib/src/mocks/basics.ts
Original file line number Diff line number Diff line change
@@ -84,7 +84,7 @@ export const MOCK_REPORT = [
},
];

export const MOCK_ASSESSMENT_LIST = [
export const MOCK_ASSESSMENT_LIST: [string, boolean, string][] = [
["微积分A(2)", true, "Mr. Z"],
["高等线性代数选讲", true, "Mr. L"],
["大学物理B(1)", true, "Mr. L"],
2 changes: 1 addition & 1 deletion packages/thu-info-lib/src/mocks/dorm.ts

Large diffs are not rendered by default.

10 changes: 5 additions & 5 deletions packages/thu-info-lib/src/models/home/assessment.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import cheerio from "cheerio";
import type {Cheerio} from "cheerio";
import type {ElementType} from "domelementtype";
import type {Element} from "domhandler";
import {AssessmentError} from "../../utils/error";

type Cheerio = ReturnType<typeof cheerio>;
type Element = Cheerio[number];
type TagElement = Element & {type: "tag"};
type TagElement = Element & {type: ElementType.Tag};

const flatMap = <T, R>(arr: T[], transform: (item: T, index: number) => R[]) =>
arr.reduce(
@@ -160,7 +160,7 @@ const assert = (exp: boolean) => {
/**
* Read persons data from their corresponding html tables.
*/
export const toPersons = (tables: Cheerio) => {
export const toPersons = (tables: Cheerio<Element>) => {
const persons: Person[] = [];
let table = tables.children("table").first();
while (table.children().length > 0) {
16 changes: 8 additions & 8 deletions packages/thu-info-lib/src/utils/cheerio.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import cheerio from "cheerio";
type Cheerio = ReturnType<typeof cheerio>;
type Element = Cheerio[number];
type Tag = Element & {type: "tag"};
import type {ElementType} from "domelementtype";
import type {DataNode, Element, Node} from "domhandler";
type Tag = Element & {type: ElementType.Tag};

// TODO: Merge two functions
export const getCheerioText = (element: Element, index?: number) =>
export const getCheerioText = (element: Node, index?: number) =>
index === undefined
? (element as Tag).firstChild?.data?.trim() ?? ""
: ((element as Tag).children[index] as Tag).firstChild?.data?.trim() ?? "";
? ((element as Tag).firstChild as DataNode)?.data?.trim() ?? ""
: (((element as Tag).children[index] as Tag).firstChild as DataNode)?.data?.trim() ?? "";

export const getTrimmedData = (element: Element, indexChain: number[]) => {
const tElement = cheerio(element);
@@ -16,10 +16,10 @@ export const getTrimmedData = (element: Element, indexChain: number[]) => {
indexChain
.slice(1)
.forEach((val) => {
res = (res as Tag).children[val];
res = (res as Tag).children[val] as Element;
});

return res.data?.trim() ?? "";
return (res as Node as DataNode).data?.trim() ?? "";
} catch {
return "";
}