Skip to content

Commit

Permalink
refactor: improve api of API
Browse files Browse the repository at this point in the history
  • Loading branch information
Je committed Oct 14, 2020
1 parent 0b1ab39 commit 5c9946a
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 28 deletions.
30 changes: 15 additions & 15 deletions api.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
import log from './log.ts'
import type { ServerRequest } from './std.ts'
import type { APIRequest, APIResponse } from './types.ts'
import type { APIRequest, APIRequestURL, APIResponse, RouterURL } from './types.ts'

export class AlephAPIRequest implements APIRequest {
#req: ServerRequest

#url: APIRequestURL
cookies: ReadonlyMap<string, string>
params: ReadonlyMap<string, string>
query: URLSearchParams

constructor(req: ServerRequest, params: Record<string, string>, query: URLSearchParams) {
constructor(req: ServerRequest, url: RouterURL) {
this.#req = req

const paramsMap = new Map<string, string>()
for (const key in params) {
paramsMap.set(key, params[key])
for (const key in url.params) {
paramsMap.set(key, url.params[key])
}
this.#url = {
pathname: url.pathname,
params: paramsMap,
query: url.query,
}
this.params = paramsMap

this.cookies = new Map()
// todo: parse cookies

this.query = query
}

get url(): string {
return this.#req.url
get url(): APIRequestURL {
return this.#url
}

get method(): string {
Expand Down Expand Up @@ -90,7 +90,7 @@ export class AlephAPIResponse implements APIResponse {
status: this.#status,
headers: this.#headers,
body
})
}).catch(err => log.warn('ServerRequest.respond:', err.message))
}

json(data: any) {
Expand All @@ -99,6 +99,6 @@ export class AlephAPIResponse implements APIResponse {
status: this.#status,
headers: this.#headers,
body: JSON.stringify(data)
})
}).catch(err => log.warn('ServerRequest.respond:', err.message))
}
}
21 changes: 11 additions & 10 deletions project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,30 +153,31 @@ export class Project {
}

async callAPI(req: ServerRequest, loc: { pathname: string, search?: string }): Promise<APIHandle | null> {
const [{ pagePath, params, query }] = this.#apiRouting.createRouter(loc)
if (pagePath != '') {
const moduleID = pagePath + '.js'
const [url] = this.#apiRouting.createRouter(loc)
if (url.pagePath != '') {
const moduleID = url.pagePath + '.js'
if (this.#modules.has(moduleID)) {
try {
const { default: handle } = await import('file://' + this.#modules.get(moduleID)!.jsFile)
handle(
new AlephAPIRequest(req, params, query),
await handle(
new AlephAPIRequest(req, url),
new AlephAPIResponse(req)
)
} catch (err) {
req.respond({
status: 500,
headers: new Headers({ 'Content-Type': 'text/plain; charset=utf-8' }),
body: JSON.stringify({ error: { status: 500, message: err.message } })
})
}).catch(err => log.warn('ServerRequest.respond:', err.message))
log.error('callAPI:', err)
}
}
} else {
req.respond({
status: 404,
headers: new Headers({ 'Content-Type': 'application/javascript; charset=utf-8' }),
body: JSON.stringify({ error: { status: 404, message: 'page not found' } })
})
}).catch(err => log.warn('ServerRequest.respond:', err.message))
}
return null
}
Expand Down Expand Up @@ -859,21 +860,21 @@ export class Project {
` };`,
` if (ref.current) {`,
` ref.current.querySelectorAll("a").forEach(a => {`,
` const href = a.getAttribute("href")`,
` const href = a.getAttribute("href");`,
` if (href && !/^(https?|mailto|file):/i.test(href)) {`,
` a.addEventListener("click", onClick, false);`,
` appLinks.push(a);`,
` }`,
` });`,
` }`,
` return () => appLinks.forEach(a => a.removeEventListener("click", onClick));`,
` }, [])`,
` }, []);`,
` return React.createElement("div", {className: "markdown-page", ref, dangerouslySetInnerHTML: {__html: ${JSON.stringify(html)}}});`,
`}`,
`MarkdownPage.meta = ${JSON.stringify(props, undefined, this.isDev ? 4 : undefined)};`,
this.isDev && `_s(MarkdownPage, "useRef{ref}\\nuseEffect{}");`,
this.isDev && `$RefreshReg$(MarkdownPage, "MarkdownPage");`,
].filter(Boolean).join(this.isDev ? '\n' : '')
].filter(Boolean).map(l => this.isDev ? String(l).trim() : l).join(this.isDev ? '\n' : '')
mod.jsSourceMap = ''
mod.hash = (new Sha1).update(mod.jsContent).hex()
} else {
Expand Down
10 changes: 7 additions & 3 deletions types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,20 @@ export interface Config {
}
}

export interface APIRequestURL {
readonly pathname: string
readonly params: ReadonlyMap<string, string>
readonly query: URLSearchParams
}

export interface APIRequest {
readonly url: string
readonly url: APIRequestURL
readonly method: string
readonly proto: string
readonly protoMinor: number
readonly protoMajor: number
readonly headers: Headers
readonly cookies: ReadonlyMap<string, string>
readonly params: ReadonlyMap<string, string>
readonly query: URLSearchParams
}

export interface APIResponse {
Expand Down

0 comments on commit 5c9946a

Please sign in to comment.