Skip to content

Commit

Permalink
Added typings to Data class
Browse files Browse the repository at this point in the history
  • Loading branch information
profexorgeek committed Dec 28, 2021
1 parent d86b4c4 commit ce97319
Showing 1 changed file with 16 additions and 16 deletions.
32 changes: 16 additions & 16 deletions src/Data/Data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,34 @@ import FrostFlake from '../FrostFlake';

export default class Data {

private static _cache = {};
private static _cache: any = {};

static async loadResponse(src) {
static async loadResponse(src: string): Promise<Response> {
const response = await fetch(src);
if(!response.ok) {
const msg = `Bad network response for ${src}`;
FrostFlake.Log.error(msg)
throw new Error(msg);
}

return response;
}

static async loadImage(src, key = null, skipCache = false) {

static async loadImage(src: string, key: string = null, skipCache: boolean = false): Promise<HTMLImageElement> {

// EARLY OUT: return from cache
if(src in this._cache && !skipCache) {
return this._cache[src];
}

const promise = new Promise((resolve, reject) => {
const img = new Image();
img.addEventListener('load', () => resolve(img));
img.addEventListener('error', (err) => {
const promise = new Promise<HTMLImageElement>((resolve, reject) => {
const promiseImage = new Image();
promiseImage.addEventListener('load', () => resolve(img));
promiseImage.addEventListener('error', (err) => {
FrostFlake.Log.error(`Error loading ${src}...`);
reject(err)
});
img.src = src;
promiseImage.src = src;
});

let img = await promise;
Expand All @@ -42,43 +42,43 @@ export default class Data {
return img;
}

static async loadJson(src) {
static async loadJson(src: string): Promise<any> {
const response = await Data.loadResponse(src);
return await response.json();
}

static async loadAudio(src) {
static async loadAudio(src: string): Promise<ArrayBuffer> {
const response = await Data.loadResponse(src);
let buffer = response.arrayBuffer();
return buffer;
}


static clearCache() {
static clearCache(): void {
Data._cache = {};
}

static itemExists(key) {
static itemExists(key: string): boolean {
if(key in Data._cache && Data._cache[key] !== null) {
return true;
}
return false;
}

static addItem(key, item) {
static addItem(key: string, item: any): void {
if(Data.itemExists(key)) {
FrostFlake.Log.warn(`Item already exists for ${key}, overwriting.`);
}
Data._cache[key] = item;
}

static removeItem(key) {
static removeItem(key: string): void {
if(Data.itemExists(key)) {
delete Data._cache[key];
}
}

static getItem(key) {
static getItem(key: string): any {
if(Data.itemExists(key)) {
return Data._cache[key];
}
Expand Down

0 comments on commit ce97319

Please sign in to comment.