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:
parent
8b16f8d8a9
commit
629c998293
9 changed files with 645 additions and 740 deletions
|
|
@ -1,11 +1,11 @@
|
|||
import axios from "axios";
|
||||
import type { AxiosRequestConfig, AxiosInstance } from "axios";
|
||||
import ky, { type Options as KyOptions } from "ky-universal";
|
||||
import type {
|
||||
ActivityResponse,
|
||||
AnnouncementsResponse,
|
||||
AttendanceResponse,
|
||||
BadgesResponse,
|
||||
BehaviourResponse,
|
||||
ClassChartsResponse,
|
||||
DetentionsResponse,
|
||||
GetActivityOptions,
|
||||
GetAttendanceOptions,
|
||||
|
|
@ -16,8 +16,8 @@ import type {
|
|||
GetStudentInfoResponse,
|
||||
HomeworksResponse,
|
||||
LessonsResponse,
|
||||
} from "./types";
|
||||
import { PING_INTERVAL } from "./consts";
|
||||
} from "./types.js";
|
||||
import { PING_INTERVAL } from "./consts.js";
|
||||
|
||||
/**
|
||||
* The base client
|
||||
|
|
@ -28,21 +28,13 @@ export class ClasschartsClient {
|
|||
public sessionId = "";
|
||||
public lastPing = 0;
|
||||
protected API_BASE = "";
|
||||
protected axios: AxiosInstance;
|
||||
/**
|
||||
*
|
||||
* @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.API_BASE = API_BASE;
|
||||
this.axios = axios.create({
|
||||
...axiosConfig,
|
||||
headers: {
|
||||
...axiosConfig?.headers,
|
||||
},
|
||||
validateStatus: () => true,
|
||||
});
|
||||
}
|
||||
public async getNewSessionId() {
|
||||
const pingFormData = new URLSearchParams();
|
||||
|
|
@ -51,10 +43,7 @@ export class ClasschartsClient {
|
|||
this.API_BASE + "/ping",
|
||||
{
|
||||
method: "POST",
|
||||
data: pingFormData.toString(),
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
body: pingFormData,
|
||||
},
|
||||
{ revalidateToken: false }
|
||||
);
|
||||
|
|
@ -63,7 +52,7 @@ export class ClasschartsClient {
|
|||
}
|
||||
public async makeAuthedRequest(
|
||||
path: string,
|
||||
axiosOptions: Omit<AxiosRequestConfig, "path">,
|
||||
kyOptions: KyOptions,
|
||||
options?: { revalidateToken?: boolean }
|
||||
) {
|
||||
if (!this.sessionId) throw new Error("No session ID");
|
||||
|
|
@ -73,26 +62,29 @@ export class ClasschartsClient {
|
|||
if (typeof options?.revalidateToken == "undefined") {
|
||||
options.revalidateToken = true;
|
||||
}
|
||||
const requestOptions: AxiosRequestConfig = {
|
||||
...axiosOptions,
|
||||
url: path,
|
||||
const requestOptions = {
|
||||
...kyOptions,
|
||||
headers: {
|
||||
Cookie: this?.authCookies?.join(";") ?? [],
|
||||
authorization: "Basic " + this.sessionId,
|
||||
...axiosOptions.headers,
|
||||
Authorization: "Basic " + this.sessionId,
|
||||
...kyOptions.headers,
|
||||
},
|
||||
};
|
||||
} satisfies KyOptions;
|
||||
if (options?.revalidateToken === true && this.lastPing) {
|
||||
if (Date.now() - this.lastPing + 5000 > PING_INTERVAL) {
|
||||
await this.getNewSessionId();
|
||||
}
|
||||
}
|
||||
const request = await this.axios.request(requestOptions);
|
||||
const responseJSON = request.data;
|
||||
const request = await ky(path, requestOptions);
|
||||
const responseJSON = (await request.json()) as ClassChartsResponse<
|
||||
unknown,
|
||||
unknown
|
||||
>;
|
||||
if (responseJSON.success == 0) {
|
||||
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
|
||||
*/
|
||||
async getStudentInfo(): Promise<GetStudentInfoResponse> {
|
||||
const body = new URLSearchParams();
|
||||
body.append("include_data", "true");
|
||||
const data = await this.makeAuthedRequest(this.API_BASE + "/ping", {
|
||||
method: "POST",
|
||||
data: "include_data=true",
|
||||
body: body,
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,2 +1,2 @@
|
|||
export * from "./parentClient";
|
||||
export * from "./studentClient";
|
||||
export * from "./parentClient.js";
|
||||
export * from "./studentClient.js";
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import type { AxiosRequestConfig } from "axios";
|
||||
import type { GetPupilsResponse } from "./types";
|
||||
import ky from "ky-universal";
|
||||
import type { GetPupilsResponse } from "./types.js";
|
||||
|
||||
import { ClasschartsClient } from "./baseClient";
|
||||
import { API_BASE_PARENT, BASE_URL } from "./consts";
|
||||
import { parseCookies } from "./utils";
|
||||
import { ClasschartsClient } from "./baseClient.js";
|
||||
import { API_BASE_PARENT, BASE_URL } from "./consts.js";
|
||||
import { parseCookies } from "./utils.js";
|
||||
/**
|
||||
* Parent Client
|
||||
*/
|
||||
|
|
@ -17,12 +17,8 @@ export class ParentClient extends ClasschartsClient {
|
|||
* @param email Parents email address
|
||||
* @param password Parents password
|
||||
*/
|
||||
constructor(
|
||||
email: string,
|
||||
password: string,
|
||||
axiosConfig?: AxiosRequestConfig
|
||||
) {
|
||||
super(API_BASE_PARENT, axiosConfig);
|
||||
constructor(email: string, password: string) {
|
||||
super(API_BASE_PARENT);
|
||||
this.email = String(email);
|
||||
this.password = String(password);
|
||||
}
|
||||
|
|
@ -38,36 +34,39 @@ export class ParentClient extends ClasschartsClient {
|
|||
formData.append("logintype", "existing");
|
||||
formData.append("password", this.password);
|
||||
formData.append("recaptcha-token", "no-token-avaliable");
|
||||
const request = await this.axios.request({
|
||||
url: BASE_URL + "/parent/login",
|
||||
method: "POST",
|
||||
data: formData.toString(),
|
||||
maxRedirects: 0,
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
validateStatus: () => true,
|
||||
const headers = new Headers({
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
});
|
||||
if (request.status != 302 || !request.headers["set-cookie"])
|
||||
throw new Error("Unauthenticated: Classcharts returned an error");
|
||||
const response = await ky(BASE_URL + "/parent/login", {
|
||||
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(";");
|
||||
const sessionCookies = parseCookies(cookies);
|
||||
const sessionID = JSON.parse(
|
||||
String(sessionCookies["parent_session_credentials"])
|
||||
);
|
||||
this.sessionId = sessionID.session_id;
|
||||
super.sessionId = sessionID.session_id;
|
||||
this.pupils = await this.getPupils();
|
||||
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
|
||||
* @returns an array of Pupils connected to this parent's account
|
||||
*/
|
||||
async getPupils(): Promise<GetPupilsResponse> {
|
||||
return this.makeAuthedRequest(this.API_BASE + "/pupils", {
|
||||
return super.makeAuthedRequest(super.API_BASE + "/pupils", {
|
||||
method: "GET",
|
||||
});
|
||||
}
|
||||
|
|
@ -81,7 +80,7 @@ export class ParentClient extends ClasschartsClient {
|
|||
for (let i = 0; i < pupils.length; i++) {
|
||||
const pupil = pupils[i];
|
||||
if (pupil.id == pupilId) {
|
||||
this.studentId = pupil.id;
|
||||
super.studentId = pupil.id;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import type { AxiosRequestConfig } from "axios";
|
||||
import { API_BASE_STUDENT, BASE_URL } from "./consts";
|
||||
import { ClasschartsClient } from "./baseClient";
|
||||
import { parseCookies } from "./utils";
|
||||
import { API_BASE_STUDENT, BASE_URL } from "./consts.js";
|
||||
import { ClasschartsClient } from "./baseClient.js";
|
||||
import { parseCookies } from "./utils.js";
|
||||
import ky from "ky-universal";
|
||||
/**
|
||||
* Student Client
|
||||
*/
|
||||
|
|
@ -15,12 +15,8 @@ export class StudentClient extends ClasschartsClient {
|
|||
* @param studentCode Classcharts student code
|
||||
* @param dateOfBirth Student's date of birth
|
||||
*/
|
||||
constructor(
|
||||
studentCode: string,
|
||||
dateOfBirth?: string,
|
||||
axiosConfig?: AxiosRequestConfig
|
||||
) {
|
||||
super(API_BASE_STUDENT, axiosConfig);
|
||||
constructor(studentCode: string, dateOfBirth?: string) {
|
||||
super(API_BASE_STUDENT);
|
||||
this.studentCode = String(studentCode);
|
||||
this.dateOfBirth = String(dateOfBirth);
|
||||
}
|
||||
|
|
@ -36,20 +32,22 @@ export class StudentClient extends ClasschartsClient {
|
|||
formData.append("dob", this.dateOfBirth);
|
||||
formData.append("remember_me", "1");
|
||||
formData.append("recaptcha-token", "no-token-avaliable");
|
||||
const request = await this.axios.request({
|
||||
url: BASE_URL + "/student/login",
|
||||
const request = await ky(BASE_URL + "/student/login", {
|
||||
method: "POST",
|
||||
data: formData.toString(),
|
||||
maxRedirects: 0,
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
validateStatus: () => true,
|
||||
body: formData,
|
||||
redirect: "manual",
|
||||
throwHttpErrors: false,
|
||||
});
|
||||
if (request.status != 302 || !request.headers["set-cookie"])
|
||||
throw new Error("Unauthenticated: Classcharts returned an error");
|
||||
const cookies = String(request.headers["set-cookie"]);
|
||||
this.authCookies = cookies.split(";");
|
||||
if (request.status != 302 || !request.headers.get("set-cookie")) {
|
||||
throw new Error(
|
||||
"Unauthenticated: Classcharts returned an error: " +
|
||||
request.status +
|
||||
" " +
|
||||
request.statusText
|
||||
);
|
||||
}
|
||||
const cookies = String(request.headers.get("set-cookie"));
|
||||
this.authCookies = cookies.split(",");
|
||||
const sessionCookies = parseCookies(cookies);
|
||||
const sessionID = JSON.parse(
|
||||
String(sessionCookies["student_session_credentials"])
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
type ClassChartsResponse<T, E> = {
|
||||
export type ClassChartsResponse<T, E> = {
|
||||
data: T;
|
||||
meta: E;
|
||||
error?: string;
|
||||
|
|
|
|||
|
|
@ -3,9 +3,14 @@ export function parseCookies(input: string) {
|
|||
const cookies = input.split(",");
|
||||
for (const cookie of cookies) {
|
||||
const cookieSplit = cookie.split(";")[0].split("=");
|
||||
output[decodeURIComponent(cookieSplit[0])] = decodeURIComponent(
|
||||
output[leftTrim(decodeURIComponent(cookieSplit[0]))] = decodeURIComponent(
|
||||
cookieSplit[1]
|
||||
);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
function leftTrim(str: string) {
|
||||
if (!str) return str;
|
||||
return str.replace(/^\s+/g, "");
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue