-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(dev): check publicDir before app routes
This is useful when an app route overlaps with a public file.
- Loading branch information
1 parent
bfe374a
commit 401e66b
Showing
3 changed files
with
100 additions
and
39 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
import fs from 'fs' | ||
import * as mime from 'mrmime' | ||
import path from 'path' | ||
import { RenderedFile } from './app' | ||
import { RuntimeConfig } from './config' | ||
|
||
export interface ServePublicFileOptions { | ||
/** @default runtimeConfig.publicDir */ | ||
root?: string | ||
/** | ||
* When defined, only files matching this can be served | ||
* by this middleware. | ||
*/ | ||
include?: RegExp | ||
/** | ||
* When defined, files matching this cannot be served | ||
* by this middleware. | ||
*/ | ||
ignore?: RegExp | ||
} | ||
|
||
export type PublicFile = RenderedFile & { | ||
data: Buffer | ||
} | ||
|
||
export function servePublicFile( | ||
url: string, | ||
runtimeConfig: RuntimeConfig, | ||
options?: ServePublicFileOptions | ||
): PublicFile | null { | ||
const fileName = url.slice(runtimeConfig.base.length) | ||
if (options?.ignore?.test(fileName)) { | ||
return null | ||
} | ||
if (options?.include && !options.include.test(fileName)) { | ||
return null | ||
} | ||
try { | ||
const publicDir = options?.root || runtimeConfig.publicDir | ||
const content = fs.readFileSync(path.join(publicDir, fileName)) | ||
return { | ||
id: fileName, | ||
data: content, | ||
get mime() { | ||
return mime.lookup(fileName) || 'application/octet-stream' | ||
}, | ||
} | ||
} catch (e: any) { | ||
if (e.code == 'ENOENT' || e.code == 'EISDIR') { | ||
return null | ||
} | ||
throw e | ||
} | ||
} |