style: fix linting issues met ESLint

This commit is contained in:
Lint Action 2025-03-11 03:09:08 +00:00
parent a30c4d0d32
commit aa1a85e64e
24 changed files with 76 additions and 90 deletions

View file

@ -23,9 +23,7 @@ export async function getLearningPaths(
? hruids.map(String)
: [String(hruids)];
} else if (themeKey) {
const theme = themes.find((t) => {
return t.title === themeKey;
});
const theme = themes.find((t) => t.title === themeKey);
if (theme) {
hruidList = theme.hruids;
} else {
@ -39,9 +37,7 @@ export async function getLearningPaths(
res.json(searchResults);
return;
} else {
hruidList = themes.flatMap((theme) => {
return theme.hruids;
});
hruidList = themes.flatMap((theme) => theme.hruids);
}
const learningPaths = await learningPathService.fetchLearningPaths(

View file

@ -12,9 +12,9 @@ const attachmentService = {
language: learningObjectId.language,
version: learningObjectId.version,
}, attachmentName);
} else {
}
return attachmentRepo.findByMostRecentVersionOfLearningObjectAndName(learningObjectId.hruid, learningObjectId.language, attachmentName);
}
}
}

View file

@ -68,23 +68,15 @@ async function fetchLearningObjects(
const nodes: LearningObjectNode[] = learningPathResponse.data[0].nodes;
if (!full) {
return nodes.map((node) => {
return node.learningobject_hruid;
});
return nodes.map((node) => node.learningobject_hruid);
}
return await Promise.all(
nodes.map(async (node) => {
return dwengoApiLearningObjectProvider.getLearningObjectById({
nodes.map(async (node) => dwengoApiLearningObjectProvider.getLearningObjectById({
hruid: node.learningobject_hruid,
language: learningPathId.language
});
})
).then((objects) => {
return objects.filter((obj): obj is FilteredLearningObject => {
return obj !== null;
});
});
}))
).then((objects) => objects.filter((obj): obj is FilteredLearningObject => obj !== null));
} catch (error) {
console.error('❌ Error fetching learning objects:', error);
return [];
@ -98,7 +90,7 @@ const dwengoApiLearningObjectProvider: LearningObjectProvider = {
async getLearningObjectById(
id: LearningObjectIdentifier
): Promise<FilteredLearningObject | null> {
let metadataUrl = `${DWENGO_API_BASE}/learningObject/getMetadata`;
const metadataUrl = `${DWENGO_API_BASE}/learningObject/getMetadata`;
const metadata = await fetchWithLogging<LearningObjectMetadata>(
metadataUrl,
`Metadata for Learning Object HRUID "${id.hruid}" (language ${id.language})`,

View file

@ -11,9 +11,9 @@ import databaseLearningObjectProvider from "./database-learning-object-provider"
function getProvider(id: LearningObjectIdentifier): LearningObjectProvider {
if (id.hruid.startsWith(getEnvVar(EnvVars.UserContentPrefix))) {
return databaseLearningObjectProvider;
} else {
}
return dwengoApiLearningObjectProvider;
}
}
/**

View file

@ -22,7 +22,7 @@ class ExternProcessor extends StringProcessor {
// If a seperate youtube-processor would be added, this code would need to move to that processor
// Converts youtube urls to youtube-embed urls
let match = /(.*youtube.com\/)watch\?v=(.*)/.exec(externURL)
const match = /(.*youtube.com\/)watch\?v=(.*)/.exec(externURL)
if (match) {
externURL = match[1] + "embed/" + match[2];
}

View file

@ -38,9 +38,9 @@ class GiftProcessor extends StringProcessor {
let html = "<div class='learning-object-gift'>\n";
let i = 1;
for (let question of quizQuestions) {
for (const question of quizQuestions) {
html += ` <div class='gift-question' id='gift-q${i}'>\n`;
html += " " + this.renderQuestion(question, i).replaceAll(/\n(.+)/g, "\n $1"); // replace for indentation.
html += " " + this.renderQuestion(question, i).replaceAll(/\n(.+)/g, "\n $1"); // Replace for indentation.
html += ` </div>\n`;
i++;
}

View file

@ -11,7 +11,7 @@ export class MultipleChoiceQuestionRenderer extends GIFTQuestionRenderer<Multipl
renderedHtml += `<p class='gift-stem' id='gift-q${questionNumber}-stem'>${question.stem.text}</p>\n`;
}
let i = 0;
for (let choice of question.choices) {
for (const choice of question.choices) {
renderedHtml += `<div class="gift-choice-div">\n`;
renderedHtml += ` <input type='radio' id='gift-q${questionNumber}-choice-${i}' name='gift-q${questionNumber}-choices' value="${i}"/>\n`;
renderedHtml += ` <label for='gift-q${questionNumber}-choice-${i}'>${choice.text}</label>\n`;

View file

@ -11,7 +11,7 @@ class BlockImageProcessor extends InlineImageProcessor {
}
override renderFn(imageUrl: string){
let inlineHtml = super.render(imageUrl);
const inlineHtml = super.render(imageUrl);
return DOMPurify.sanitize(`<div>${inlineHtml}</div>`);
}
}

View file

@ -56,53 +56,53 @@ function extractLearningObjectIdFromHref(href: string): LearningObjectIdentifier
},
// When the syntax for a link is used => [text](href "title")
// render a custom link when the prefix for a learning object is used.
// Render a custom link when the prefix for a learning object is used.
link(link: Link): string {
const href = link.href;
const title = link.title || "";
const text = marked.parseInline(link.text); // There could for example be an image in the link.
if (href.startsWith(prefixes.learningObject)) {
// link to learning-object
// Link to learning-object
const learningObjectId = extractLearningObjectIdFromHref(href);
return `<a href="${getUrlStringForLearningObjectHTML(learningObjectId)}" target="_blank" title="${title}">${text}</a>`;
} else {
// any other link
}
// Any other link
if (!isValidHttpUrl(href)) {
throw new ProcessingError("Link is not a valid HTTP URL!");
}
//<a href="https://kiks.ilabt.imec.be/hub/tmplogin?id=0101" title="Notebooks Werking"><img src="Knop.png" alt="" title="Knop"></a>
return `<a href="${href}" target="_blank" title="${title}">${text}</a>`;
}
},
// When the syntax for an image is used => ![text](href "title")
// render a learning object, pdf, audio or video if a prefix is used.
// Render a learning object, pdf, audio or video if a prefix is used.
image(img: Image): string {
const href = img.href;
if (href.startsWith(prefixes.learningObject)) {
// embedded learning-object
// Embedded learning-object
const learningObjectId = extractLearningObjectIdFromHref(href);
return `
<learning-object hruid="${learningObjectId.hruid}" language="${learningObjectId.language}" version="${learningObjectId.version}"/>
`; // Placeholder for the learning object since we cannot fetch its HTML here (this has to be a sync function!)
} else if (href.startsWith(prefixes.pdf)) {
// embedded pdf
let proc = new PdfProcessor();
// Embedded pdf
const proc = new PdfProcessor();
return proc.render(href.split(/\/(.+)/, 2)[1]);
} else if (href.startsWith(prefixes.audio)) {
// embedded audio
let proc = new AudioProcessor();
// Embedded audio
const proc = new AudioProcessor();
return proc.render(href.split(/\/(.+)/, 2)[1]);
} else if (href.startsWith(prefixes.extern) || href.startsWith(prefixes.video) || href.startsWith(prefixes.notebook)) {
// embedded youtube video or notebook (or other extern content)
let proc = new ExternProcessor();
// Embedded youtube video or notebook (or other extern content)
const proc = new ExternProcessor();
return proc.render(href.split(/\/(.+)/, 2)[1]);
} else {
// embedded image
let proc = new InlineImageProcessor();
}
// Embedded image
const proc = new InlineImageProcessor();
return proc.render(href)
}
},
}

View file

@ -27,7 +27,7 @@ class MarkdownProcessor extends StringProcessor {
}
replaceLinks(html: string) {
let proc = new InlineImageProcessor();
const proc = new InlineImageProcessor();
html = html.replace(/<img.*?src="(.*?)".*?(alt="(.*?)")?.*?(title="(.*?)")?.*?>/g, (
match: string,
src: string,
@ -35,9 +35,7 @@ class MarkdownProcessor extends StringProcessor {
altText: string,
title: string,
titleText: string
) => {
return proc.render(src);
});
) => proc.render(src));
return html;
}
}

View file

@ -54,7 +54,7 @@ class ProcessingService {
learningObject: LearningObject,
fetchEmbeddedLearningObjects?: (loId: LearningObjectIdentifier) => Promise<LearningObject | null>
): Promise<string> {
let html = this.processors.get(learningObject.contentType)!.renderLearningObject(learningObject);
const html = this.processors.get(learningObject.contentType)!.renderLearningObject(learningObject);
if (fetchEmbeddedLearningObjects) {
// Replace all embedded learning objects.
return replaceAsync(

View file

@ -22,7 +22,7 @@ import {LearningPathTransition} from "../../entities/content/learning-path-trans
*/
async function getLearningObjectsForNodes(nodes: LearningPathNode[]): Promise<Map<LearningPathNode, FilteredLearningObject>> {
// Fetching the corresponding learning object for each of the nodes and creating a map that maps each node to
// its corresponding learning object.
// Its corresponding learning object.
const nullableNodesToLearningObjects = new Map<LearningPathNode, FilteredLearningObject | null>(
await Promise.all(
nodes.map(node =>
@ -58,7 +58,7 @@ async function convertLearningPath(learningPath: LearningPathEntity, order: numb
const image = learningPath.image ? learningPath.image.toString("base64") : undefined;
return {
_id: `${learningPath.hruid}/${learningPath.language}`, // for backwards compatibility with the original Dwengo API.
_id: `${learningPath.hruid}/${learningPath.language}`, // For backwards compatibility with the original Dwengo API.
__order: order,
hruid: learningPath.hruid,
language: learningPath.language,

View file

@ -43,7 +43,7 @@ function transitionPossible(transition: LearningPathTransition, submitted: objec
*/
const learningPathPersonalizingService = {
async calculatePersonalizedTrajectory(nodes: LearningPathNode[], pathFor: {student?: Student, group?: Group}): Promise<LearningPathNode[]> {
let trajectory: LearningPathNode[] = [];
const trajectory: LearningPathNode[] = [];
// Always start with the start node.
let currentNode = nodes.filter(it => it.startNode)[0];
@ -51,17 +51,17 @@ const learningPathPersonalizingService = {
while (true) {
// At every node, calculate all the possible next transitions.
let lastSubmission = await getLastRelevantSubmission(currentNode, pathFor);
let submitted = lastSubmission === null ? null : JSON.parse(lastSubmission.content);
let possibleTransitions = currentNode.transitions
const lastSubmission = await getLastRelevantSubmission(currentNode, pathFor);
const submitted = lastSubmission === null ? null : JSON.parse(lastSubmission.content);
const possibleTransitions = currentNode.transitions
.filter(it => transitionPossible(it, submitted));
if (possibleTransitions.length === 0) { // If there are none, the trajectory has ended.
return trajectory;
} else { // Otherwise, take the first possible transition.
} // Otherwise, take the first possible transition.
currentNode = possibleTransitions[0].node;
trajectory.push(currentNode);
}
}
}
};

View file

@ -19,5 +19,5 @@ export async function replaceAsync(str: string, regex: RegExp, replacementFn: (m
const replacements: string[] = (await Promise.all(promises));
// Second run through matches: Replace them by their previously computed replacements.
return str.replace(regex, () => replacements.pop()!!);
return str.replace(regex, () => replacements.pop()!);
}

View file

@ -11,10 +11,10 @@ import {LearningObjectIdentifier} from "../../../src/entities/content/learning-o
const NEWER_TEST_SUFFIX = "nEweR";
function createTestLearningObjects(learningObjectRepo: LearningObjectRepository): {older: LearningObject, newer: LearningObject} {
let olderExample = example.createLearningObject();
const olderExample = example.createLearningObject();
learningObjectRepo.save(olderExample);
let newerExample = example.createLearningObject();
const newerExample = example.createLearningObject();
newerExample.title = "Newer example";
newerExample.version = 100;
@ -40,7 +40,7 @@ describe("AttachmentRepository", () => {
.values(example.createAttachment)
.map(fn => fn(exampleLearningObjects.older));
for (let attachment of attachmentsOlderLearningObject) {
for (const attachment of attachmentsOlderLearningObject) {
attachmentRepo.save(attachment);
}
});

View file

@ -12,8 +12,8 @@ import {FilteredLearningObject} from "../../../src/interfaces/learning-content";
import {Language} from "../../../src/entities/content/language";
async function initExampleData(): Promise<LearningObject> {
let learningObjectRepo = getLearningObjectRepository();
let exampleLearningObject = createExampleLearningObjectWithAttachments(example);
const learningObjectRepo = getLearningObjectRepository();
const exampleLearningObject = createExampleLearningObjectWithAttachments(example);
await learningObjectRepo.insert(exampleLearningObject);
return exampleLearningObject;
}

View file

@ -18,7 +18,7 @@ const DWENGO_TEST_LEARNING_OBJECT_ID: LearningObjectIdentifier = {
async function initExampleData(): Promise<LearningObject> {
const learningObjectRepo = getLearningObjectRepository();
let learningObject = learningObjectExample.createLearningObject();
const learningObject = learningObjectExample.createLearningObject();
learningObject.title = TEST_LEARNING_OBJECT_TITLE
await learningObjectRepo.save(learningObject);
return learningObject;

View file

@ -14,8 +14,8 @@ import {Language} from "../../../src/entities/content/language";
async function initExampleData(): Promise<{ learningObject: LearningObject, learningPath: LearningPath }> {
const learningObjectRepo = getLearningObjectRepository();
const learningPathRepo = getLearningPathRepository();
let learningObject = learningObjectExample.createLearningObject();
let learningPath = learningPathExample.createLearningPath();
const learningObject = learningObjectExample.createLearningObject();
const learningPath = learningPathExample.createLearningPath();
await learningObjectRepo.save(learningObject);
await learningPathRepo.save(learningPath);
return { learningObject, learningPath };
@ -55,7 +55,7 @@ describe("DatabaseLearningPathProvider", () => {
it("returns a non-successful response if a non-existing learning path is queried", async () => {
const result = await databaseLearningPathProvider.fetchLearningPaths(
[example.learningPath.hruid],
Language.Abkhazian, // wrong language
Language.Abkhazian, // Wrong language
"the source"
);

View file

@ -11,8 +11,8 @@ import learningPathService from "../../../src/services/learning-paths/learning-p
async function initExampleData(): Promise<{ learningObject: LearningObject, learningPath: LearningPath }> {
const learningObjectRepo = getLearningObjectRepository();
const learningPathRepo = getLearningPathRepository();
let learningObject = learningObjectExample.createLearningObject();
let learningPath = learningPathExample.createLearningPath();
const learningObject = learningObjectExample.createLearningObject();
const learningPath = learningPathExample.createLearningPath();
await learningObjectRepo.save(learningObject);
await learningPathRepo.save(learningPath);
return { learningObject, learningPath };
@ -76,7 +76,7 @@ describe("LearningPathService", () => {
).length
).toBe(1);
// but should not only find that one.
// But should not only find that one.
expect(result.length).not.toBeLessThan(2);
});
it("should still return results from the Dwengo API even though there are no matches in the database", async () => {
@ -88,7 +88,7 @@ describe("LearningPathService", () => {
// Should find something...
expect(result.length).not.toBe(0);
// but not the example learning path.
// But not the example learning path.
expect(
result.filter(it =>
it.hruid === example.learningPath.hruid && it.title === example.learningPath.title

View file

@ -2,8 +2,8 @@ import {LearningObjectExample} from "./learning-object-example";
import {LearningObject} from "../../../src/entities/content/learning-object.entity";
export function createExampleLearningObjectWithAttachments(example: LearningObjectExample): LearningObject {
let learningObject = example.createLearningObject();
for (let creationFn of Object.values(example.createAttachment)) {
const learningObject = example.createLearningObject();
for (const creationFn of Object.values(example.createAttachment)) {
learningObject.attachments.push(creationFn(learningObject));
}
return learningObject;

View file

@ -10,7 +10,7 @@ const ASSETS_PREFIX = "learning-objects/pn-werkingnotebooks/";
const example: LearningObjectExample = {
createLearningObject: ()=> {
let learningObject = new LearningObject();
const learningObject = new LearningObject();
learningObject.hruid = `${getEnvVar(EnvVars.UserContentPrefix)}pn_werkingnotebooks`;
learningObject.version = 3;
learningObject.language = Language.Dutch;
@ -18,11 +18,11 @@ const example: LearningObjectExample = {
learningObject.description = "Leren werken met notebooks";
learningObject.keywords = ["Python", "KIKS", "Wiskunde", "STEM", "AI"]
let educationalGoal1 = new EducationalGoal();
const educationalGoal1 = new EducationalGoal();
educationalGoal1.source = "Source";
educationalGoal1.id = "id";
let educationalGoal2 = new EducationalGoal();
const educationalGoal2 = new EducationalGoal();
educationalGoal2.source = "Source2";
educationalGoal2.id = "id2";
@ -39,7 +39,7 @@ const example: LearningObjectExample = {
learningObject.license = "dwengo";
learningObject.estimatedTime = 10;
let returnValue = new ReturnValue();
const returnValue = new ReturnValue();
returnValue.callbackUrl = "callback_url_example";
returnValue.callbackSchema = '{"att": "test", "att2": "test2"}';
@ -51,7 +51,7 @@ const example: LearningObjectExample = {
},
createAttachment: {
dwengoLogo: (learningObject) => {
let att = new Attachment();
const att = new Attachment();
att.learningObject = learningObject;
att.name = "dwengo.png";
att.mimeType = "image/png";
@ -59,7 +59,7 @@ const example: LearningObjectExample = {
return att;
},
knop: (learningObject) => {
let att = new Attachment();
const att = new Attachment();
att.learningObject = learningObject;
att.name = "Knop.png";
att.mimeType = "image/png";

View file

@ -4,7 +4,7 @@ import {LearningPathNode} from "../../../src/entities/content/learning-path-node
import {LearningPath} from "../../../src/entities/content/learning-path.entity";
export function createLearningPathTransition(node: LearningPathNode, transitionNumber: number, condition: string | null, to: LearningPathNode) {
let trans = new LearningPathTransition();
const trans = new LearningPathTransition();
trans.node = node;
trans.transitionNumber = transitionNumber;
trans.condition = condition || "true";
@ -20,7 +20,7 @@ export function createLearningPathNode(
language: Language,
startNode: boolean
) {
let node = new LearningPathNode();
const node = new LearningPathNode();
node.learningPath = learningPath;
node.nodeNumber = nodeNumber;
node.learningObjectHruid = learningObjectHruid;

View file

@ -5,7 +5,7 @@ import {createLearningPathNode, createLearningPathTransition} from "./learning-p
import {LearningPathNode} from "../../../src/entities/content/learning-path-node.entity";
function createNodes(learningPath: LearningPath): LearningPathNode[] {
let nodes = [
const nodes = [
createLearningPathNode(learningPath, 0, "u_pn_werkingnotebooks", 3, Language.Dutch, true),
createLearningPathNode(learningPath, 1, "pn_werkingnotebooks2", 3, Language.Dutch, false),
createLearningPathNode(learningPath, 2, "pn_werkingnotebooks3", 3, Language.Dutch, false),

View file

@ -22,7 +22,7 @@ export function expectToBeCorrectEntity<T extends object>(
if (!expected.name) {
expected.name = "expected";
}
for (let property in expected.entity) {
for (const property in expected.entity) {
if (
property !in IGNORE_PROPERTIES
&& expected.entity[property] !== undefined // If we don't expect a certain value for a property, we assume it can be filled in by the database however it wants.
@ -34,10 +34,10 @@ export function expectToBeCorrectEntity<T extends object>(
});
}
if (typeof expected.entity[property] === "boolean") { // Sometimes, booleans get represented by numbers 0 and 1 in the objects actual from the database.
if (!!expected.entity[property] !== !!actual.entity[property]) {
if (Boolean(expected.entity[property]) !== Boolean(actual.entity[property])) {
throw new AssertionError({
message: `${property} was ${expected.entity[property]} in ${expected.name},
but ${actual.entity[property]} (${!!expected.entity[property]}) in ${actual.name}`
but ${actual.entity[property]} (${Boolean(expected.entity[property])}) in ${actual.name}`
});
}
} else if (typeof expected.entity[property] !== typeof actual.entity[property]) {
@ -78,7 +78,7 @@ export function expectToBeCorrectFilteredLearningObject(filtered: FilteredLearni
expect(filtered.key).toEqual(original.hruid);
expect(filtered.targetAges).toEqual(original.targetAges);
expect(filtered.title).toEqual(original.title);
expect(!!filtered.teacherExclusive).toEqual(original.teacherExclusive) // !!: Workaround: MikroORM with SQLite returns 0 and 1 instead of booleans.
expect(Boolean(filtered.teacherExclusive)).toEqual(original.teacherExclusive) // !!: Workaround: MikroORM with SQLite returns 0 and 1 instead of booleans.
expect(filtered.skosConcepts).toEqual(original.skosConcepts);
expect(filtered.estimatedTime).toEqual(original.estimatedTime);
expect(filtered.educationalGoals).toEqual(original.educationalGoals);
@ -123,21 +123,21 @@ export function expectToBeCorrectLearningPath(
expect(learningPath.num_nodes).toEqual(expectedEntity.nodes.length);
expect(learningPath.image || null).toEqual(expectedEntity.image);
let expectedLearningPathNodes = new Map(
const expectedLearningPathNodes = new Map(
expectedEntity.nodes.map(node => [
{learningObjectHruid: node.learningObjectHruid, language: node.language, version: node.version},
{startNode: node.startNode, transitions: node.transitions}
])
);
for (let node of learningPath.nodes) {
for (const node of learningPath.nodes) {
const nodeKey = {
learningObjectHruid: node.learningobject_hruid,
language: node.language,
version: node.version
};
expect(expectedLearningPathNodes.keys()).toContainEqual(nodeKey);
let expectedNode = [...expectedLearningPathNodes.entries()]
const expectedNode = [...expectedLearningPathNodes.entries()]
.filter(([key, _]) =>
key.learningObjectHruid === nodeKey.learningObjectHruid
&& key.language === node.language