1
0
Fork 0
mirror of https://github.com/classchartsapi/classcharts-api-js.git synced 2026-05-14 11:58:13 +00:00

feat: axios -> ky-universal

Better compat since ky uses fetch :)
E.g. cloudflare workers
This commit is contained in:
James Cook 2023-04-16 15:13:42 +01:00
parent 8b16f8d8a9
commit 629c998293
9 changed files with 645 additions and 740 deletions

View file

@ -1,5 +1,6 @@
{ {
"name": "classcharts-api", "name": "classcharts-api",
"type": "module",
"version": "2.0.0", "version": "2.0.0",
"description": "A typescript wrapper for getting information from the Classcharts API", "description": "A typescript wrapper for getting information from the Classcharts API",
"keywords": [ "keywords": [
@ -25,24 +26,24 @@
"author": "James Cook", "author": "James Cook",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"axios": "^1.3.5" "ky-universal": "^0.11.0"
}, },
"files": [ "files": [
"dist/**" "dist/**"
], ],
"devDependencies": { "devDependencies": {
"@types/jest": "^29.5.0", "@types/jest": "^29.5.0",
"@types/node": "^18", "@types/node": "^18.15.11",
"@typescript-eslint/eslint-plugin": "^5.57.1", "@typescript-eslint/eslint-plugin": "^5.58.0",
"@typescript-eslint/parser": "^5.57.1", "@typescript-eslint/parser": "^5.58.0",
"eslint": "^8.37.0", "eslint": "^8.38.0",
"eslint-config-prettier": "^8.8.0", "eslint-config-prettier": "^8.8.0",
"jest": "^29.5.0", "jest": "^29.5.0",
"jest-extended": "^3.2.4", "jest-extended": "^3.2.4",
"prettier": "^2.8.7", "prettier": "^2.8.7",
"ts-jest": "^29.1.0", "ts-jest": "^29.1.0",
"typedoc": "^0.23.28", "typedoc": "^0.24.2",
"typescript": "^5.0.3" "typescript": "^5.0.4"
}, },
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",
"exports": { "exports": {

1206
pnpm-lock.yaml generated

File diff suppressed because it is too large Load diff

View file

@ -1,11 +1,11 @@
import axios from "axios"; import ky, { type Options as KyOptions } from "ky-universal";
import type { AxiosRequestConfig, AxiosInstance } from "axios";
import type { import type {
ActivityResponse, ActivityResponse,
AnnouncementsResponse, AnnouncementsResponse,
AttendanceResponse, AttendanceResponse,
BadgesResponse, BadgesResponse,
BehaviourResponse, BehaviourResponse,
ClassChartsResponse,
DetentionsResponse, DetentionsResponse,
GetActivityOptions, GetActivityOptions,
GetAttendanceOptions, GetAttendanceOptions,
@ -16,8 +16,8 @@ import type {
GetStudentInfoResponse, GetStudentInfoResponse,
HomeworksResponse, HomeworksResponse,
LessonsResponse, LessonsResponse,
} from "./types"; } from "./types.js";
import { PING_INTERVAL } from "./consts"; import { PING_INTERVAL } from "./consts.js";
/** /**
* The base client * The base client
@ -28,21 +28,13 @@ export class ClasschartsClient {
public sessionId = ""; public sessionId = "";
public lastPing = 0; public lastPing = 0;
protected API_BASE = ""; protected API_BASE = "";
protected axios: AxiosInstance;
/** /**
* *
* @param API_BASE Base API URL, this is different depending if its called as a parent or student * @param API_BASE Base API URL, this is different depending if its called as a parent or student
*/ */
constructor(API_BASE: string, axiosConfig?: AxiosRequestConfig) { constructor(API_BASE: string) {
this.authCookies = []; this.authCookies = [];
this.API_BASE = API_BASE; this.API_BASE = API_BASE;
this.axios = axios.create({
...axiosConfig,
headers: {
...axiosConfig?.headers,
},
validateStatus: () => true,
});
} }
public async getNewSessionId() { public async getNewSessionId() {
const pingFormData = new URLSearchParams(); const pingFormData = new URLSearchParams();
@ -51,10 +43,7 @@ export class ClasschartsClient {
this.API_BASE + "/ping", this.API_BASE + "/ping",
{ {
method: "POST", method: "POST",
data: pingFormData.toString(), body: pingFormData,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
}, },
{ revalidateToken: false } { revalidateToken: false }
); );
@ -63,7 +52,7 @@ export class ClasschartsClient {
} }
public async makeAuthedRequest( public async makeAuthedRequest(
path: string, path: string,
axiosOptions: Omit<AxiosRequestConfig, "path">, kyOptions: KyOptions,
options?: { revalidateToken?: boolean } options?: { revalidateToken?: boolean }
) { ) {
if (!this.sessionId) throw new Error("No session ID"); if (!this.sessionId) throw new Error("No session ID");
@ -73,26 +62,29 @@ export class ClasschartsClient {
if (typeof options?.revalidateToken == "undefined") { if (typeof options?.revalidateToken == "undefined") {
options.revalidateToken = true; options.revalidateToken = true;
} }
const requestOptions: AxiosRequestConfig = { const requestOptions = {
...axiosOptions, ...kyOptions,
url: path,
headers: { headers: {
Cookie: this?.authCookies?.join(";") ?? [], Cookie: this?.authCookies?.join(";") ?? [],
authorization: "Basic " + this.sessionId, Authorization: "Basic " + this.sessionId,
...axiosOptions.headers, ...kyOptions.headers,
}, },
}; } satisfies KyOptions;
if (options?.revalidateToken === true && this.lastPing) { if (options?.revalidateToken === true && this.lastPing) {
if (Date.now() - this.lastPing + 5000 > PING_INTERVAL) { if (Date.now() - this.lastPing + 5000 > PING_INTERVAL) {
await this.getNewSessionId(); await this.getNewSessionId();
} }
} }
const request = await this.axios.request(requestOptions); const request = await ky(path, requestOptions);
const responseJSON = request.data; const responseJSON = (await request.json()) as ClassChartsResponse<
unknown,
unknown
>;
if (responseJSON.success == 0) { if (responseJSON.success == 0) {
throw new Error(responseJSON.error); throw new Error(responseJSON.error);
} }
return responseJSON; // eslint-disable-next-line @typescript-eslint/no-explicit-any
return responseJSON as any;
} }
/** /**
@ -100,9 +92,11 @@ export class ClasschartsClient {
* @returns Student object * @returns Student object
*/ */
async getStudentInfo(): Promise<GetStudentInfoResponse> { async getStudentInfo(): Promise<GetStudentInfoResponse> {
const body = new URLSearchParams();
body.append("include_data", "true");
const data = await this.makeAuthedRequest(this.API_BASE + "/ping", { const data = await this.makeAuthedRequest(this.API_BASE + "/ping", {
method: "POST", method: "POST",
data: "include_data=true", body: body,
}); });
return data; return data;
} }

View file

@ -1,2 +1,2 @@
export * from "./parentClient"; export * from "./parentClient.js";
export * from "./studentClient"; export * from "./studentClient.js";

View file

@ -1,9 +1,9 @@
import type { AxiosRequestConfig } from "axios"; import ky from "ky-universal";
import type { GetPupilsResponse } from "./types"; import type { GetPupilsResponse } from "./types.js";
import { ClasschartsClient } from "./baseClient"; import { ClasschartsClient } from "./baseClient.js";
import { API_BASE_PARENT, BASE_URL } from "./consts"; import { API_BASE_PARENT, BASE_URL } from "./consts.js";
import { parseCookies } from "./utils"; import { parseCookies } from "./utils.js";
/** /**
* Parent Client * Parent Client
*/ */
@ -17,12 +17,8 @@ export class ParentClient extends ClasschartsClient {
* @param email Parents email address * @param email Parents email address
* @param password Parents password * @param password Parents password
*/ */
constructor( constructor(email: string, password: string) {
email: string, super(API_BASE_PARENT);
password: string,
axiosConfig?: AxiosRequestConfig
) {
super(API_BASE_PARENT, axiosConfig);
this.email = String(email); this.email = String(email);
this.password = String(password); this.password = String(password);
} }
@ -38,36 +34,39 @@ export class ParentClient extends ClasschartsClient {
formData.append("logintype", "existing"); formData.append("logintype", "existing");
formData.append("password", this.password); formData.append("password", this.password);
formData.append("recaptcha-token", "no-token-avaliable"); formData.append("recaptcha-token", "no-token-avaliable");
const request = await this.axios.request({ const headers = new Headers({
url: BASE_URL + "/parent/login", "Content-Type": "application/x-www-form-urlencoded",
method: "POST",
data: formData.toString(),
maxRedirects: 0,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
validateStatus: () => true,
}); });
if (request.status != 302 || !request.headers["set-cookie"]) const response = await ky(BASE_URL + "/parent/login", {
throw new Error("Unauthenticated: Classcharts returned an error"); method: "POST",
body: formData,
headers: headers,
});
if (response.status != 302 || !response.headers.get("set-cookie"))
throw new Error(
"Unauthenticated: Classcharts returned an error: " +
response.status +
" " +
response.statusText
);
const cookies = String(request.headers["set-cookie"]); const cookies = String(response.headers.get("set-cookie"));
// this.authCookies = cookies.split(";"); // this.authCookies = cookies.split(";");
const sessionCookies = parseCookies(cookies); const sessionCookies = parseCookies(cookies);
const sessionID = JSON.parse( const sessionID = JSON.parse(
String(sessionCookies["parent_session_credentials"]) String(sessionCookies["parent_session_credentials"])
); );
this.sessionId = sessionID.session_id; super.sessionId = sessionID.session_id;
this.pupils = await this.getPupils(); this.pupils = await this.getPupils();
if (!this.pupils) throw new Error("Account has no pupils attached"); if (!this.pupils) throw new Error("Account has no pupils attached");
this.studentId = this.pupils[0].id; super.studentId = this.pupils[0].id;
} }
/** /**
* Get Pupil details * Get Pupil details
* @returns an array of Pupils connected to this parent's account * @returns an array of Pupils connected to this parent's account
*/ */
async getPupils(): Promise<GetPupilsResponse> { async getPupils(): Promise<GetPupilsResponse> {
return this.makeAuthedRequest(this.API_BASE + "/pupils", { return super.makeAuthedRequest(super.API_BASE + "/pupils", {
method: "GET", method: "GET",
}); });
} }
@ -81,7 +80,7 @@ export class ParentClient extends ClasschartsClient {
for (let i = 0; i < pupils.length; i++) { for (let i = 0; i < pupils.length; i++) {
const pupil = pupils[i]; const pupil = pupils[i];
if (pupil.id == pupilId) { if (pupil.id == pupilId) {
this.studentId = pupil.id; super.studentId = pupil.id;
return; return;
} }
} }

View file

@ -1,7 +1,7 @@
import type { AxiosRequestConfig } from "axios"; import { API_BASE_STUDENT, BASE_URL } from "./consts.js";
import { API_BASE_STUDENT, BASE_URL } from "./consts"; import { ClasschartsClient } from "./baseClient.js";
import { ClasschartsClient } from "./baseClient"; import { parseCookies } from "./utils.js";
import { parseCookies } from "./utils"; import ky from "ky-universal";
/** /**
* Student Client * Student Client
*/ */
@ -15,12 +15,8 @@ export class StudentClient extends ClasschartsClient {
* @param studentCode Classcharts student code * @param studentCode Classcharts student code
* @param dateOfBirth Student's date of birth * @param dateOfBirth Student's date of birth
*/ */
constructor( constructor(studentCode: string, dateOfBirth?: string) {
studentCode: string, super(API_BASE_STUDENT);
dateOfBirth?: string,
axiosConfig?: AxiosRequestConfig
) {
super(API_BASE_STUDENT, axiosConfig);
this.studentCode = String(studentCode); this.studentCode = String(studentCode);
this.dateOfBirth = String(dateOfBirth); this.dateOfBirth = String(dateOfBirth);
} }
@ -36,20 +32,22 @@ export class StudentClient extends ClasschartsClient {
formData.append("dob", this.dateOfBirth); formData.append("dob", this.dateOfBirth);
formData.append("remember_me", "1"); formData.append("remember_me", "1");
formData.append("recaptcha-token", "no-token-avaliable"); formData.append("recaptcha-token", "no-token-avaliable");
const request = await this.axios.request({ const request = await ky(BASE_URL + "/student/login", {
url: BASE_URL + "/student/login",
method: "POST", method: "POST",
data: formData.toString(), body: formData,
maxRedirects: 0, redirect: "manual",
headers: { throwHttpErrors: false,
"Content-Type": "application/x-www-form-urlencoded",
},
validateStatus: () => true,
}); });
if (request.status != 302 || !request.headers["set-cookie"]) if (request.status != 302 || !request.headers.get("set-cookie")) {
throw new Error("Unauthenticated: Classcharts returned an error"); throw new Error(
const cookies = String(request.headers["set-cookie"]); "Unauthenticated: Classcharts returned an error: " +
this.authCookies = cookies.split(";"); request.status +
" " +
request.statusText
);
}
const cookies = String(request.headers.get("set-cookie"));
this.authCookies = cookies.split(",");
const sessionCookies = parseCookies(cookies); const sessionCookies = parseCookies(cookies);
const sessionID = JSON.parse( const sessionID = JSON.parse(
String(sessionCookies["student_session_credentials"]) String(sessionCookies["student_session_credentials"])

View file

@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-explicit-any */
type ClassChartsResponse<T, E> = { export type ClassChartsResponse<T, E> = {
data: T; data: T;
meta: E; meta: E;
error?: string; error?: string;

View file

@ -3,9 +3,14 @@ export function parseCookies(input: string) {
const cookies = input.split(","); const cookies = input.split(",");
for (const cookie of cookies) { for (const cookie of cookies) {
const cookieSplit = cookie.split(";")[0].split("="); const cookieSplit = cookie.split(";")[0].split("=");
output[decodeURIComponent(cookieSplit[0])] = decodeURIComponent( output[leftTrim(decodeURIComponent(cookieSplit[0]))] = decodeURIComponent(
cookieSplit[1] cookieSplit[1]
); );
} }
return output; return output;
} }
function leftTrim(str: string) {
if (!str) return str;
return str.replace(/^\s+/g, "");
}

View file

@ -21,16 +21,16 @@
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
/* Modules */ /* Modules */
"module": "commonjs" /* Specify what module code is generated. */, "module": "ES2020" /* Specify what module code is generated. */,
// "rootDir": "./", /* Specify the root folder within your source files. */ // "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ "moduleResolution": "nodenext", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */ // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
"resolveJsonModule": true, /* Enable importing .json files */ // "resolveJsonModule": true, /* Enable importing .json files */
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */ // "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */ /* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */