-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(cache): loadData returns a promise
instead of a passing callback to it
- Loading branch information
Showing
2 changed files
with
29 additions
and
28 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,36 +1,37 @@ | ||
import { IData } from "../Data"; | ||
import { TContentType } from "./TContentType"; | ||
|
||
type TLoadData = (callback: TCallback, contentType: TContentType) => void; | ||
type TCallback = (data: IData) => void; | ||
export function loadData(type: TContentType): Promise<IData> { | ||
return new Promise((res, rej) => { | ||
const input = createInput(type); | ||
|
||
export const loadData: TLoadData = (callback, contentType) => { | ||
const input = document.createElement("input"); | ||
input.onchange = () => { | ||
const file = input.files?.[0]; | ||
|
||
input.type = "file"; | ||
input.accept = contentType; | ||
input.addEventListener("change", (e) => inputOnChange(e, callback), { | ||
once: true, | ||
}); | ||
input.click(); | ||
if (file) readData(file).then(res).catch(rej); | ||
}; | ||
|
||
input.remove(); | ||
}; | ||
input.click(); | ||
}); | ||
} | ||
|
||
function inputOnChange(e: Event, callback: TCallback) { | ||
const inputFile = (e.target as HTMLInputElement).files?.[0]; | ||
if (inputFile) { | ||
const fileReader = new FileReader(); | ||
function readData(file: File): Promise<IData> { | ||
return new Promise((res, rej) => { | ||
const reader = new FileReader(); | ||
|
||
fileReader.addEventListener("load", (e) => readerOnLoad(e, callback), { | ||
once: true, | ||
}); | ||
fileReader.readAsText(inputFile); | ||
} | ||
reader.onerror = rej; | ||
reader.onload = () => { | ||
const data = JSON.parse(reader.result as string); | ||
res(data); | ||
}; | ||
reader.readAsText(file); | ||
}); | ||
} | ||
|
||
function readerOnLoad(e: Event, callback: TCallback) { | ||
const data: IData = JSON.parse((e.target as FileReader).result as string); | ||
function createInput(type: TContentType): HTMLInputElement { | ||
const input = document.createElement("input"); | ||
input.type = "file"; | ||
input.accept = type; | ||
|
||
callback(data); | ||
return input; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters