Skip to content

Implement Range Requests #31

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 62 additions & 15 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,26 @@ const listFiles = async (dir: string): Promise<string[]> => {
return all.flat()
}

const createRangeResponse = async (
file: Blob,
range: string,
headers: Record<string, string>
) => {
// from https://bun.sh/docs/api/http#streaming-files
// parse `Range` header
const [start = 0, end = Infinity] = range
.split('=') // ["Range: bytes", "0-100"]
.at(-1)! // "0-100"
.split('-') // ["0", "100"]
.map(Number) // [0, 100]

headers['Content-Range'] = `bytes ${start}-${end - 1}/${file.size}`
return new Response(file.slice(start, end), {
headers,
status: 206
})
}

export const staticPlugin = async <Prefix extends string = '/prefix'>(
{
assets = 'public',
Expand Down Expand Up @@ -236,12 +256,22 @@ export const staticPlugin = async <Prefix extends string = '/prefix'>(
? prefix + fileName.split(sep).join(URL_PATH_SEP)
: join(prefix, fileName)

let responseSingleton: Response

app.get(
pathName,
noCache
? new Response(file, {
headers
})
? ({ headers: reqHeaders }) => {
return !reqHeaders.range
? (responseSingleton ??= new Response(file, {
headers
}))
: createRangeResponse(
file,
reqHeaders['range'],
headers
)
}
: async ({ headers: reqHeaders }) => {
if (await isCached(reqHeaders, etag, filePath)) {
return new Response(null, {
Expand All @@ -255,9 +285,15 @@ export const staticPlugin = async <Prefix extends string = '/prefix'>(
if (maxAge !== null)
headers['Cache-Control'] += `, max-age=${maxAge}`

return new Response(file, {
headers
})
return !reqHeaders.range
? new Response(file, {
headers
})
: createRangeResponse(
file,
reqHeaders['range'],
headers
)
}
)

Expand All @@ -279,9 +315,8 @@ export const staticPlugin = async <Prefix extends string = '/prefix'>(
headers['Etag'] = etag
headers['Cache-Control'] = directive
if (maxAge !== null)
headers[
'Cache-Control'
] += `, max-age=${maxAge}`
headers['Cache-Control'] +=
`, max-age=${maxAge}`

return new Response(file, {
headers
Expand Down Expand Up @@ -358,9 +393,15 @@ export const staticPlugin = async <Prefix extends string = '/prefix'>(
}

if (noCache)
return new Response(file, {
headers
})
return !reqHeaders.range
? new Response(file, {
headers
})
: createRangeResponse(
file,
reqHeaders['range'],
headers
)

const etag = await generateETag(file)
if (await isCached(reqHeaders, etag, path))
Expand All @@ -374,9 +415,15 @@ export const staticPlugin = async <Prefix extends string = '/prefix'>(
if (maxAge !== null)
headers['Cache-Control'] += `, max-age=${maxAge}`

return new Response(file, {
headers
})
return !reqHeaders.range
? new Response(file, {
headers
})
: createRangeResponse(
file,
reqHeaders['range'],
headers
)
} catch (error) {
throw new NotFoundError()
}
Expand Down
20 changes: 20 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -437,4 +437,24 @@ describe('Static Plugin', () => {
res = await app.handle(req('/public/html'))
expect(res.status).toBe(404)
})

it.each([
[{}],
[{ alwaysStatic: true }],
[{ noCache: true }],
[{ alwaysStatic: true, noCache: true }]
])('should work with range requests', async (options) => {
const app = new Elysia().use(staticPlugin(options))
await app.modules

const request = req('/public/takodachi.png')
request.headers.append('Range', 'bytes=100-200')

const res = await app.handle(request)
expect(res.status).toBe(206)
expect(res.headers.get('Content-Range')).toBe('bytes 100-199/71118')

const body = await res.blob()
expect(body.size).toBe(100)
})
})