refactor: extract file serve to own module
This commit is contained in:
parent
ed408be3fc
commit
da0a668285
20
server.ts
20
server.ts
|
@ -1,7 +1,6 @@
|
||||||
import { contentType } from '@std/media-types'
|
|
||||||
import { extname } from '@std/path'
|
|
||||||
import { getBaseUrl, getSourceUrl } from './src/url_utils.ts'
|
import { getBaseUrl, getSourceUrl } from './src/url_utils.ts'
|
||||||
import { toUser, toUserDomain } from './src/user_utils.ts'
|
import { toUser, toUserDomain } from './src/user_utils.ts'
|
||||||
|
import { serveFile } from './src/serve_file.ts'
|
||||||
|
|
||||||
Deno.serve({ port: Number(Deno.env.get('PORT') ?? 8000) }, async (req) => {
|
Deno.serve({ port: Number(Deno.env.get('PORT') ?? 8000) }, async (req) => {
|
||||||
const reqUrl = new URL(req.url)
|
const reqUrl = new URL(req.url)
|
||||||
|
@ -21,20 +20,5 @@ Deno.serve({ port: Number(Deno.env.get('PORT') ?? 8000) }, async (req) => {
|
||||||
const fileUrl = getSourceUrl(filePath, baseUrl)
|
const fileUrl = getSourceUrl(filePath, baseUrl)
|
||||||
|
|
||||||
// Get source and mime type
|
// Get source and mime type
|
||||||
const response = await fetch(fileUrl)
|
return serveFile(fileUrl)
|
||||||
const ext = extname(fileUrl.pathname)
|
|
||||||
const mimeType = contentType(ext) ?? 'text/plain; charset=utf-8' // Assume plain text as default.
|
|
||||||
|
|
||||||
if (response.ok) {
|
|
||||||
// Update content-type if not bin file
|
|
||||||
const headers = new Headers(response.headers)
|
|
||||||
if (headers.get('Content-Type') !== 'application/octet-stream') {
|
|
||||||
headers.set('Content-Type', mimeType)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Stream original file to user
|
|
||||||
return new Response(response.body, { headers })
|
|
||||||
}
|
|
||||||
|
|
||||||
return response
|
|
||||||
})
|
})
|
||||||
|
|
22
src/serve_file.ts
Normal file
22
src/serve_file.ts
Normal file
|
@ -0,0 +1,22 @@
|
||||||
|
import { extname } from '@std/path'
|
||||||
|
import { contentType } from '@std/media-types'
|
||||||
|
|
||||||
|
export async function serveFile(fileUrl: URL): Promise<Response> {
|
||||||
|
// Get source and mime type
|
||||||
|
const response = await fetch(fileUrl)
|
||||||
|
const ext = extname(fileUrl.pathname)
|
||||||
|
const mimeType = contentType(ext) ?? 'text/plain; charset=utf-8' // Assume plain text as default.
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
// Update content-type if not bin file
|
||||||
|
const headers = new Headers(response.headers)
|
||||||
|
if (headers.get('Content-Type') !== 'application/octet-stream') {
|
||||||
|
headers.set('Content-Type', mimeType)
|
||||||
|
}
|
||||||
|
// Stream original file to user
|
||||||
|
return new Response(response.body, { headers })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return raw error if status !== 2XX
|
||||||
|
return response
|
||||||
|
}
|
Loading…
Reference in a new issue