From 5c9946a4db72c727e3735892798c958c68b413eb Mon Sep 17 00:00:00 2001 From: Je Date: Wed, 14 Oct 2020 22:07:04 +0800 Subject: [PATCH] refactor: improve api of API --- api.ts | 30 +++++++++++++++--------------- project.ts | 21 +++++++++++---------- types.ts | 10 +++++++--- 3 files changed, 33 insertions(+), 28 deletions(-) diff --git a/api.ts b/api.ts index f0d9d72d8..99d4e5960 100644 --- a/api.ts +++ b/api.ts @@ -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 - params: ReadonlyMap - query: URLSearchParams - constructor(req: ServerRequest, params: Record, query: URLSearchParams) { + constructor(req: ServerRequest, url: RouterURL) { this.#req = req const paramsMap = new Map() - 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 { @@ -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) { @@ -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)) } } diff --git a/project.ts b/project.ts index 191cd08d8..b4f6cd11e 100644 --- a/project.ts +++ b/project.ts @@ -153,14 +153,14 @@ export class Project { } async callAPI(req: ServerRequest, loc: { pathname: string, search?: string }): Promise { - 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) { @@ -168,7 +168,8 @@ export class Project { 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 { @@ -176,7 +177,7 @@ export class Project { 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 } @@ -859,7 +860,7 @@ 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);`, @@ -867,13 +868,13 @@ export class Project { ` });`, ` }`, ` 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 { diff --git a/types.ts b/types.ts index dd1d45bc8..863cff2dc 100644 --- a/types.ts +++ b/types.ts @@ -26,16 +26,20 @@ export interface Config { } } +export interface APIRequestURL { + readonly pathname: string + readonly params: ReadonlyMap + 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 - readonly params: ReadonlyMap - readonly query: URLSearchParams } export interface APIResponse {