Refactoring: remove no longer used code and tests, fix some linting errors

This commit is contained in:
Pieter Vander Vennet 2024-04-10 13:18:29 +02:00
parent 6b381e05c6
commit 1bc45c1c0c
2 changed files with 15 additions and 111 deletions

View file

@ -896,26 +896,6 @@ In the case that MapComplete is pointed to the testing grounds, the edit will be
return dict.get(k)
}
/**
* Tries to minify the given JSON by applying some compression
*/
public static MinifyJSON(stringified: string): string {
stringified = stringified.replace(/\|/g, "||")
const keys = Utils.knownKeys.concat(Utils.extraKeys)
for (let i = 0; i < keys.length; i++) {
const knownKey = keys[i]
let code = i
if (i >= 124) {
code += 1 // Character 127 is our 'escape' character |
}
const replacement = "|" + String.fromCharCode(code)
stringified = stringified.replace(new RegExp(`\"${knownKey}\":`, "g"), replacement)
}
return stringified
}
public static UnMinify(minified: string): string {
if (minified === undefined || minified === null) {
return undefined
@ -942,7 +922,7 @@ In the case that MapComplete is pointed to the testing grounds, the edit will be
Utils.injectedDownloads[url] = data
}
public static async download(url: string, headers?: any): Promise<string | undefined> {
public static async download(url: string, headers?: Record<string, string>): Promise<string | undefined> {
const result = await Utils.downloadAdvanced(url, headers)
if (result["error"] !== undefined) {
throw result["error"]
@ -955,7 +935,7 @@ In the case that MapComplete is pointed to the testing grounds, the edit will be
*/
public static downloadAdvanced(
url: string,
headers?: any,
headers?: Record<string, string>,
method: "POST" | "GET" | "PUT" | "UPDATE" | "DELETE" | "OPTIONS" = "GET",
content?: string
): Promise<
@ -995,7 +975,7 @@ In the case that MapComplete is pointed to the testing grounds, the edit will be
})
}
public static upload(url: string, data, headers?: any): Promise<string> {
public static upload(url: string, data: string | Blob, headers?: Record<string, string>): Promise<string> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.onload = () => {
@ -1022,9 +1002,9 @@ In the case that MapComplete is pointed to the testing grounds, the edit will be
public static async downloadJsonCached(
url: string,
maxCacheTimeMs: number,
headers?: any
): Promise<any> {
const result = await Utils.downloadJsonAdvanced(url, headers)
headers?: Record<string, string>
): Promise<object> {
const result = await Utils.downloadJsonCachedAdvanced(url, maxCacheTimeMs, headers)
if (result["content"]) {
return result["content"]
}
@ -1034,8 +1014,8 @@ In the case that MapComplete is pointed to the testing grounds, the edit will be
public static async downloadJsonCachedAdvanced(
url: string,
maxCacheTimeMs: number,
headers?: any
): Promise<{ content: any } | { error: string; url: string; statuscode?: number }> {
headers?: Record<string, string>
): Promise<{ content: object | [] } | { error: string; url: string; statuscode?: number }> {
const cached = Utils._download_cache.get(url)
if (cached !== undefined) {
if (new Date().getTime() - cached.timestamp <= maxCacheTimeMs) {
@ -1051,7 +1031,7 @@ In the case that MapComplete is pointed to the testing grounds, the edit will be
return await promise
}
public static async downloadJson(url: string, headers?: any): Promise<any> {
public static async downloadJson(url: string, headers?: Record<string, string>): Promise<object | []> {
const result = await Utils.downloadJsonAdvanced(url, headers)
if (result["content"]) {
return result["content"]
@ -1069,12 +1049,12 @@ In the case that MapComplete is pointed to the testing grounds, the edit will be
public static async downloadJsonAdvanced(
url: string,
headers?: any
): Promise<{ content: any } | { error: string; url: string; statuscode?: number }> {
headers?: Record<string, string>
): Promise<{ content: object | object[] } | { error: string; url: string; statuscode?: number }> {
const injected = Utils.injectedDownloads[url]
if (injected !== undefined) {
console.log("Using injected resource for test for URL", url)
return new Promise((resolve, _) => resolve({ content: injected }))
return new Promise((resolve) => resolve({ content: injected }))
}
const result = await Utils.downloadAdvanced(
url,
@ -1086,6 +1066,9 @@ In the case that MapComplete is pointed to the testing grounds, the edit will be
const data = result["content"]
try {
if (typeof data === "string") {
if(data === ""){
return {content: {}}
}
return { content: JSON.parse(data) }
}
return { content: data }
@ -1134,26 +1117,6 @@ In the case that MapComplete is pointed to the testing grounds, the edit will be
element.click()
}
/**
* Reorders an object: creates a new object where the keys have been added alphabetically
*
* const sorted = Utils.sortKeys({ x: 'x', abc: {'x': 'x', 'a': 'a'}, def: 'def'})
* JSON.stringify(sorted) // => '{"abc":{"a":"a","x":"x"},"def":"def","x":"x"}'
*/
static sortKeys(o: any) {
const copy = {}
let keys = Object.keys(o)
keys = keys.sort()
for (const key of keys) {
let v = o[key]
if (typeof v === "object") {
v = Utils.sortKeys(v)
}
copy[key] = v
}
return copy
}
public static async waitFor(timeMillis: number): Promise<void> {
return new Promise((resolve) => {
window.setTimeout(resolve, timeMillis)

View file

@ -1,59 +0,0 @@
import { Utils } from "../src/Utils"
import LZString from "lz-string"
import { describe, expect, it } from "vitest"
const example = {
id: "bookcases",
maintainer: "MapComplete",
version: "2020-08-29",
language: ["en", "nl", "de", "fr"],
title: {
en: "Open Bookcase Map",
nl: "Open Boekenruilkastenkaart",
de: "Öffentliche Bücherschränke Karte",
fr: "Carte des microbibliothèques",
},
description: {
en: "A public bookcase is a small streetside cabinet, box, old phone boot or some other objects where books are stored. Everyone can place or take a book. This map aims to collect all these bookcases. You can discover new bookcases nearby and, with a free OpenStreetMap account, quickly add your favourite bookcases.",
nl: "Een boekenruilkast is een kastje waar iedereen een boek kan nemen of achterlaten. Op deze kaart kan je deze boekenruilkasten terugvinden en met een gratis OpenStreetMap-account, ook boekenruilkasten toevoegen of informatie verbeteren",
de: "Ein öffentlicher Bücherschrank ist ein kleiner Bücherschrank am Straßenrand, ein Kasten, eine alte Telefonzelle oder andere Gegenstände, in denen Bücher aufbewahrt werden. Jeder kann ein Buch hinstellen oder mitnehmen. Diese Karte zielt darauf ab, all diese Bücherschränke zu sammeln. Sie können neue Bücherschränke in der Nähe entdecken und mit einem kostenlosen OpenStreetMap-Account schnell Ihre Lieblingsbücherschränke hinzufügen.",
fr: "Une microbibliothèques, également appelée boite à livre, est un élément de mobilier urbain (étagère, armoire, etc) dans lequel sont stockés des livres et autres objets en accès libre. Découvrez les boites à livres prêt de chez vous, ou ajouter en une nouvelle à l'aide de votre compte OpenStreetMap.",
},
icon: "./assets/themes/bookcases/bookcase.svg",
socialImage: null,
startLat: 0,
startLon: 0,
startZoom: 1,
widenFactor: 0.05,
roamingRenderings: [],
layers: ["public_bookcase"],
}
describe("Utils", () => {
describe("Minify-json", () => {
it("should work in two directions", () => {
const str = JSON.stringify({ title: "abc", and: "xyz", render: "somevalue" })
const minified = Utils.MinifyJSON(str)
const restored = Utils.UnMinify(minified)
expect(str).toBe(restored)
})
it("should minify and restore the bookcase example", () => {
const str = JSON.stringify(example, null, 0)
const minified = Utils.MinifyJSON(str)
const restored = Utils.UnMinify(minified)
expect(str).toBe(restored)
})
it("should LZ-compress a theme", () => {
const str = JSON.stringify(example, null, 0)
const minified = LZString.compressToBase64(Utils.MinifyJSON(str))
const restored = Utils.UnMinify(LZString.decompressFromBase64(minified))
expect(str).toBe(restored)
})
it("shoud be able to decode the LZ-compression of a theme", () => {
const str = JSON.stringify(example, null, 0)
const minified = LZString.compressToBase64(str)
const restored = LZString.decompressFromBase64(minified)
expect(str).toBe(restored)
})
})
})