-
Notifications
You must be signed in to change notification settings - Fork 461
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
50 additions
and
2 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
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,46 @@ | ||
import { CompatibilityEvent, eventHandler } from 'h3' | ||
|
||
export interface RenderResponse { | ||
body: string, | ||
statusCode: number, | ||
statusMessage: string, | ||
headers: Record<string, string> | ||
} | ||
|
||
export type RenderHandler = (event: CompatibilityEvent) => Partial<RenderResponse> | Promise<Partial<RenderResponse>> | ||
|
||
export function defineRenderHandler (handler: RenderHandler) { | ||
return eventHandler(async (event) => { | ||
// TODO: Use serve-placeholder | ||
if (event.req.url.endsWith('/favicon.ico')) { | ||
event.res.setHeader('Content-Type', 'image/x-icon') | ||
event.res.end('data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7') | ||
return | ||
} | ||
|
||
const response = await handler(event) | ||
|
||
// TODO: Warn if response is already handled | ||
|
||
// TODO: Caching support | ||
|
||
// Send headers | ||
if (!event.res.headersSent && response.headers) { | ||
for (const header in response.headers) { | ||
event.res.setHeader(header, response.headers[header]) | ||
} | ||
if (response.statusCode) { | ||
event.res.statusCode = response.statusCode | ||
} | ||
if (response.statusMessage) { | ||
event.res.statusMessage = response.statusMessage | ||
} | ||
} | ||
|
||
// Send response body | ||
if (!event.res.writableEnded) { | ||
// TODO: Warn if body is not string | ||
event.res.end(typeof response.body === 'string' ? response.body : JSON.stringify(response.body)) | ||
} | ||
}) | ||
} |