Skip to content

Fix up types for cached and returned data. #84

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 17, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 17 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
const privateData = new WeakMap()
interface CachedData {
src: string
data: Promise<string | Error>
}
const privateData = new WeakMap<IncludeFragmentElement, CachedData>()

function isWildcard(accept: string | null) {
return accept && !!accept.split(',').find(x => x.match(/^\s*\*\/\*/))
Expand Down Expand Up @@ -41,7 +45,7 @@ export default class IncludeFragmentElement extends HTMLElement {
this.setAttribute('accept', val)
}

get data(): Promise<string> {
get data(): Promise<string | Error> {
return this.#getData()
}

Expand Down Expand Up @@ -97,7 +101,7 @@ export default class IncludeFragmentElement extends HTMLElement {
})
}

load(): Promise<string> {
load(): Promise<string | Error> {
return this.#getData()
}

Expand Down Expand Up @@ -133,11 +137,14 @@ export default class IncludeFragmentElement extends HTMLElement {
this.#busy = true
this.#observer.unobserve(this)
try {
const html = await this.#getData()
const data = await this.#getData()
if (data instanceof Error) {
throw data
}

const template = document.createElement('template')
// eslint-disable-next-line github/no-inner-html
template.innerHTML = html
template.innerHTML = data
const fragment = document.importNode(template.content, true)
const canceled = !this.dispatchEvent(
new CustomEvent('include-fragment-replace', {cancelable: true, detail: {fragment}})
Expand All @@ -150,12 +157,13 @@ export default class IncludeFragmentElement extends HTMLElement {
}
}

#getData(): Promise<string> {
async #getData(): Promise<string | Error> {
const src = this.src
let data = privateData.get(this)
if (data && data.src === src) {
return data.data
const cachedData = privateData.get(this)
if (cachedData && cachedData.src === src) {
return cachedData.data
} else {
let data: Promise<string | Error>
if (src) {
data = this.#fetchDataWithEvents()
} else {
Expand Down