assets-getter.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /**
  2. * This class is responsible for loading assets from the server.
  3. */
  4. export class assets_getter {
  5. #app_url;
  6. /**
  7. * This create new assets getter.
  8. *
  9. * @param {string} app_url - This is base app url
  10. */
  11. constructor(app_url) {
  12. this.#app_url = app_url;
  13. }
  14. /**
  15. * This fetch file from the config directory.
  16. *
  17. * @async
  18. * @param {string} file - Name of the file to load
  19. * @returns {string, object} - Content of the file, or object if json
  20. * @throws {Error} - When file not exists on the server
  21. * @throws {TypeError} - When JSON file is bad formated
  22. */
  23. async load(file) {
  24. const url = this.#get_url(file);
  25. const result = await fetch(url);
  26. if (!result.ok) {
  27. let info = `Can not load file: "${url}", `;
  28. info += `status: "${result.status}".`;
  29. throw new Error(info);
  30. }
  31. if (this.#is_json(file)) {
  32. try {
  33. return await result.json();
  34. } catch (error) {
  35. let info = `JSON file "${file}" is bad formated. `;
  36. info += `More: "${error.message}".`;
  37. throw new TypeError(info);
  38. }
  39. }
  40. return await result.text();
  41. }
  42. /**
  43. * @async
  44. * @returns {object} - Return enviroment json as object
  45. */
  46. get enviroment() {
  47. return this.load("enviroment.json");
  48. }
  49. /**
  50. * @async
  51. * @returns {object} - Return items json as object
  52. */
  53. get items() {
  54. return this.load("items.json");
  55. }
  56. /**
  57. * @async
  58. * @returns {object} - Return rooms json as object
  59. */
  60. get rooms() {
  61. return this.load("rooms.json");
  62. }
  63. /**
  64. * @returns {string} - Base config directory on server
  65. */
  66. get #base_url() {
  67. return "/static/config";
  68. }
  69. /**
  70. * This function generate full URL to the file on server.
  71. *
  72. * @param {string} file - Name of the file in config location
  73. * @returns {string} - Full path to the file on server
  74. */
  75. #get_url(file) {
  76. return `${this.#app_url}/${this.#base_url}/${file}`;
  77. }
  78. /**
  79. * This function check that file is json.
  80. *
  81. * @param {string} file - Name of the file to load
  82. * @returns {bool} - True if file is json, os false when not
  83. */
  84. #is_json(file) {
  85. return file.substring(file.length - 5) === ".json";
  86. }
  87. }