| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- import { room } from "./room.js";
- /**
- * This class is responsible for loading assets from the server.
- */
- export class assets_getter {
- #app_url;
-
- /**
- * This create new assets getter.
- *
- * @param {string} app_url - This is base app url
- */
- constructor(app_url) {
- this.#app_url = app_url;
- }
- /**
- * This fetch file from the config directory.
- *
- * @async
- * @param {string} file - Name of the file to load
- * @returns {string, object} - Content of the file, or object if json
- * @throws {Error} - When file not exists on the server
- * @throws {TypeError} - When JSON file is bad formated
- */
- async load(file) {
- const url = this.#get_url(file);
- const result = await fetch(url);
- if (!result.ok) {
- let info = `Can not load file: "${url}", `;
- info += `status: "${result.status}".`;
- throw new Error(info);
- }
- if (this.#is_json(file)) {
- try {
- return await result.json();
- } catch (error) {
- let info = `JSON file "${file}" is bad formated. `;
- info += `More: "${error.message}".`;
- throw new TypeError(info);
- }
- }
- return await result.text();
- }
- /**
- * This return url for texture, from texture name or room.
- *
- * @param {string, room} target - Name or room of the texture
- * @returns {string} Link to the texture
- */
- texture(target) {
- if (target instanceof room) {
- target = target.texture;
- }
- return this.#get_url(`textures/${target}`);
- }
- /**
- * @async
- * @returns {object} - Return enviroment json as object
- */
- get enviroment() {
- return this.load("enviroment.json");
- }
- /**
- * @async
- * @returns {object} - Return items json as object
- */
- get items() {
- return this.load("items.json");
- }
- /**
- * @async
- * @returns {object} - Return rooms json as object
- */
- get rooms() {
- return this.load("rooms.json");
- }
- /**
- * @returns {string} - Base config directory on server
- */
- get #base_url() {
- return "/static/config";
- }
- /**
- * This function generate full URL to the file on server.
- *
- * @param {string} file - Name of the file in config location
- * @returns {string} - Full path to the file on server
- */
- #get_url(file) {
- return `${this.#app_url}/${this.#base_url}/${file}`;
- }
- /**
- * This function check that file is json.
- *
- * @param {string} file - Name of the file to load
- * @returns {bool} - True if file is json, os false when not
- */
- #is_json(file) {
- return file.substring(file.length - 5) === ".json";
- }
- }
|