Skip to content

Commit

Permalink
feat(http): use type instead of mime
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed May 21, 2024
1 parent 42be858 commit c2c6f96
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
10 changes: 7 additions & 3 deletions packages/core/src/adapter/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,20 @@ import { basename } from 'node:path'
import FileType from 'file-type'
import { FileResponse } from '../index.js'
import { readFile } from 'node:fs/promises'
import { Binary } from 'cosmokit'

export { lookup } from 'node:dns/promises'

export async function loadFile(url: string): Promise<FileResponse | undefined> {
if (url.startsWith('file://')) {
const data = await readFile(fileURLToPath(url))
const result = await FileType.fromBuffer(data)
// https://stackoverflow.com/questions/8609289/convert-a-binary-nodejs-buffer-to-javascript-arraybuffer#answer-31394257
const buffer = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)
return { mime: result?.mime, filename: basename(url), data: buffer }
return {
type: result?.mime!,
mime: result?.mime,
filename: basename(url),
data: Binary.fromSource(data),
}
}
}

Expand Down
12 changes: 7 additions & 5 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,8 @@ export interface FileConfig {
}

export interface FileResponse {
type: string
/** @deprecated use `type` instead */
mime?: string
filename: string
data: ArrayBuffer
Expand Down Expand Up @@ -384,20 +386,20 @@ export class HTTP extends Service<HTTP.Config> {
if (result) return result
const capture = /^data:([\w/-]+);base64,(.*)$/.exec(url)
if (capture) {
const [, mime, base64] = capture
const [, type, base64] = capture
let name = 'file'
const ext = mime && mimedb[mime]?.extensions?.[0]
const ext = type && mimedb[type]?.extensions?.[0]
if (ext) name += `.${ext}`
return { mime, data: Binary.fromBase64(base64), filename: name }
return { type, mime: type, data: Binary.fromBase64(base64), filename: name }
}
const { headers, data, url: responseUrl } = await this<ArrayBuffer>(url, {
method: 'GET',
responseType: 'arraybuffer',
timeout: +options.timeout! || undefined,
})
const mime = headers.get('content-type') ?? undefined
const type = headers.get('content-type')!
const [, name] = responseUrl.match(/.+\/([^/?]*)(?=\?)?/)!
return { mime, filename: name, data }
return { type, mime: type, filename: name, data }
}

async isLocal(url: string) {
Expand Down

0 comments on commit c2c6f96

Please sign in to comment.