1
0
Fork 0
mirror of https://github.com/classchartsapi/classcharts-api-js.git synced 2026-05-14 03:56:59 +00:00

feat: Use biomejs for formatting & linting (#42)

This commit is contained in:
James Cook 2023-11-29 00:03:56 +00:00 committed by GitHub
parent 602529171f
commit ac5569f53e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
17 changed files with 1095 additions and 1000 deletions

View file

@ -0,0 +1,33 @@
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/typescript-node
{
"name": "Node.js & TypeScript",
// Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
"image": "mcr.microsoft.com/devcontainers/typescript-node:1-20-bullseye",
"features": {
"ghcr.io/devcontainers-contrib/features/deno:1": {}
},
"customizations": {
"vscode": {
"extensions": [
"biomejs.biome",
"denoland.vscode-deno"
]
}
}
// Features to add to the dev container. More info: https://containers.dev/features.
// "features": {},
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],
// Use 'postCreateCommand' to run commands after the container is created.
// "postCreateCommand": "yarn install",
// Configure tool-specific properties.
// "customizations": {},
// Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
// "remoteUser": "root"
}

21
.github/workflows/lint.yml vendored Normal file
View file

@ -0,0 +1,21 @@
name: test
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
lint:
name: Lint
runs-on: ubuntu-latest
steps:
- name: Checkout Repo
uses: actions/checkout@v3
- uses: denoland/setup-deno@v1
with:
deno-version: 1.x
- name: Lint Package with Biome
run: deno task lint

View file

@ -1,5 +1,3 @@
{ {
"recommendations": [ "recommendations": ["denoland.vscode-deno", "biomejs.biome"]
"denoland.vscode-deno"
]
} }

View file

@ -1,4 +1,4 @@
{ {
"deno.enable": true, "deno.enable": true,
"deno.lint": true "deno.lint": false
} }

15
biome.json Normal file
View file

@ -0,0 +1,15 @@
{
"$schema": "https://biomejs.dev/schemas/1.4.0/schema.json",
"organizeImports": {
"enabled": true
},
"linter": {
"enabled": true,
"rules": {
"recommended": true
}
},
"files": {
"ignore": [".devcontainer/*", "npm/*", "deno.lock"]
}
}

View file

@ -1,6 +1,8 @@
{ {
"tasks": { "tasks": {
"npm": "deno run -A scripts/build_npm.ts" "npm": "deno run -A scripts/build_npm.ts",
"format": "deno run -A npm:@biomejs/biome format . --write",
"lint": "deno run -A npm:@biomejs/biome lint ."
}, },
"exclude": ["npm"] "exclude": ["npm"]
} }

44
deno.lock generated
View file

@ -1,5 +1,47 @@
{ {
"version": "2", "version": "3",
"packages": {
"specifiers": {
"npm:@biomejs/biome": "npm:@biomejs/biome@1.4.0"
},
"npm": {
"@biomejs/biome@1.4.0": {
"integrity": "sha512-/rDlao6ra38nhxo4IYCqWCzfTJcpMk4YHjSVBI9yN/ifdhnzSwirL25xDVH7G9hZdNhpF9g78FaPJhFa9DX0Cw==",
"dependencies": {
"@biomejs/cli-darwin-arm64": "@biomejs/cli-darwin-arm64@1.4.0",
"@biomejs/cli-darwin-x64": "@biomejs/cli-darwin-x64@1.4.0",
"@biomejs/cli-linux-arm64": "@biomejs/cli-linux-arm64@1.4.0",
"@biomejs/cli-linux-x64": "@biomejs/cli-linux-x64@1.4.0",
"@biomejs/cli-win32-arm64": "@biomejs/cli-win32-arm64@1.4.0",
"@biomejs/cli-win32-x64": "@biomejs/cli-win32-x64@1.4.0"
}
},
"@biomejs/cli-darwin-arm64@1.4.0": {
"integrity": "sha512-nBrtVRwr4IlTtxLOHwBwLv1sWvggf9/DnT5/ALIANJZOpoING6u8jHWipods69wK8kGa8Ld7iwHm3W5BrJJFFQ==",
"dependencies": {}
},
"@biomejs/cli-darwin-x64@1.4.0": {
"integrity": "sha512-nny0VgOj3ksUGzU5GblgtQEvrAZFgFe1IJBoYOP978OQdDrg7BpS+GX5udfof87Dl4ZlHPRBU951ceHOxF7BTg==",
"dependencies": {}
},
"@biomejs/cli-linux-arm64@1.4.0": {
"integrity": "sha512-gyLkT/Yh9xfW1T9yjQs/2txkCeG0e+LRs0adLugMwN0ptcNTRyusBvUoiHnpB+9rS6hWu9ZCedGMNmKQ8v2GSw==",
"dependencies": {}
},
"@biomejs/cli-linux-x64@1.4.0": {
"integrity": "sha512-LIxTuU2zSbIHM9XDYjQphJ5UU8h2eS7yR8uIvGYSba7Qt9AKqfbenyVJTsVnoj1CXxxgKNVSc/wVmlOlGz5DBQ==",
"dependencies": {}
},
"@biomejs/cli-win32-arm64@1.4.0": {
"integrity": "sha512-U2jT1/0wZLJIRqnU8qHAfi/A/+yUwlL3sYJgqs+wO0BbR22WGQZlj03u5FdpEoyLXdsLv1pbeIcjNp+V0NYXWA==",
"dependencies": {}
},
"@biomejs/cli-win32-x64@1.4.0": {
"integrity": "sha512-gN6DgyyBxIwoCovAUFJHFWVallb0cLosayDRtNyxU3MDv/atZxSXOWQezfVKBIbgmFPxYWJObd+awvbPYXwwww==",
"dependencies": {}
}
}
},
"remote": { "remote": {
"https://deno.land/std@0.140.0/_util/assert.ts": "e94f2eb37cebd7f199952e242c77654e43333c1ac4c5c700e929ea3aa5489f74", "https://deno.land/std@0.140.0/_util/assert.ts": "e94f2eb37cebd7f199952e242c77654e43333c1ac4c5c700e929ea3aa5489f74",
"https://deno.land/std@0.140.0/_util/os.ts": "3b4c6e27febd119d36a416d7a97bd3b0251b77c88942c8f16ee5953ea13e2e49", "https://deno.land/std@0.140.0/_util/os.ts": "3b4c6e27febd119d36a416d7a97bd3b0251b77c88942c8f16ee5953ea13e2e49",

View file

@ -1,5 +1,5 @@
export { export {
assertEquals, assertEquals,
assertExists, assertExists,
assertRejects, assertRejects,
} from "https://deno.land/std@0.201.0/assert/mod.ts"; } from "https://deno.land/std@0.201.0/assert/mod.ts";

View file

@ -6,49 +6,52 @@ if (!Deno.args[0]) throw new Error("No version specified");
await emptyDir("./npm"); await emptyDir("./npm");
await build({ await build({
entryPoints: [{ entryPoints: [
name: ".", {
path: "./mod.ts", name: ".",
}, { path: "./mod.ts",
name: "./types", },
path: "./src/types.ts", {
}], name: "./types",
outDir: "./npm", path: "./src/types.ts",
importMap: "./deno.jsonc", },
shims: { ],
deno: true, outDir: "./npm",
}, importMap: "./deno.jsonc",
packageManager: "pnpm", shims: {
compilerOptions: { deno: true,
lib: ["DOM", "ESNext"], },
}, packageManager: "pnpm",
typeCheck: "both", compilerOptions: {
package: { lib: ["DOM", "ESNext"],
name: "classcharts-api", },
version: String(Deno.args[0]).replace("v", ""), typeCheck: "both",
author: { package: {
name: "James Cook", name: "classcharts-api",
email: "james@jaminit.co.uk", version: String(Deno.args[0]).replace("v", ""),
}, author: {
description: name: "James Cook",
"A Typescript wrapper for getting information from the ClassCharts API", email: "james@jaminit.co.uk",
license: "ISC", },
keywords: ["node", "typescript", "classcharts", "class charts"], description:
bugs: { "A Typescript wrapper for getting information from the ClassCharts API",
url: "https://github.com/classchartsapi/classcharts-api-js/issues", license: "ISC",
}, keywords: ["node", "typescript", "classcharts", "class charts"],
repository: { bugs: {
type: "git", url: "https://github.com/classchartsapi/classcharts-api-js/issues",
url: "https://github.com/classchartsapi/classcharts-api-js.git", },
}, repository: {
homepage: "https://classchartsapi.github.io/classcharts-api-js/", type: "git",
engines: { url: "https://github.com/classchartsapi/classcharts-api-js.git",
node: ">=18", },
}, homepage: "https://classchartsapi.github.io/classcharts-api-js/",
sideEffects: false, engines: {
}, node: ">=18",
postBuild() { },
Deno.copyFileSync("LICENSE", "npm/LICENSE"); sideEffects: false,
Deno.copyFileSync("README.md", "npm/README.md"); },
}, postBuild() {
Deno.copyFileSync("LICENSE", "npm/LICENSE");
Deno.copyFileSync("README.md", "npm/README.md");
},
}); });

View file

@ -1,21 +1,21 @@
import type { import type {
ActivityResponse, ActivityResponse,
AnnouncementsResponse, AnnouncementsResponse,
AttendanceResponse, AttendanceResponse,
BadgesResponse, BadgesResponse,
BehaviourResponse, BehaviourResponse,
ClassChartsResponse, ClassChartsResponse,
DetentionsResponse, DetentionsResponse,
GetActivityOptions, GetActivityOptions,
GetAttendanceOptions, GetAttendanceOptions,
GetBehaviourOptions, GetBehaviourOptions,
GetFullActivityOptions, GetFullActivityOptions,
GetHomeworkOptions, GetHomeworkOptions,
GetLessonsOptions, GetLessonsOptions,
GetStudentInfoResponse, GetStudentInfoResponse,
HomeworksResponse, HomeworksResponse,
LessonsResponse, LessonsResponse,
PupilFieldsResponse, PupilFieldsResponse,
} from "../types.ts"; } from "../types.ts";
import { PING_INTERVAL } from "../utils/consts.ts"; import { PING_INTERVAL } from "../utils/consts.ts";
@ -23,290 +23,283 @@ import { PING_INTERVAL } from "../utils/consts.ts";
* Shared client for both parent and student. This is not exported and should not be used directly * Shared client for both parent and student. This is not exported and should not be used directly
*/ */
export class BaseClient { export class BaseClient {
/** /**
* @property studentId Currently selected student ID * @property studentId Currently selected student ID
*/ */
public studentId = 0; public studentId = 0;
/** /**
* @property authCookies Cookies used for authentication (set during login and can be empty) * @property authCookies Cookies used for authentication (set during login and can be empty)
*/ */
public authCookies: Array<string>; public authCookies: Array<string>;
/** /**
* @property sessionId Session ID used for authentication * @property sessionId Session ID used for authentication
*/ */
public sessionId = ""; public sessionId = "";
/** /**
* @property lastPing Last time the sessionId was updated * @property lastPing Last time the sessionId was updated
*/ */
public lastPing = 0; public lastPing = 0;
/** /**
* @property API_BASE Base API URL, this is different depending on if its called as a parent or student * @property API_BASE Base API URL, this is different depending on if its called as a parent or student
*/ */
protected API_BASE = ""; protected API_BASE = "";
/** /**
* @param API_BASE Base API URL, this is different depending on if its called as a parent or student * @param API_BASE Base API URL, this is different depending on if its called as a parent or student
*/ */
constructor(API_BASE: string) { constructor(API_BASE: string) {
this.authCookies = []; this.authCookies = [];
this.API_BASE = API_BASE; this.API_BASE = API_BASE;
} }
/** /**
* Revalidates the session ID. * Revalidates the session ID.
* *
* This is called automatically when the session ID is older than 3 minutes or when initially using the .login() method * This is called automatically when the session ID is older than 3 minutes or when initially using the .login() method
*/ */
public async getNewSessionId() { public async getNewSessionId() {
const pingFormData = new URLSearchParams(); const pingFormData = new URLSearchParams();
pingFormData.append("include_data", "true"); pingFormData.append("include_data", "true");
const pingData = await this.makeAuthedRequest( const pingData = await this.makeAuthedRequest(
this.API_BASE + "/ping", `${this.API_BASE}/ping`,
{ {
method: "POST", method: "POST",
body: pingFormData, body: pingFormData,
}, },
{ revalidateToken: false }, { revalidateToken: false },
); );
this.sessionId = pingData.meta.session_id; this.sessionId = pingData.meta.session_id;
this.lastPing = Date.now(); this.lastPing = Date.now();
} }
/** /**
* Makes a request to the ClassCharts API with the required authentication headers * Makes a request to the ClassCharts API with the required authentication headers
* *
* @param path Path to the API endpoint * @param path Path to the API endpoint
* @param fetchOptions Request Options * @param fetchOptions Request Options
* @param options * @param options
* @param options.revalidateToken Whether to revalidate the session ID if it is older than 3 minutes * @param options.revalidateToken Whether to revalidate the session ID if it is older than 3 minutes
* *
* @returns Response * @returns Response
*/ */
public async makeAuthedRequest( public async makeAuthedRequest(
path: string, path: string,
fetchOptions: RequestInit, fetchOptions: RequestInit,
options?: { revalidateToken?: boolean }, options: { revalidateToken?: boolean } = { revalidateToken: true },
) { ) {
if (!this.sessionId) throw new Error("No session ID"); if (!this.sessionId) throw new Error("No session ID");
if (!options) { if (typeof options?.revalidateToken === "undefined") {
options = {}; options.revalidateToken = true;
} }
if (typeof options?.revalidateToken == "undefined") { const requestOptions = {
options.revalidateToken = true; ...fetchOptions,
} headers: {
const requestOptions = { Cookie: this?.authCookies?.join(";") ?? [],
...fetchOptions, Authorization: `Basic ${this.sessionId}`,
headers: { "User-Agent":
Cookie: this?.authCookies?.join(";") ?? [], "classcharts-api https://github.com/classchartsapi/classcharts-api-js",
Authorization: "Basic " + this.sessionId, ...fetchOptions.headers,
"User-Agent": },
"classcharts-api https://github.com/classchartsapi/classcharts-api-js", } satisfies RequestInit;
...fetchOptions.headers, if (options?.revalidateToken === true && this.lastPing) {
}, if (Date.now() - this.lastPing + 5000 > PING_INTERVAL) {
} satisfies RequestInit; await this.getNewSessionId();
if (options?.revalidateToken === true && this.lastPing) { }
if (Date.now() - this.lastPing + 5000 > PING_INTERVAL) { }
await this.getNewSessionId(); const request = await fetch(path, requestOptions);
} // biome-ignore lint/suspicious/noExplicitAny:
} let responseJSON: ClassChartsResponse<any, any>;
const request = await fetch(path, requestOptions); try {
// deno-lint-ignore no-explicit-any responseJSON = await request.json();
let responseJSON: ClassChartsResponse<any, any>; } catch {
try { throw new Error(
responseJSON = await request.json(); `Error parsing JSON. Returned response: ${await request.text()}`,
} catch { );
throw new Error( }
"Error parsing JSON. Returned response: " + (await request.text()), if (responseJSON.success === 0) {
); throw new Error(responseJSON.error);
} }
if (responseJSON.success == 0) { return responseJSON;
throw new Error(responseJSON.error); }
} /**
return responseJSON; * Gets general information about the current student
} * @returns Student object
/** */
* Gets general information about the current student async getStudentInfo(): Promise<GetStudentInfoResponse> {
* @returns Student object const body = new URLSearchParams();
*/ body.append("include_data", "true");
async getStudentInfo(): Promise<GetStudentInfoResponse> { return await this.makeAuthedRequest(`${this.API_BASE}/ping`, {
const body = new URLSearchParams(); method: "POST",
body.append("include_data", "true"); body: body,
return await this.makeAuthedRequest(this.API_BASE + "/ping", { });
method: "POST", }
body: body, /**
}); * Gets the current student's activity
} *
/** * This function is only used for pagination, you likely want client.getFullActivity
* Gets the current student's activity * @param options GetActivityOptions
* * @returns Activity data
* This function is only used for pagination, you likely want client.getFullActivity * @see getFullActivity
* @param options GetActivityOptions */
* @returns Activity data async getActivity(options?: GetActivityOptions): Promise<ActivityResponse> {
* @see getFullActivity const params = new URLSearchParams();
*/ options?.from && params.append("from", options?.from);
async getActivity(options?: GetActivityOptions): Promise<ActivityResponse> { options?.to && params.append("to", options?.to);
const params = new URLSearchParams(); options?.last_id && params.append("last_id", options?.last_id);
options?.from && params.append("from", options?.from); return await this.makeAuthedRequest(
options?.to && params.append("to", options?.to); `${this.API_BASE}/activity/${this.studentId}?${params.toString()}`,
options?.last_id && params.append("last_id", options?.last_id); {
return await this.makeAuthedRequest( method: "GET",
this.API_BASE + "/activity/" + this.studentId + "?" + params.toString(), },
{ );
method: "GET", }
}, /**
); * Gets the current student's activity between two dates
} *
/** * This function will automatically paginate through all the data returned by getActivity
* Gets the current student's activity between two dates * @param options GetFullActivityOptions
* * @returns Activity Data
* This function will automatically paginate through all the data returned by getActivity * @see getActivity
* @param options GetFullActivityOptions */
* @returns Activity Data async getFullActivity(
* @see getActivity options: GetFullActivityOptions,
*/ ): Promise<ActivityResponse["data"]> {
async getFullActivity( let data: ActivityResponse["data"] = [];
options: GetFullActivityOptions, let prevLast: number | undefined;
): Promise<ActivityResponse["data"]> { let gotData = true;
let data: ActivityResponse["data"] = []; while (gotData) {
let prevLast: number | undefined; const params: GetActivityOptions = {
let gotData = true; from: options.from,
while (gotData) { to: options.to,
const params: GetActivityOptions = { };
from: options.from, if (prevLast) {
to: options.to, params.last_id = String(prevLast);
}; }
if (prevLast) { const fragment = (await this.getActivity(params)).data;
params.last_id = String(prevLast); if (!fragment || !fragment.length) {
} gotData = false;
const fragment = (await this.getActivity(params)).data; } else {
if (!fragment || !fragment.length) { data = data.concat(fragment);
gotData = false; prevLast = fragment[fragment.length - 1].id;
} else { }
data = data.concat(fragment); }
prevLast = fragment[fragment.length - 1].id; return data;
} }
} /**
return data; * Gets the current student's behaviour
} * @param options GetBehaviourOptions
/** * @returns Array of behaviour points
* Gets the current student's behaviour */
* @param options GetBehaviourOptions async getBehaviour(
* @returns Array of behaviour points options?: GetBehaviourOptions,
*/ ): Promise<BehaviourResponse> {
async getBehaviour( const params = new URLSearchParams();
options?: GetBehaviourOptions, options?.from && params.append("from", options?.from);
): Promise<BehaviourResponse> { options?.to && params.append("to", options?.to);
const params = new URLSearchParams(); return await this.makeAuthedRequest(
options?.from && params.append("from", options?.from); `${this.API_BASE}/behaviour/${this.studentId}?${params.toString()}`,
options?.to && params.append("to", options?.to); {
return await this.makeAuthedRequest( method: "GET",
this.API_BASE + "/behaviour/" + this.studentId + "?" + params.toString(), },
{ );
method: "GET", }
}, /**
); * Gets the current student's homework
} * @param options GetHomeworkOptions
/** * @returns Array of homeworks
* Gets the current student's homework */
* @param options GetHomeworkOptions async getHomeworks(options?: GetHomeworkOptions): Promise<HomeworksResponse> {
* @returns Array of homeworks const params = new URLSearchParams();
*/ if (options?.displayDate) {
async getHomeworks(options?: GetHomeworkOptions): Promise<HomeworksResponse> { params.append("display_date", String(options?.displayDate));
const params = new URLSearchParams(); }
if (options?.displayDate) {
params.append("display_date", String(options?.displayDate));
}
options?.from && params.append("from", String(options?.from)); options?.from && params.append("from", String(options?.from));
options?.to && params.append("to", String(options?.to)); options?.to && params.append("to", String(options?.to));
return await this.makeAuthedRequest( return await this.makeAuthedRequest(
this.API_BASE + "/homeworks/" + this.studentId + "?" + params.toString(), `${this.API_BASE}/homeworks/${this.studentId}?${params.toString()}`,
{ {
method: "GET", method: "GET",
}, },
); );
} }
/** /**
* Gets the current student's lessons for a given date * Gets the current student's lessons for a given date
* @param options GetLessonsOptions * @param options GetLessonsOptions
* @returns Array of lessons * @returns Array of lessons
*/ */
async getLessons(options: GetLessonsOptions): Promise<LessonsResponse> { async getLessons(options: GetLessonsOptions): Promise<LessonsResponse> {
if (!options?.date) throw new Error("No date specified"); if (!options?.date) throw new Error("No date specified");
const params = new URLSearchParams(); const params = new URLSearchParams();
params.append("date", String(options?.date)); params.append("date", String(options?.date));
return await this.makeAuthedRequest( return await this.makeAuthedRequest(
this.API_BASE + "/timetable/" + this.studentId + "?" + params.toString(), `${this.API_BASE}/timetable/${this.studentId}?${params.toString()}`,
{ {
method: "GET", method: "GET",
}, },
); );
} }
/** /**
* Gets the current student's earned badges * Gets the current student's earned badges
* @returns Array of badges * @returns Array of badges
*/ */
async getBadges(): Promise<BadgesResponse> { async getBadges(): Promise<BadgesResponse> {
return await this.makeAuthedRequest( return await this.makeAuthedRequest(
this.API_BASE + "/eventbadges/" + this.studentId, `${this.API_BASE}/eventbadges/${this.studentId}`,
{ {
method: "GET", method: "GET",
}, },
); );
} }
/** /**
* Gets the current student's announcements * Gets the current student's announcements
* @returns Array of announcements * @returns Array of announcements
*/ */
async getAnnouncements(): Promise<AnnouncementsResponse> { async getAnnouncements(): Promise<AnnouncementsResponse> {
return await this.makeAuthedRequest( return await this.makeAuthedRequest(
this.API_BASE + "/announcements/" + this.studentId, `${this.API_BASE}/announcements/${this.studentId}`,
{ {
method: "GET", method: "GET",
}, },
); );
} }
/** /**
* Gets the current student's detentions * Gets the current student's detentions
* @returns Array of detentions * @returns Array of detentions
*/ */
async getDetentions(): Promise<DetentionsResponse> { async getDetentions(): Promise<DetentionsResponse> {
return await this.makeAuthedRequest( return await this.makeAuthedRequest(
this.API_BASE + "/detentions/" + this.studentId, `${this.API_BASE}/detentions/${this.studentId}`,
{ {
method: "GET", method: "GET",
}, },
); );
} }
/** /**
* Gets the current student's attendance * Gets the current student's attendance
* @param options GetAttendanceOptions * @param options GetAttendanceOptions
* @returns Array of dates of attendance * @returns Array of dates of attendance
*/ */
async getAttendance( async getAttendance(
options?: GetAttendanceOptions, options?: GetAttendanceOptions,
): Promise<AttendanceResponse> { ): Promise<AttendanceResponse> {
const params = new URLSearchParams(); const params = new URLSearchParams();
options?.from && params.append("from", options?.from); options?.from && params.append("from", options?.from);
options?.to && params.append("to", options?.to); options?.to && params.append("to", options?.to);
return await this.makeAuthedRequest( return await this.makeAuthedRequest(
this.API_BASE + `${this.API_BASE}/attendance/${this.studentId}?${params.toString()}`,
"/attendance/" + {
this.studentId + method: "GET",
"?" + },
params.toString(), );
{ }
method: "GET", /**
}, * Gets the current student's pupil fields
); * @returns Array of stats
} */
/** async getPupilFields(): Promise<PupilFieldsResponse> {
* Gets the current student's pupil fields return await this.makeAuthedRequest(
* @returns Array of stats `${this.API_BASE}/customfields/${this.studentId}`,
*/ {
async getPupilFields(): Promise<PupilFieldsResponse> { method: "GET",
return await this.makeAuthedRequest( },
this.API_BASE + "/customfields/" + this.studentId, );
{ }
method: "GET",
},
);
}
} }

View file

@ -7,112 +7,107 @@ import { parseCookies } from "../utils/utils.ts";
* Parent Client * Parent Client
*/ */
export class ParentClient extends BaseClient { export class ParentClient extends BaseClient {
private password = ""; private password = "";
private email = ""; private email = "";
// @ts-expect-error Init in .login // @ts-expect-error Init in .login
public pupils: GetPupilsResponse; public pupils: GetPupilsResponse;
/** /**
* @param email Parent's email address * @param email Parent's email address
* @param password Parent's password * @param password Parent's password
*/ */
constructor(email: string, password: string) { constructor(email: string, password: string) {
super(API_BASE_PARENT); super(API_BASE_PARENT);
this.email = String(email); this.email = String(email);
this.password = String(password); this.password = String(password);
} }
/** /**
* Authenticates with ClassCharts * Authenticates with ClassCharts
*/ */
async login(): Promise<void> { async login(): Promise<void> {
if (!this.email) throw new Error("Email not provided"); if (!this.email) throw new Error("Email not provided");
if (!this.password) throw new Error("Password not provided"); if (!this.password) throw new Error("Password not provided");
const formData = new URLSearchParams(); const formData = new URLSearchParams();
formData.append("_method", "POST"); formData.append("_method", "POST");
formData.append("email", this.email); formData.append("email", this.email);
formData.append("logintype", "existing"); formData.append("logintype", "existing");
formData.append("password", this.password); formData.append("password", this.password);
formData.append("recaptcha-token", "no-token-available"); formData.append("recaptcha-token", "no-token-available");
const headers = new Headers({ const headers = new Headers({
"Content-Type": "application/x-www-form-urlencoded", "Content-Type": "application/x-www-form-urlencoded",
}); });
const response = await fetch(BASE_URL + "/parent/login", { const response = await fetch(`${BASE_URL}/parent/login`, {
method: "POST", method: "POST",
body: formData, body: formData,
headers: headers, headers: headers,
redirect: "manual", redirect: "manual",
}); });
if (response.status != 302 || !response.headers.has("set-cookie")) { if (response.status !== 302 || !response.headers.has("set-cookie")) {
await response.body?.cancel(); // Make deno tests happy by closing the body, unsure whether this is needed for the actual library await response.body?.cancel(); // Make deno tests happy by closing the body, unsure whether this is needed for the actual library
throw new Error( throw new Error(
"Unauthenticated: ClassCharts didn't return authentication cookies", "Unauthenticated: ClassCharts didn't return authentication cookies",
); );
} }
const cookies = String(response.headers.get("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; this.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; this.studentId = this.pupils[0].id;
} }
/** /**
* Get a list of pupils connected to this parent's account * Get a list of pupils connected to this parent's account
* @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> {
const response = await this.makeAuthedRequest(this.API_BASE + "/pupils", { const response = await this.makeAuthedRequest(`${this.API_BASE}/pupils`, {
method: "GET", method: "GET",
}); });
return response.data; return response.data;
} }
/** /**
* Selects a pupil to be used with API requests * Selects a pupil to be used with API requests
* @param pupilId Pupil ID obtained from this.pupils or getPupils() * @param pupilId Pupil ID obtained from this.pupils or getPupils()
* *
* @see getPupils * @see getPupils
*/ */
selectPupil(pupilId: number) { selectPupil(pupilId: number) {
if (!pupilId) throw new Error("No pupil ID specified"); if (!pupilId) throw new Error("No pupil ID specified");
const pupils = this.pupils; const pupils = this.pupils;
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; this.studentId = pupil.id;
return; return;
} }
} }
throw new Error("No pupil with specified ID returned"); throw new Error("No pupil with specified ID returned");
} }
/** /**
* Changes the login password for the current parent account * Changes the login password for the current parent account
* @param currentPassword Current password * @param currentPassword Current password
* @param newPassword New password * @param newPassword New password
* @returns Whether the request was successful * @returns Whether the request was successful
*/ */
async changePassword( async changePassword(
currentPassword: string, currentPassword: string,
newPassword: string, newPassword: string,
): Promise<ChangePasswordResponse> { ): Promise<ChangePasswordResponse> {
const formData = new URLSearchParams(); const formData = new URLSearchParams();
formData.append("current", currentPassword); formData.append("current", currentPassword);
formData.append("new", newPassword); formData.append("new", newPassword);
formData.append("repeat", newPassword); formData.append("repeat", newPassword);
return ( return await this.makeAuthedRequest(`${this.API_BASE}/password`, {
await this.makeAuthedRequest( method: "POST",
this.API_BASE + "/password", body: formData,
{ headers: {
method: "POST", "Content-Type": "application/x-www-form-urlencoded",
body: formData, },
headers: { });
"Content-Type": "application/x-www-form-urlencoded", }
},
},
)
);
}
} }

View file

@ -2,34 +2,34 @@ import { assertRejects } from "../../deps_dev.ts";
import { ParentClient } from "../core/parentClient.ts"; import { ParentClient } from "../core/parentClient.ts";
Deno.test("Throws when no email is provided", async () => { Deno.test("Throws when no email is provided", async () => {
const client = new ParentClient("", "password"); const client = new ParentClient("", "password");
await assertRejects( await assertRejects(
async () => { async () => {
await client.login(); await client.login();
}, },
Error, Error,
"Email not provided", "Email not provided",
); );
}); });
Deno.test("Throws when no password is provided", async () => { Deno.test("Throws when no password is provided", async () => {
const client = new ParentClient("email", ""); const client = new ParentClient("email", "");
await assertRejects( await assertRejects(
async () => { async () => {
await client.login(); await client.login();
}, },
Error, Error,
"Password not provided", "Password not provided",
); );
}); });
Deno.test("Throws with invalid username and password", async () => { Deno.test("Throws with invalid username and password", async () => {
const client = new ParentClient("invalid", "invalid"); const client = new ParentClient("invalid", "invalid");
await assertRejects( await assertRejects(
async () => { async () => {
await client.login(); await client.login();
}, },
Error, Error,
"Unauthenticated: ClassCharts didn't return authentication cookies", "Unauthenticated: ClassCharts didn't return authentication cookies",
); );
}); });

View file

@ -2,116 +2,109 @@ import { API_BASE_STUDENT, BASE_URL } from "../utils/consts.ts";
import { BaseClient } from "../core/baseClient.ts"; import { BaseClient } from "../core/baseClient.ts";
import { parseCookies } from "../utils/utils.ts"; import { parseCookies } from "../utils/utils.ts";
import { import {
GetStudentCodeOptions, GetStudentCodeOptions,
GetStudentCodeResponse, GetStudentCodeResponse,
RewardPurchaseResponse, RewardPurchaseResponse,
RewardsResponse, RewardsResponse,
} from "../types.ts"; } from "../types.ts";
/** /**
* Student Client * Student Client
*/ */
export class StudentClient extends BaseClient { export class StudentClient extends BaseClient {
/** /**
* @property studentCode ClassCharts student code * @property studentCode ClassCharts student code
*/ */
private studentCode = ""; private studentCode = "";
/** /**
* @property dateOfBirth Student's date of birth * @property dateOfBirth Student's date of birth
*/ */
private dateOfBirth = ""; private dateOfBirth = "";
/** /**
* @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(studentCode: string, dateOfBirth?: string) { constructor(studentCode: string, dateOfBirth?: string) {
super(API_BASE_STUDENT); super(API_BASE_STUDENT);
this.studentCode = String(studentCode); this.studentCode = String(studentCode);
this.dateOfBirth = String(dateOfBirth); this.dateOfBirth = String(dateOfBirth);
} }
/** /**
* Authenticates with ClassCharts * Authenticates with ClassCharts
*/ */
async login(): Promise<void> { async login(): Promise<void> {
if (!this.studentCode) throw new Error("Student Code not provided"); if (!this.studentCode) throw new Error("Student Code not provided");
const formData = new URLSearchParams(); const formData = new URLSearchParams();
formData.append("_method", "POST"); formData.append("_method", "POST");
formData.append("code", this.studentCode.toUpperCase()); formData.append("code", this.studentCode.toUpperCase());
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-available"); formData.append("recaptcha-token", "no-token-available");
const request = await fetch(BASE_URL + "/student/login", { const request = await fetch(`${BASE_URL}/student/login`, {
method: "POST", method: "POST",
body: formData, body: formData,
redirect: "manual", redirect: "manual",
}); });
if (request.status != 302 || !request.headers.has("set-cookie")) { if (request.status !== 302 || !request.headers.has("set-cookie")) {
await request.body?.cancel(); // Make deno tests happy by closing the body, unsure whether this is needed for the actual library await request.body?.cancel(); // Make deno tests happy by closing the body, unsure whether this is needed for the actual library
throw new Error( throw new Error(
"Unauthenticated: ClassCharts didn't return authentication cookies", "Unauthenticated: ClassCharts didn't return authentication cookies",
); );
} }
const cookies = String(request.headers.get("set-cookie")); const cookies = String(request.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["student_session_credentials"]), String(sessionCookies.student_session_credentials),
); );
this.sessionId = sessionID.session_id; this.sessionId = sessionID.session_id;
await this.getNewSessionId(); await this.getNewSessionId();
const user = await this.getStudentInfo(); const user = await this.getStudentInfo();
this.studentId = user.data.user.id; this.studentId = user.data.user.id;
} }
/** /**
* Gets the available items in the current student's rewards shop * Gets the available items in the current student's rewards shop
* @returns Array of purchasable items * @returns Array of purchasable items
*/ */
async getRewards(): Promise<RewardsResponse> { async getRewards(): Promise<RewardsResponse> {
return ( return await this.makeAuthedRequest(
await this.makeAuthedRequest( `${this.API_BASE}/rewards/${this.studentId}`,
this.API_BASE + "/rewards/" + this.studentId, {
{ method: "GET",
method: "GET", },
}, );
) }
);
}
/** /**
* Purchase a reward item from the current student's rewards shop * Purchase a reward item from the current student's rewards shop
* @param itemId number * @param itemId number
* @returns An object containing the current student's balance and item ID purchased * @returns An object containing the current student's balance and item ID purchased
*/ */
async purchaseReward(itemId: number): Promise<RewardPurchaseResponse> { async purchaseReward(itemId: number): Promise<RewardPurchaseResponse> {
return ( return await this.makeAuthedRequest(`${this.API_BASE}/purchase/${itemId}`, {
await this.makeAuthedRequest( method: "POST",
this.API_BASE + "/purchase/" + itemId, body: `pupil_id=${this.studentId}`,
{ });
method: "POST", }
body: `pupil_id=${this.studentId}`,
},
)
);
}
/** /**
* Gets the current student's student code * Gets the current student's student code
* @param options GetStudentCodeOptions * @param options GetStudentCodeOptions
* @param options.dateOfBirth Date of birth in the format YYYY-MM-DD * @param options.dateOfBirth Date of birth in the format YYYY-MM-DD
* @returns * @returns
*/ */
async getStudentCode( async getStudentCode(
options: GetStudentCodeOptions, options: GetStudentCodeOptions,
): Promise<GetStudentCodeResponse> { ): Promise<GetStudentCodeResponse> {
const data = await this.makeAuthedRequest(this.API_BASE + "/getcode", { const data = await this.makeAuthedRequest(`${this.API_BASE}/getcode`, {
method: "POST", method: "POST",
body: JSON.stringify({ body: JSON.stringify({
date: options.dateOfBirth, date: options.dateOfBirth,
}), }),
}); });
return data; return data;
} }
} }

View file

@ -2,23 +2,23 @@ import { assertRejects } from "../../deps_dev.ts";
import { StudentClient } from "../core/studentClient.ts"; import { StudentClient } from "../core/studentClient.ts";
Deno.test("Throws when no student code is provided", async () => { Deno.test("Throws when no student code is provided", async () => {
const client = new StudentClient(""); const client = new StudentClient("");
await assertRejects( await assertRejects(
async () => { async () => {
await client.login(); await client.login();
}, },
Error, Error,
"Student Code not provided", "Student Code not provided",
); );
}); });
Deno.test("Throws with invalid student code", async () => { Deno.test("Throws with invalid student code", async () => {
const client = new StudentClient("invalid"); const client = new StudentClient("invalid");
await assertRejects( await assertRejects(
async () => { async () => {
await client.login(); await client.login();
}, },
Error, Error,
"Unauthenticated: ClassCharts didn't return authentication cookies", "Unauthenticated: ClassCharts didn't return authentication cookies",
); );
}); });

View file

@ -2,490 +2,490 @@
* Helper type to define response from ClassCharts * Helper type to define response from ClassCharts
*/ */
export type ClassChartsResponse<Data, Meta> = { export type ClassChartsResponse<Data, Meta> = {
data: Data; data: Data;
meta: Meta; meta: Meta;
error?: string; error?: string;
success: number; success: number;
}; };
export interface Student { export interface Student {
id: number; id: number;
name: string; name: string;
first_name: string; first_name: string;
last_name: string; last_name: string;
avatar_url: string; avatar_url: string;
display_behaviour: boolean; display_behaviour: boolean;
display_parent_behaviour: boolean; display_parent_behaviour: boolean;
display_homework: boolean; display_homework: boolean;
display_rewards: boolean; display_rewards: boolean;
display_detentions: boolean; display_detentions: boolean;
display_report_cards: boolean; display_report_cards: boolean;
display_classes: boolean; display_classes: boolean;
display_announcements: boolean; display_announcements: boolean;
display_attendance: boolean; display_attendance: boolean;
display_attendance_type: string; display_attendance_type: string;
display_attendance_percentage: boolean; display_attendance_percentage: boolean;
display_activity: boolean; display_activity: boolean;
display_mental_health: boolean; display_mental_health: boolean;
display_timetable: boolean; display_timetable: boolean;
is_disabled: boolean; is_disabled: boolean;
display_two_way_communications: boolean; display_two_way_communications: boolean;
display_absences: boolean; display_absences: boolean;
can_upload_attachments: boolean | null; can_upload_attachments: boolean | null;
display_event_badges: boolean; display_event_badges: boolean;
display_avatars: boolean; display_avatars: boolean;
display_concern_submission: boolean; display_concern_submission: boolean;
display_custom_fields: boolean; display_custom_fields: boolean;
pupil_concerns_help_text: string; pupil_concerns_help_text: string;
allow_pupils_add_timetable_notes: boolean; allow_pupils_add_timetable_notes: boolean;
announcements_count: number; announcements_count: number;
messages_count: number; messages_count: number;
pusher_channel_name: string; pusher_channel_name: string;
has_birthday: boolean; has_birthday: boolean;
has_new_survey: boolean; has_new_survey: boolean;
survey_id: number | null; survey_id: number | null;
detention_alias_plural_uc: string; detention_alias_plural_uc: string;
} }
export interface GetStudentInfoData { export interface GetStudentInfoData {
user: Student; user: Student;
} }
export interface GetStudentInfoMeta { export interface GetStudentInfoMeta {
version: string; version: string;
} }
export type GetStudentInfoResponse = ClassChartsResponse< export type GetStudentInfoResponse = ClassChartsResponse<
GetStudentInfoData, GetStudentInfoData,
GetStudentInfoMeta GetStudentInfoMeta
>; >;
export interface GetBehaviourOptions { export interface GetBehaviourOptions {
/** /**
* From date, in format YYYY-MM-DD * From date, in format YYYY-MM-DD
*/ */
from?: string; from?: string;
/** /**
* To date, in format YYYY-MM-DD * To date, in format YYYY-MM-DD
*/ */
to?: string; to?: string;
} }
export interface BehaviourTimelinePoint { export interface BehaviourTimelinePoint {
positive: number; positive: number;
negative: number; negative: number;
name: string; name: string;
start: string; start: string;
end: string; end: string;
} }
export interface BehaviourResponseData { export interface BehaviourResponseData {
timeline: Array<BehaviourTimelinePoint>; timeline: Array<BehaviourTimelinePoint>;
positive_reasons: Record<string, number>; positive_reasons: Record<string, number>;
negative_reasons: Record<string, number>; negative_reasons: Record<string, number>;
other_positive: Array<string>; other_positive: Array<string>;
other_negative: Array<string>; other_negative: Array<string>;
other_positive_count: Array<Record<string, number>>; other_positive_count: Array<Record<string, number>>;
other_negative_count: Array<Record<string, number>>; other_negative_count: Array<Record<string, number>>;
} }
export interface BehaviourResponseMeta { export interface BehaviourResponseMeta {
start_date: string; start_date: string;
end_date: string; end_date: string;
step_size: string; step_size: string;
} }
export type BehaviourResponse = ClassChartsResponse< export type BehaviourResponse = ClassChartsResponse<
BehaviourResponseData, BehaviourResponseData,
BehaviourResponseMeta BehaviourResponseMeta
>; >;
export interface GetActivityOptions { export interface GetActivityOptions {
/** /**
* From date, in format YYYY-MM-DD * From date, in format YYYY-MM-DD
*/ */
from?: string; from?: string;
/** /**
* To date, in format YYYY-MM-DD * To date, in format YYYY-MM-DD
*/ */
to?: string; to?: string;
/** /**
* ID of the last activityPoint (used in pagination) * ID of the last activityPoint (used in pagination)
*/ */
last_id?: string; last_id?: string;
} }
export interface ActivityPoint { export interface ActivityPoint {
id: number; id: number;
type: string; type: string;
polarity: string; polarity: string;
reason: string; reason: string;
score: number; score: number;
timestamp: string; timestamp: string;
timestamp_custom_time: string | null; timestamp_custom_time: string | null;
style: { style: {
border_color: string | null; border_color: string | null;
custom_class: string | null; custom_class: string | null;
}; };
pupil_name: string; pupil_name: string;
lesson_name: string | null; lesson_name: string | null;
teacher_name: string; teacher_name: string;
room_name: string | null; room_name: string | null;
note: string | null; note: string | null;
_can_delete: boolean; _can_delete: boolean;
badges: string | undefined; badges: string | undefined;
detention_date: string | null; detention_date: string | null;
detention_time: string | null; detention_time: string | null;
detention_location: string | null; detention_location: string | null;
detention_type: string | null; detention_type: string | null;
} }
export type ActivityResponseData = Array<ActivityPoint>; export type ActivityResponseData = Array<ActivityPoint>;
interface ActivityResponseMeta { interface ActivityResponseMeta {
start_date: string; start_date: string;
end_date: string; end_date: string;
last_id: number | boolean; last_id: number | boolean;
step_size: string; step_size: string;
detention_alias_uc: string; detention_alias_uc: string;
} }
export type ActivityResponse = ClassChartsResponse< export type ActivityResponse = ClassChartsResponse<
ActivityResponseData, ActivityResponseData,
ActivityResponseMeta ActivityResponseMeta
>; >;
export type DisplayDate = "due_date" | "issue_date"; export type DisplayDate = "due_date" | "issue_date";
export interface GetHomeworkOptions { export interface GetHomeworkOptions {
/** /**
* Way to sort homeworks * Way to sort homeworks
* *
* Used to sort homeworks by when they are due or when they were issued * Used to sort homeworks by when they are due or when they were issued
* @default "issue_date" * @default "issue_date"
*/ */
displayDate?: DisplayDate; displayDate?: DisplayDate;
/** /**
* From date, in format YYYY-MM-DD * From date, in format YYYY-MM-DD
*/ */
from?: string; from?: string;
/** /**
* To date, in format YYYY-MM-DD * To date, in format YYYY-MM-DD
*/ */
to?: string; to?: string;
} }
export interface ValidatedHomeworkAttachment { export interface ValidatedHomeworkAttachment {
id: number; id: number;
file_name: string; file_name: string;
file: string; file: string;
validated_file: string; validated_file: string;
} }
export interface Homework { export interface Homework {
lesson: string; lesson: string;
subject: string; subject: string;
teacher: string; teacher: string;
homework_type: string; homework_type: string;
id: number; id: number;
title: string; title: string;
meta_title: string; meta_title: string;
description: string; description: string;
issue_date: string; issue_date: string;
due_date: string; due_date: string;
completion_time_unit: string; completion_time_unit: string;
completion_time_value: string; completion_time_value: string;
publish_time: string; publish_time: string;
status: { status: {
id: number; id: number;
state: "not_completed" | "late" | "completed" | null; state: "not_completed" | "late" | "completed" | null;
mark: unknown | null; mark: unknown | null;
mark_relative: number; mark_relative: number;
ticked: "yes" | "no"; ticked: "yes" | "no";
allow_attachments: boolean; allow_attachments: boolean;
first_seen_date: string | null; first_seen_date: string | null;
last_seen_date: string | null; last_seen_date: string | null;
attachments: Array<unknown>; attachments: Array<unknown>;
has_feedback: boolean; has_feedback: boolean;
}; };
validated_links: Array<unknown>; validated_links: Array<unknown>;
validated_attachments: Array<ValidatedHomeworkAttachment>; validated_attachments: Array<ValidatedHomeworkAttachment>;
} }
export type HomeworksResponseData = Array<Homework>; export type HomeworksResponseData = Array<Homework>;
export interface HomeworksResponseMeta { export interface HomeworksResponseMeta {
start_date: string; start_date: string;
end_date: string; end_date: string;
display_type: DisplayDate; display_type: DisplayDate;
max_files_allowed: number; max_files_allowed: number;
allowed_file_types: string[]; allowed_file_types: string[];
this_week_due_count: number; this_week_due_count: number;
this_week_outstanding_count: number; this_week_outstanding_count: number;
this_week_completed_count: number; this_week_completed_count: number;
allow_attachments: boolean; allow_attachments: boolean;
display_marks: boolean; display_marks: boolean;
} }
export type HomeworksResponse = ClassChartsResponse< export type HomeworksResponse = ClassChartsResponse<
HomeworksResponseData, HomeworksResponseData,
HomeworksResponseMeta HomeworksResponseMeta
>; >;
export interface GetLessonsOptions { export interface GetLessonsOptions {
/** /**
* Date to get lessons for, in format YYYY-MM-DD * Date to get lessons for, in format YYYY-MM-DD
*/ */
date: string; date: string;
} }
export interface Lesson { export interface Lesson {
teacher_name: string; teacher_name: string;
lesson_name: string; lesson_name: string;
subject_name: string; subject_name: string;
is_alternative_lesson: boolean; is_alternative_lesson: boolean;
period_name: string; period_name: string;
period_number: string; period_number: string;
room_name: string; room_name: string;
date: string; date: string;
start_time: string; start_time: string;
end_time: string; end_time: string;
key: number; key: number;
note_abstract: string; note_abstract: string;
note: string; note: string;
pupil_note_abstract: string; pupil_note_abstract: string;
pupil_note: string; pupil_note: string;
pupil_note_raw: string; pupil_note_raw: string;
} }
export type LessonsResponseData = Lesson[]; export type LessonsResponseData = Lesson[];
interface PeriodMeta { interface PeriodMeta {
number: string; number: string;
start_time: string; start_time: string;
end_time: string; end_time: string;
} }
export interface LessonsResponseMeta { export interface LessonsResponseMeta {
dates: string[]; dates: string[];
timetable_dates: string[]; timetable_dates: string[];
periods: PeriodMeta[]; periods: PeriodMeta[];
start_time: string; start_time: string;
end_time: string; end_time: string;
} }
export type LessonsResponse = ClassChartsResponse< export type LessonsResponse = ClassChartsResponse<
LessonsResponseData, LessonsResponseData,
LessonsResponseMeta LessonsResponseMeta
>; >;
// Not sure what to call this // Not sure what to call this
export interface LessonPupilBehaviour { export interface LessonPupilBehaviour {
reason: string; reason: string;
score: number; score: number;
icon: string; icon: string;
polarity: string; polarity: string;
timestamp: string; timestamp: string;
teacher: { teacher: {
title: string; title: string;
first_name: string; first_name: string;
last_name: string; last_name: string;
}; };
} }
export interface PupilEvent { export interface PupilEvent {
timestamp: string; timestamp: string;
lesson_pupil_behaviour: LessonPupilBehaviour; lesson_pupil_behaviour: LessonPupilBehaviour;
event: { event: {
label: string; label: string;
}; };
} }
export interface Badge { export interface Badge {
id: number; id: number;
name: string; name: string;
icon: string; icon: string;
colour: string; colour: string;
created_date: string; created_date: string;
pupil_badges: Array<PupilEvent>; pupil_badges: Array<PupilEvent>;
icon_url: string; icon_url: string;
} }
export type BadgesResponseData = Array<Badge>; export type BadgesResponseData = Array<Badge>;
export type BadgesResponseMeta = []; export type BadgesResponseMeta = [];
export type BadgesResponse = ClassChartsResponse< export type BadgesResponse = ClassChartsResponse<
BadgesResponseData, BadgesResponseData,
BadgesResponseMeta BadgesResponseMeta
>; >;
export interface Detention { export interface Detention {
id: number; id: number;
attended: "yes" | "no" | "upscaled" | "pending"; attended: "yes" | "no" | "upscaled" | "pending";
date: string | null; date: string | null;
length: number | null; length: number | null;
location: string | null; location: string | null;
notes: string | null; notes: string | null;
time: string | null; time: string | null;
pupil: { pupil: {
id: number; id: number;
first_name: string; first_name: string;
last_name: string; last_name: string;
school: { school: {
opt_notes_names: "yes" | "no"; opt_notes_names: "yes" | "no";
opt_notes_comments: "yes" | "no"; opt_notes_comments: "yes" | "no";
opt_notes_comments_pupils: "yes" | "no"; opt_notes_comments_pupils: "yes" | "no";
}; };
}; };
lesson: { lesson: {
id: number; id: number;
name: string; name: string;
subject: { subject: {
id: number; id: number;
name: string; name: string;
}; };
} | null; } | null;
lesson_pupil_behaviour: { lesson_pupil_behaviour: {
reason: string; reason: string;
}; };
teacher: { teacher: {
id: number; id: number;
first_name: string; first_name: string;
last_name: string; last_name: string;
title: string; title: string;
} | null; } | null;
detention_type: { detention_type: {
name: string; name: string;
}; };
} }
export type DetentionsData = Array<Detention>; export type DetentionsData = Array<Detention>;
export interface DetentionsMeta { export interface DetentionsMeta {
detention_alias_plural: string; detention_alias_plural: string;
} }
export type DetentionsResponse = ClassChartsResponse< export type DetentionsResponse = ClassChartsResponse<
DetentionsData, DetentionsData,
DetentionsMeta DetentionsMeta
>; >;
export interface Announcement { export interface Announcement {
id: number; id: number;
title: string; title: string;
description: string | null; description: string | null;
school_name: string; school_name: string;
teacher_name: string; teacher_name: string;
school_logo: string | null; school_logo: string | null;
sticky: "yes" | "no"; sticky: "yes" | "no";
state: string | null; state: string | null;
timestamp: string; timestamp: string;
attachments: Array<{ attachments: Array<{
filename: string; filename: string;
url: string; url: string;
}>; }>;
for_pupils: Array<unknown>; for_pupils: Array<unknown>;
comment_visibility: string; comment_visibility: string;
allow_comments: "yes" | "no"; allow_comments: "yes" | "no";
allow_reactions: "yes" | "no"; allow_reactions: "yes" | "no";
allow_consent: "yes" | "no"; allow_consent: "yes" | "no";
priority_pinned: "yes" | "no"; priority_pinned: "yes" | "no";
requires_consent: "yes" | "no"; requires_consent: "yes" | "no";
can_change_consent: boolean; can_change_consent: boolean;
consent: unknown | null; consent: unknown | null;
pupil_consents: Array<unknown>; pupil_consents: Array<unknown>;
} }
export type AnnouncementsResponse = ClassChartsResponse< export type AnnouncementsResponse = ClassChartsResponse<
Array<Announcement>, Array<Announcement>,
[] []
>; >;
export interface Pupil extends Student { export interface Pupil extends Student {
school_name: string; school_name: string;
school_logo: string; school_logo: string;
timezone: string; timezone: string;
display_covid_tests: boolean; display_covid_tests: boolean;
can_record_covid_tests: boolean; can_record_covid_tests: boolean;
detention_yes_count: number; detention_yes_count: number;
detention_no_count: number; detention_no_count: number;
detention_pending_count: number; detention_pending_count: number;
detention_upscaled_count: number; detention_upscaled_count: number;
homework_todo_count: number; homework_todo_count: number;
homework_late_count: number; homework_late_count: number;
homework_not_completed_count: number; homework_not_completed_count: number;
homework_excused_count: number; homework_excused_count: number;
homework_completed_count: number; homework_completed_count: number;
homework_submitted_count: number; homework_submitted_count: number;
announcements_count: number; announcements_count: number;
messages_count: number; messages_count: number;
} }
export type GetPupilsResponse = Array<Pupil>; export type GetPupilsResponse = Array<Pupil>;
export interface GetFullActivityOptions { export interface GetFullActivityOptions {
/** /**
* From date, in format YYYY-MM-DD * From date, in format YYYY-MM-DD
*/ */
from: string; from: string;
/** /**
* To date, in format YYYY-MM-DD * To date, in format YYYY-MM-DD
*/ */
to: string; to: string;
} }
export interface GetAttendanceOptions { export interface GetAttendanceOptions {
/** /**
* From date, in format YYYY-MM-DD * From date, in format YYYY-MM-DD
*/ */
from: string; from: string;
/** /**
* To date, in format YYYY-MM-DD * To date, in format YYYY-MM-DD
*/ */
to: string; to: string;
} }
export interface AttendancePeriod { export interface AttendancePeriod {
code: string; code: string;
status: "present" | "ignore"; status: "present" | "ignore";
late_minutes: number | string; late_minutes: number | string;
lesson_name?: string; lesson_name?: string;
room_name?: string; room_name?: string;
} }
export interface AttendanceMeta { export interface AttendanceMeta {
dates: Array<string>; dates: Array<string>;
sessions: Array<string>; sessions: Array<string>;
start_date: string; start_date: string;
end_date: string; end_date: string;
percentage: string; percentage: string;
percentage_singe_august: string; percentage_singe_august: string;
} }
export type AttendanceData = Record<string, Record<string, AttendancePeriod>>; export type AttendanceData = Record<string, Record<string, AttendancePeriod>>;
export type AttendanceResponse = ClassChartsResponse< export type AttendanceResponse = ClassChartsResponse<
AttendanceData, AttendanceData,
AttendanceMeta AttendanceMeta
>; >;
export type RewardsData = { export type RewardsData = {
id: number; id: number;
name: string; name: string;
description: string; description: string;
photo: string; photo: string;
price: number; price: number;
stock_control: boolean; stock_control: boolean;
stock: number; stock: number;
can_purchase: boolean; can_purchase: boolean;
unable_to_purchase_reason: string; unable_to_purchase_reason: string;
once_per_pupil: boolean; once_per_pupil: boolean;
purchased: boolean; purchased: boolean;
purchased_count: string | number; purchased_count: string | number;
price_balance_difference: number; price_balance_difference: number;
}[]; }[];
export interface RewardsMeta { export interface RewardsMeta {
pupil_score_balance: number; pupil_score_balance: number;
} }
export type RewardsResponse = ClassChartsResponse<RewardsData, RewardsMeta>; export type RewardsResponse = ClassChartsResponse<RewardsData, RewardsMeta>;
export interface RewardPurchaseData { export interface RewardPurchaseData {
single_purchase: "yes" | "no"; single_purchase: "yes" | "no";
order_id: number; order_id: number;
balance: number; balance: number;
} }
export type RewardPurchaseResponse = ClassChartsResponse< export type RewardPurchaseResponse = ClassChartsResponse<
RewardPurchaseData, RewardPurchaseData,
[] []
>; >;
export interface PupilFieldsData { export interface PupilFieldsData {
note: string; note: string;
fields: Array<{ fields: Array<{
id: number; id: number;
name: string; name: string;
graphic: string; graphic: string;
value: string; value: string;
}>; }>;
} }
export type PupilFieldsResponse = ClassChartsResponse<PupilFieldsData, []>; export type PupilFieldsResponse = ClassChartsResponse<PupilFieldsData, []>;
@ -493,18 +493,18 @@ export type PupilFieldsResponse = ClassChartsResponse<PupilFieldsData, []>;
export type ChangePasswordResponse = ClassChartsResponse<[], []>; export type ChangePasswordResponse = ClassChartsResponse<[], []>;
export interface GetStudentCodeOptions { export interface GetStudentCodeOptions {
/** /**
* Date of birth, in format YYYY-MM-DD * Date of birth, in format YYYY-MM-DD
*/ */
dateOfBirth: string; dateOfBirth: string;
} }
export interface GetStudentCodeResponseData { export interface GetStudentCodeResponseData {
code: string; code: string;
} }
export type GetStudentCodeResponseMeta = []; export type GetStudentCodeResponseMeta = [];
export type GetStudentCodeResponse = ClassChartsResponse< export type GetStudentCodeResponse = ClassChartsResponse<
GetStudentCodeResponseData, GetStudentCodeResponseData,
GetStudentCodeResponseMeta GetStudentCodeResponseMeta
>; >;

View file

@ -4,16 +4,16 @@
* @returns Object of cookies * @returns Object of cookies
*/ */
export function parseCookies(input: string) { export function parseCookies(input: string) {
const output: Record<string, unknown> = {}; const output: Record<string, unknown> = {};
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[leftTrim(decodeURIComponent(cookieSplit[0]))] = decodeURIComponent( output[leftTrim(decodeURIComponent(cookieSplit[0]))] = decodeURIComponent(
cookieSplit[1], cookieSplit[1],
); );
} }
return output; return output;
} }
export function leftTrim(str: string) { export function leftTrim(str: string) {
return str.replace(/^\s+/g, ""); return str.replace(/^\s+/g, "");
} }

View file

@ -1,37 +1,37 @@
import { assertEquals, assertExists } from "../../deps_dev.ts"; import { assertEquals, assertExists } from "../../deps_dev.ts";
import { parseCookies } from "./utils.ts"; import { parseCookies } from "./utils.ts";
Deno.test("Parses simple cookie", () => { Deno.test("Parses simple cookie", () => {
const cookie = const cookie =
"testCookie=Hello%20world!; expires=Tue, 28-Nov-2023 10:28:45 GMT; Max-Age=7776000; path=/"; "testCookie=Hello%20world!; expires=Tue, 28-Nov-2023 10:28:45 GMT; Max-Age=7776000; path=/";
const parsed = parseCookies(cookie); const parsed = parseCookies(cookie);
assertEquals(parsed.testCookie, "Hello world!"); assertEquals(parsed.testCookie, "Hello world!");
}); });
Deno.test("Parses multiple cookies", () => { Deno.test("Parses multiple cookies", () => {
const cookies = const cookies =
"firstCookie=I'm%20the%20first%20cookie; expires=Tue, 28-Nov-2023 10:28:45 GMT; Max-Age=7776000; path=/, secondCookie=I'm%20the%20second%20cookie; expires=Tue, 28-Nov-2023 10:28:45 GMT; Max-Age=7776000; path=/"; "firstCookie=I'm%20the%20first%20cookie; expires=Tue, 28-Nov-2023 10:28:45 GMT; Max-Age=7776000; path=/, secondCookie=I'm%20the%20second%20cookie; expires=Tue, 28-Nov-2023 10:28:45 GMT; Max-Age=7776000; path=/";
const parsed = parseCookies(cookies); const parsed = parseCookies(cookies);
assertEquals(parsed.firstCookie, "I'm the first cookie"); assertEquals(parsed.firstCookie, "I'm the first cookie");
assertEquals(parsed.secondCookie, "I'm the second cookie"); assertEquals(parsed.secondCookie, "I'm the second cookie");
}); });
Deno.test("Parses cookie with no value", () => { Deno.test("Parses cookie with no value", () => {
const cookie = const cookie =
"cookieWithNoValue=; expires=Tue, 28-Nov-2023 10:28:45 GMT; Max-Age=7776000; path=/"; "cookieWithNoValue=; expires=Tue, 28-Nov-2023 10:28:45 GMT; Max-Age=7776000; path=/";
const parsed = parseCookies(cookie); const parsed = parseCookies(cookie);
assertExists(parsed.cookieWithNoValue); assertExists(parsed.cookieWithNoValue);
assertEquals(parsed.cookieWithNoValue, ""); assertEquals(parsed.cookieWithNoValue, "");
}); });
import { leftTrim } from "./utils.ts"; import { leftTrim } from "./utils.ts";
Deno.test("Trims left with spaces", () => { Deno.test("Trims left with spaces", () => {
const input = " Hello world!"; const input = " Hello world!";
const output = leftTrim(input); const output = leftTrim(input);
assertEquals(output, "Hello world!"); assertEquals(output, "Hello world!");
}); });
Deno.test("Trims left with no spaces", () => { Deno.test("Trims left with no spaces", () => {
const input = "Hello world!"; const input = "Hello world!";
const output = leftTrim(input); const output = leftTrim(input);
assertEquals(output, "Hello world!"); assertEquals(output, "Hello world!");
}); });