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

@ -6,13 +6,16 @@ if (!Deno.args[0]) throw new Error("No version specified");
await emptyDir("./npm"); await emptyDir("./npm");
await build({ await build({
entryPoints: [{ entryPoints: [
{
name: ".", name: ".",
path: "./mod.ts", path: "./mod.ts",
}, { },
{
name: "./types", name: "./types",
path: "./src/types.ts", path: "./src/types.ts",
}], },
],
outDir: "./npm", outDir: "./npm",
importMap: "./deno.jsonc", importMap: "./deno.jsonc",
shims: { shims: {

View file

@ -59,7 +59,7 @@ export class BaseClient {
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,
@ -82,20 +82,17 @@ export class BaseClient {
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 = {};
}
if (typeof options?.revalidateToken == "undefined") {
options.revalidateToken = true; options.revalidateToken = true;
} }
const requestOptions = { const requestOptions = {
...fetchOptions, ...fetchOptions,
headers: { headers: {
Cookie: this?.authCookies?.join(";") ?? [], Cookie: this?.authCookies?.join(";") ?? [],
Authorization: "Basic " + this.sessionId, Authorization: `Basic ${this.sessionId}`,
"User-Agent": "User-Agent":
"classcharts-api https://github.com/classchartsapi/classcharts-api-js", "classcharts-api https://github.com/classchartsapi/classcharts-api-js",
...fetchOptions.headers, ...fetchOptions.headers,
@ -107,16 +104,16 @@ export class BaseClient {
} }
} }
const request = await fetch(path, requestOptions); const request = await fetch(path, requestOptions);
// deno-lint-ignore no-explicit-any // biome-ignore lint/suspicious/noExplicitAny:
let responseJSON: ClassChartsResponse<any, any>; let responseJSON: ClassChartsResponse<any, any>;
try { try {
responseJSON = await request.json(); responseJSON = await request.json();
} catch { } catch {
throw new Error( throw new Error(
"Error parsing JSON. Returned response: " + (await request.text()), `Error parsing JSON. Returned response: ${await request.text()}`,
); );
} }
if (responseJSON.success == 0) { if (responseJSON.success === 0) {
throw new Error(responseJSON.error); throw new Error(responseJSON.error);
} }
return responseJSON; return responseJSON;
@ -128,7 +125,7 @@ export class BaseClient {
async getStudentInfo(): Promise<GetStudentInfoResponse> { async getStudentInfo(): Promise<GetStudentInfoResponse> {
const body = new URLSearchParams(); const body = new URLSearchParams();
body.append("include_data", "true"); body.append("include_data", "true");
return await this.makeAuthedRequest(this.API_BASE + "/ping", { return await this.makeAuthedRequest(`${this.API_BASE}/ping`, {
method: "POST", method: "POST",
body: body, body: body,
}); });
@ -147,7 +144,7 @@ export class BaseClient {
options?.to && params.append("to", options?.to); options?.to && params.append("to", options?.to);
options?.last_id && params.append("last_id", options?.last_id); options?.last_id && params.append("last_id", options?.last_id);
return await this.makeAuthedRequest( return await this.makeAuthedRequest(
this.API_BASE + "/activity/" + this.studentId + "?" + params.toString(), `${this.API_BASE}/activity/${this.studentId}?${params.toString()}`,
{ {
method: "GET", method: "GET",
}, },
@ -197,7 +194,7 @@ export class BaseClient {
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 + "/behaviour/" + this.studentId + "?" + params.toString(), `${this.API_BASE}/behaviour/${this.studentId}?${params.toString()}`,
{ {
method: "GET", method: "GET",
}, },
@ -217,7 +214,7 @@ export class BaseClient {
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",
}, },
@ -233,7 +230,7 @@ export class BaseClient {
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",
}, },
@ -245,7 +242,7 @@ export class BaseClient {
*/ */
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",
}, },
@ -257,7 +254,7 @@ export class BaseClient {
*/ */
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",
}, },
@ -269,7 +266,7 @@ export class BaseClient {
*/ */
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",
}, },
@ -287,11 +284,7 @@ export class BaseClient {
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 +
"?" +
params.toString(),
{ {
method: "GET", method: "GET",
}, },
@ -303,7 +296,7 @@ export class BaseClient {
*/ */
async getPupilFields(): Promise<PupilFieldsResponse> { async getPupilFields(): Promise<PupilFieldsResponse> {
return await this.makeAuthedRequest( return await this.makeAuthedRequest(
this.API_BASE + "/customfields/" + this.studentId, `${this.API_BASE}/customfields/${this.studentId}`,
{ {
method: "GET", method: "GET",
}, },

View file

@ -36,13 +36,13 @@ export class ParentClient extends BaseClient {
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",
@ -53,7 +53,7 @@ export class ParentClient extends BaseClient {
// 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();
@ -65,7 +65,7 @@ export class ParentClient extends BaseClient {
* @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;
@ -81,7 +81,7 @@ export class ParentClient extends BaseClient {
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;
} }
@ -102,17 +102,12 @@ export class ParentClient extends BaseClient {
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(
this.API_BASE + "/password",
{
method: "POST", method: "POST",
body: formData, body: formData,
headers: { headers: {
"Content-Type": "application/x-www-form-urlencoded", "Content-Type": "application/x-www-form-urlencoded",
}, },
}, });
)
);
} }
} }

View file

@ -42,12 +42,12 @@ export class StudentClient extends BaseClient {
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",
@ -57,7 +57,7 @@ export class StudentClient extends BaseClient {
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();
@ -70,13 +70,11 @@ export class StudentClient extends BaseClient {
* @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",
}, },
)
); );
} }
@ -86,15 +84,10 @@ export class StudentClient extends BaseClient {
* @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(
this.API_BASE + "/purchase/" + itemId,
{
method: "POST", method: "POST",
body: `pupil_id=${this.studentId}`, body: `pupil_id=${this.studentId}`,
}, });
)
);
} }
/** /**
@ -106,7 +99,7 @@ export class StudentClient extends BaseClient {
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,