Skip to content

Commit

Permalink
copy fetcher/ from inet-js
Browse files Browse the repository at this point in the history
  • Loading branch information
xieyuheng committed Nov 15, 2023
1 parent f6a3a05 commit 28a10c1
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 2 deletions.
8 changes: 6 additions & 2 deletions TODO.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
# module system

node/Node

Mod -- has loader

Place and Transition -- has modId

Mod has definitions: Map<string, Definition>

# loader

copy `loader/` from inet-js

# command-line

# net

[net] addPlace
Expand Down
63 changes: 63 additions & 0 deletions src/fetcher/Fetcher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
export type FetcherHandler = {
fetchText: (url: URL) => string | Promise<string>
formatURL?: (url: URL) => string
}

export class Fetcher {
handlers: Record<string, FetcherHandler> = {}

constructor() {
this.register("http", {
fetchText: async (url) => await (await fetch(url)).text(),
})

this.register("https", {
fetchText: async (url) => await (await fetch(url)).text(),
})
}

findHandler(url: URL): FetcherHandler | undefined {
const scheme = url.protocol.slice(0, url.protocol.length - 1)
return this.handlers[scheme]
}

formatURL(url: URL): string {
const handler = this.findHandler(url)
if (handler === undefined) {
throw new Error(
[
`[Fetcher.formatURL] I meet unknown protocol.`,
``,
` protocol: ${url.protocol}`,
` url: ${url.href}`,
].join("\n"),
)
}

if (handler.formatURL) {
return handler.formatURL(url)
} else {
return url.href
}
}

async fetchText(url: URL): Promise<string> {
const handler = this.findHandler(url)
if (handler === undefined) {
throw new Error(
[
`[Fetcher.fetchText] I meet unknown protocol.`,
``,
` protocol: ${url.protocol}`,
` url: ${url.href}`,
].join("\n"),
)
}

return handler.fetchText(url)
}

register(scheme: string, handler: FetcherHandler): void {
this.handlers[scheme] = handler
}
}
1 change: 1 addition & 0 deletions src/fetcher/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./Fetcher"

0 comments on commit 28a10c1

Please sign in to comment.