refactor: improve structure of src

This commit is contained in:
Johannes Loher 2022-11-04 21:47:18 +01:00
parent b74919b75b
commit c5d4ec1abd
96 changed files with 146 additions and 157 deletions

22
src/utils/logger.ts Normal file
View file

@ -0,0 +1,22 @@
// SPDX-FileCopyrightText: 2021 Johannes Loher
//
// SPDX-License-Identifier: MIT
const loggingContext = "DS4";
const loggingSeparator = "|";
type LogLevel = "debug" | "info" | "warning" | "error";
type LoggingFunction = (...data: unknown[]) => void;
const getLoggingFunction = (type: LogLevel = "info"): LoggingFunction => {
const log = { debug: console.debug, info: console.info, warning: console.warn, error: console.error }[type];
return (...data: unknown[]) => log(loggingContext, loggingSeparator, ...data);
};
export const logger = Object.freeze({
debug: getLoggingFunction("debug"),
info: getLoggingFunction("info"),
warn: getLoggingFunction("warning"),
error: getLoggingFunction("error"),
getLoggingFunction,
});

40
src/utils/utils.ts Normal file
View file

@ -0,0 +1,40 @@
// SPDX-FileCopyrightText: 2021 Johannes Loher
//
// SPDX-License-Identifier: MIT
/**
* Tests if the given `value` is truthy.
*
* If it is not truthy, an {@link Error} is thrown, which depends on the given `message` parameter:
* - If `message` is a string`, it is used to construct a new {@link Error} which then is thrown.
* - If `message` is an instance of {@link Error}, it is thrown.
* - If `message` is `undefined`, an {@link Error} with a default message is thrown.
*/
export function enforce(value: unknown, message?: string | Error): asserts value {
if (!value) {
if (!message) {
message =
getGameSafe()?.i18n.localize("DS4.ErrorUnexpectedError") ??
"There was an unexpected error in the Dungeonslayers 4 system. For more details, please take a look at the console (F12).";
}
throw message instanceof Error ? message : new Error(message);
}
}
export function getCanvas(): Canvas {
if (!(canvas instanceof Canvas) || !canvas.ready) {
throw new Error(getGame().i18n.localize("DS4.ErrorCanvasIsNotInitialized"));
}
return canvas;
}
export function getGame(): Game {
if (!(game instanceof Game)) {
throw new Error("Game is not initialized yet.");
}
return game;
}
export function getGameSafe(): Game | undefined {
return game instanceof Game ? game : undefined;
}