Skip to content
This repository was archived by the owner on Jul 6, 2025. It is now read-only.

Commit e236384

Browse files
author
Je
committed
refactor: improve APIResponse
1 parent 201f14d commit e236384

File tree

2 files changed

+16
-13
lines changed

2 files changed

+16
-13
lines changed

api.ts

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -54,17 +54,18 @@ export class AlephAPIRequest implements APIRequest {
5454

5555
export class AlephAPIResponse implements APIResponse {
5656
#req: ServerRequest
57-
#headers: Headers
5857
#status: number
58+
#headers: Headers
59+
#sent: boolean
5960

6061
constructor(req: ServerRequest) {
6162
this.#req = req
63+
this.#status = 200
6264
this.#headers = new Headers({
6365
'Status': '200',
6466
'Server': 'Aleph.js',
65-
'Date': (new Date).toUTCString(),
6667
})
67-
this.#status = 200
68+
this.#sent = false
6869
}
6970

7071
status(code: number): this {
@@ -95,7 +96,16 @@ export class AlephAPIResponse implements APIResponse {
9596
}).catch(err => log.warn('ServerRequest.respond:', err.message))
9697
}
9798

99+
async json(data: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number) {
100+
return this.send(JSON.stringify(data, replacer, space), 'application/json', true)
101+
}
102+
98103
async send(data: string | Uint8Array | ArrayBuffer, contentType?: string, gzip = false) {
104+
if (this.#sent) {
105+
log.warn('ServerRequest.respond: repeat send calls')
106+
return
107+
}
108+
99109
let body: Uint8Array
100110
if (typeof data === 'string') {
101111
body = new TextEncoder().encode(data)
@@ -114,19 +124,12 @@ export class AlephAPIResponse implements APIResponse {
114124
this.#headers.set('Content-Encoding', 'gzip')
115125
body = gzipEncode(body)
116126
}
127+
this.#headers.set('Date', (new Date).toUTCString())
128+
this.#sent = true
117129
return this.#req.respond({
118130
status: this.#status,
119131
headers: this.#headers,
120132
body
121133
}).catch(err => log.warn('ServerRequest.respond:', err.message))
122134
}
123-
124-
async json(data: any) {
125-
this.#headers.set('Content-Type', 'application/json')
126-
return this.#req.respond({
127-
status: this.#status,
128-
headers: this.#headers,
129-
body: JSON.stringify(data)
130-
}).catch(err => log.warn('ServerRequest.respond:', err.message))
131-
}
132135
}

server.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ export async function start(appDir: string, port: number, isDev = false, reload
128128
const body = await Deno.readFile(filePath)
129129
const ct = getContentType(filePath)
130130
resp.setHeader('Last-Modified', info.mtime!.toUTCString())
131-
resp.send(body, ct, ct.startsWith('text/') || /\.(m?js|json|xml)$/i.test(filePath))
131+
resp.send(body, ct, ct.startsWith('text/') || /\.(m?js|json|xml|svg)$/i.test(filePath))
132132
continue
133133
}
134134

0 commit comments

Comments
 (0)