Skip to content

Commit

Permalink
fix: Use status code specified in context
Browse files Browse the repository at this point in the history
Fix elysiajs#56

Previously the html plugin would always return 200 for HTML responses.
This commit adds support for reading the status code in set.status to
determine which status code to use. It fallbacks to 200 if no status
code is set. It uses the StatusMap exported by Elysia to map res.status
values supplied as string literals.

Example for statuscode has been added to examples folder showcasing
returning Forbidden status. Added test for overriding status code.

Needed to upgrade Elysia peer and dev dependency to a newer version as
the StatusMap value was not available in elysia 1.0.2. Running bun
install and pnpm install also updated the patch versions of @kitajs/*
dependencies.
  • Loading branch information
snorremd committed Mar 30, 2024
1 parent b94978d commit 363f74e
Show file tree
Hide file tree
Showing 8 changed files with 133 additions and 55 deletions.
Binary file modified bun.lockb
Binary file not shown.
4 changes: 4 additions & 0 deletions example/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,7 @@ app.handle(new Request('http://localhost:8080/'))
app.handle(new Request('http://localhost:8080/'))
.then((x) => x.headers.toJSON())
.then(console.log)

app.handle(new Request('http://localhost:8080/'))
.then((x) => x.status)
.then(console.log)
16 changes: 16 additions & 0 deletions example/statuscode.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Elysia } from 'elysia'
import { html } from '../src'

const app = new Elysia()
.use(html({ autoDetect: true }))
.get('/a', ({ html, set }) => {
set.status = 'Forbidden'
return html(`<h1>Forbidden!</h1>`)
})
.compile()

console.log(app.routes[0]?.composed?.toString())

app.handle(new Request('http://localhost:8080/a'))
.then((x) => x.status)
.then(console.log)
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,13 @@
"format": "prettier --write ."
},
"peerDependencies": {
"elysia": ">= 1.0.2"
"elysia": ">= 1.0.6"
},
"devDependencies": {
"@elysiajs/stream": "^0.7.2",
"@types/bun": "^1.0.4",
"@types/node": "^20.7.2",
"elysia": "1.0.2",
"elysia": "1.0.6",
"eslint": "^8.50.0",
"rimraf": "^5.0.5",
"typescript": "^5.2.2"
Expand Down
120 changes: 78 additions & 42 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 12 additions & 7 deletions src/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ import { isHtml, isTagHtml } from './utils'
export function handleHtml(
value: string | Readable | Promise<string | Readable>,
options: HtmlOptions,
hasContentType: boolean
hasContentType: boolean,
status?: number
): Promise<Response | string> | Response | string {

// Only use promises if value is a promise itself
if (value instanceof Promise) {
return value.then((v) => handleHtml(v, options, hasContentType))
Expand All @@ -24,9 +26,7 @@ export function handleHtml(

return new Response(
value,
hasContentType
? undefined
: { headers: { 'content-type': options.contentType! } }
initValue(options, hasContentType, status)
)
}

Expand Down Expand Up @@ -60,8 +60,13 @@ export function handleHtml(

return new Response(
stream as any,
hasContentType
? undefined
: { headers: { 'content-type': options.contentType! } }
initValue(options, hasContentType, status)
)
}


function initValue(options: HtmlOptions, hasContentType: boolean, status?: number) {
return hasContentType
? { status: status?? 200 }
: { headers: { 'content-type': options.contentType! }, status: status?? 200 }
}
15 changes: 11 additions & 4 deletions src/html.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Elysia } from 'elysia'
import { Elysia, StatusMap } from 'elysia'
import { Readable } from 'node:stream'
import { renderToStream } from '@kitajs/html/suspense'

Expand All @@ -17,22 +17,26 @@ export function html(options: HtmlOptions = {}) {
name: '@elysiajs/html',
seed: options
}).derive({ as: 'global' }, ({ set }) => {

return {
html(
value: Readable | JSX.Element
): Promise<Response | string> | Response | string {
return handleHtml(value, options, 'content-type' in set.headers)
const status = typeof set.status === 'string' ? StatusMap[set.status] : set.status
return handleHtml(value, options, 'content-type' in set.headers, status)
},
stream<A = any>(
value: (this: void, arg: A & { id: number }) => JSX.Element,
args: A
) {
const status = typeof set.status === 'string' ? StatusMap[set.status] : set.status
return handleHtml(
renderToStream((id) =>
(value as Function)({ ...args, id })
),
options,
'content-type' in set.headers
'content-type' in set.headers,
status
)
}
}
Expand All @@ -48,10 +52,13 @@ export function html(options: HtmlOptions = {}) {
// @kitajs/html stream
(value instanceof Readable && 'rid' in value)
) {
const status = typeof set.status === 'string' ? StatusMap[set.status] : set.status

const response = await handleHtml(
value,
options,
'content-type' in set.headers
'content-type' in set.headers,
status
)

if (response instanceof Response) return response
Expand Down
10 changes: 10 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,16 @@ describe('HTML', () => {
'text/html; charset=utf8'
)
})

it('returns user provided status code', async () => {
const app = new Elysia().use(html()).get('/', ({ html, set }) => {
set.status = 404
return html('<h1>Not Found</h1>')
})

const res = await app.handle(req('/'))
expect(res.status).toBe(404)
})
})

describe('HTML vs No html - header', () => {
Expand Down

0 comments on commit 363f74e

Please sign in to comment.