Skip to content

Commit

Permalink
🧹 chore: review issues
Browse files Browse the repository at this point in the history
  • Loading branch information
SaltyAom committed Jan 1, 2024
1 parent 25d48eb commit a6bf3d8
Show file tree
Hide file tree
Showing 15 changed files with 167 additions and 35 deletions.
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
# 0.8.7. - 29 Dec 2023
Improvement:
- [#385](https://github.com/elysiajs/elysia/issues/385) If error is instanceof Response, respond with it

Bug fix:
- onRequest doesn't early return
- handle thrown error function
- [#373](https://github.com/elysiajs/elysia/issues/373) cookie is not set when File is return
- [#379](https://github.com/elysiajs/elysia/issues/379) WebSocket: Sending a space character ' ' receives 0
- [#317](https://github.com/elysiajs/elysia/issues/317) Exclude TypeBox from bundling

# 0.8.6. - 29 Dec 2023
Bug fix:
- body without default value thrown Object.assign error
Expand Down
3 changes: 2 additions & 1 deletion build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ await Bun.build({
outdir: './dist/bun',
minify: true,
target: 'bun',
sourcemap: 'external'
sourcemap: 'external',
'external': ['@sinclair/typebox']
})

copyFileSync('dist/index.d.ts', 'dist/bun/index.d.ts')
Expand Down
26 changes: 16 additions & 10 deletions example/a.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
import { Elysia, t } from '../src'
import { cors } from '@elysiajs/cors'
import { Elysia, error, t } from '../src'
import { req } from '../test/utils'

export const cache = () =>
new Elysia({ name: 'cache' }).mapResponse(({ response }) => {
return new Response('hello world')
const app = new Elysia().group('inbox', (app) =>
app.ws('join', {
body: t.Object({
inboxId: t.String()
}),
message(ws, { inboxId }) {
ws.send(inboxId)
}
})
).listen(3000)

export default cache
// const response = await app.handle(req('/a')).then((x) => x.text())
// console.log(response)

const app = new Elysia()
.use(cache)
.get('/', () => 'A')
.listen(3000)
console.log(
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
)
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "elysia",
"description": "Ergonomic Framework for Human",
"version": "0.8.6",
"version": "0.8.7",
"author": {
"name": "saltyAom",
"url": "https://github.com/SaltyAom",
Expand Down
51 changes: 38 additions & 13 deletions src/compose.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ import {
NotFoundError,
ValidationError,
InternalServerError,
ERROR_CODE
ERROR_CODE,
ELYSIA_RESPONSE
} from './error'

import { CookieOptions, parseCookie } from './cookie'
Expand Down Expand Up @@ -1612,8 +1613,11 @@ export const composeGeneralHandler = (
`
}
return ${maybeAsync ? 'async' : ''} function map(request) {
`
return ${maybeAsync ? 'async' : ''} function map(request) {\n`

if(app.event.request.length)
fnLiteral += `let re`


const traceLiteral = app.event.trace.map((x) => x.toString())
const report = createReport({
Expand Down Expand Up @@ -1670,17 +1674,16 @@ export const composeGeneralHandler = (
name: app.event.request[i].name
})

const name = `re${i}`

if (withReturn) {
fnLiteral += `const ${name} = mapEarlyResponse(
fnLiteral += `re = mapEarlyResponse(
${maybeAsync ? 'await' : ''} onRequest[${i}](ctx),
ctx.set
)\n`

endUnit()

// fnLiteral += `if(${name}) return ${name}\n`
if(withReturn)
fnLiteral += `if(re !== undefined) return re\n`
} else {
fnLiteral += `${
maybeAsync ? 'await' : ''
Expand Down Expand Up @@ -1810,17 +1813,25 @@ export const composeErrorHandler = (
let fnLiteral = `const {
app: { event: { error: onError, onResponse: res } },
mapResponse,
ERROR_CODE
ERROR_CODE,
ELYSIA_RESPONSE
} = inject
return ${
app.event.error.find(isAsync) ? 'async' : ''
} function(context, error) {
let r
const { set } = context
context.code = error.code
context.error = error
`
if(error[ELYSIA_RESPONSE]) {
error.status = error[ELYSIA_RESPONSE]
error.message = error.response
}
`
for (let i = 0; i < app.event.error.length; i++) {
const handler = app.event.error[i]

Expand All @@ -1829,9 +1840,16 @@ export const composeErrorHandler = (
}onError[${i}](context)`

if (hasReturn(handler.toString()))
fnLiteral += `const r${i} = ${response}; if(r${i} !== undefined) {
fnLiteral += `r = ${response}; if(r !== undefined) {
if(r instanceof Response) return r
if(r[ELYSIA_RESPONSE]) {
error.status = error[ELYSIA_RESPONSE]
error.message = error.response
}
if(set.status === 200) set.status = error.status
return mapResponse(r${i}, set)
return mapResponse(r, set)
}\n`
else fnLiteral += response + '\n'
}
Expand All @@ -1843,7 +1861,13 @@ export const composeErrorHandler = (
{ headers: set.headers, status: set.status }
)
} else {
return new Response(error.message, { headers: set.headers, status: error.status ?? 500 })
if(error.code && typeof error.status === "number")
return new Response(
error.message,
{ headers: set.headers, status: error.status }
)
return mapResponse(error, set)
}
}`

Expand All @@ -1853,6 +1877,7 @@ export const composeErrorHandler = (
)({
app,
mapResponse,
ERROR_CODE
ERROR_CODE,
ELYSIA_RESPONSE
})
}
4 changes: 2 additions & 2 deletions src/cookie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { parse } from 'cookie'
import type { Context } from './context'

import { unsignCookie } from './utils'
import { isNumericString, unsignCookie } from './utils'
import { InvalidCookieSignature } from './error'

export interface CookieOptions {
Expand Down Expand Up @@ -431,7 +431,7 @@ export const parseCookie = async (
}

// @ts-ignore
if (!Number.isNaN(+value)) value = +value
if (isNumericString(value)) value = +value

This comment has been minimized.

Copy link
@7f8ddd

7f8ddd Jan 3, 2024

This is causing cookies that start with a number to return NaN.

// @ts-ignore
else if (value === 'true') value = true
// @ts-ignore
Expand Down
4 changes: 2 additions & 2 deletions src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ const env =
? process?.env
: undefined

export const ERROR_CODE = Symbol('ErrorCode')
export const ERROR_CODE = Symbol('ElysiaErrorCode')
export const ELYSIA_RESPONSE = Symbol('ElysiaResponse')

export const isProduction = (env?.NODE_ENV ?? env?.ENV) === 'production'

Expand All @@ -23,7 +24,6 @@ export type ElysiaErrors =
| ValidationError
| InvalidCookieSignature

export const ELYSIA_RESPONSE = Symbol('ElysiaResponse')

export const error = <
const Code extends number | keyof typeof StatusMap,
Expand Down
10 changes: 9 additions & 1 deletion src/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export const isNotEmpty = (obj: Object) => {

const handleFile = (response: File | Blob, set?: Context['set']) => {
const size = response.size

if (
(size &&
set &&
Expand All @@ -29,7 +30,13 @@ const handleFile = (response: File | Blob, set?: Context['set']) => {
set.status !== 416) ||
(!set && size)
) {
if (set)
if (set) {
if (set.headers instanceof Headers)
if (hasHeaderShorthand) set.headers = set.headers.toJSON()
else
for (const [key, value] of set.headers.entries())
if (key in set.headers) set.headers[key] = value

return new Response(response as Blob, {
status: set.status as number,
headers: Object.assign(
Expand All @@ -40,6 +47,7 @@ const handleFile = (response: File | Blob, set?: Context['set']) => {
set.headers
)
})
}

return new Response(response as Blob, {
headers: {
Expand Down
7 changes: 4 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ import {
asGlobal,
traceBackMacro,
replaceUrlPath,
primitiveHooks
primitiveHooks,
isNumericString
} from './utils'

import {
Expand All @@ -40,11 +41,11 @@ import {
import {
isProduction,
ERROR_CODE,
ELYSIA_RESPONSE,
ValidationError,
type ParseError,
type NotFoundError,
type InternalServerError,
ELYSIA_RESPONSE
} from './error'

import type {
Expand Down Expand Up @@ -3199,7 +3200,7 @@ export default class Elysia<
} catch {
// Not empty
}
else if (!Number.isNaN(+message)) message = +message
else if (isNumericString(message)) message = +message
}

if (transform?.length)
Expand Down
3 changes: 3 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -582,3 +582,6 @@ export const traceBackMacro = (
traceBackMacro(extension[key], value as any, hooks)
}
}

export const isNumericString = (message: string) =>
!Number.isNaN(parseInt(message))
19 changes: 19 additions & 0 deletions test/core/elysia.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,23 @@ describe('Edge Case', () => {
expect(await strict.handle(req('/a')).then((x) => x.status)).toBe(404)
expect(await strict.handle(req('/a/')).then((x) => x.status)).toBe(200)
})

it('return cookie with file', async () => {
const kyuukararin = Bun.file('test/kyuukurarin.mp4')

const app = new Elysia().get('/', ({ cookie: { name } }) => {
name.set({
value: 'Rikuhachima Aru',
maxAge: new Date().setFullYear(new Date().getFullYear() + 1),
httpOnly: true
})

return kyuukararin
})

const response = await app.handle(req('/')).then((x) => x.headers.toJSON())

expect(response['set-cookie']).toHaveLength(1)
expect(response['content-type']).toBe('video/mp4')
})
})
24 changes: 23 additions & 1 deletion test/core/handle-error.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Elysia, InternalServerError, NotFoundError, t } from '../../src'
import { Elysia, InternalServerError, NotFoundError, error, t } from '../../src'

import { describe, expect, it } from 'bun:test'
import { req } from '../utils'
Expand Down Expand Up @@ -146,4 +146,26 @@ describe('Handle Error', () => {
expect(await response.text()).toEqual('handled')
expect(response.status).toEqual(418)
})

it('handle thrown error function', async () => {
const app = new Elysia().get('/', () => {
throw error(404, 'Not Found :(')
})

const response = await app.handle(req('/'))

expect(await response.text()).toEqual('Not Found :(')
expect(response.status).toEqual(404)
})

it('handle thrown Response', async () => {
const app = new Elysia().get('/', () => {
throw error(404, 'Not Found :(')
})

const response = await app.handle(req('/'))

expect(await response.text()).toEqual('Not Found :(')
expect(response.status).toEqual(404)
})
})
16 changes: 16 additions & 0 deletions test/lifecycle/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,20 @@ describe('On Request', () => {

expect(res.headers.get('name')).toBe('llama')
})

it('early return', async () => {
const app = new Elysia()
.onRequest(({ set }) => {
set.status = 401
return 'Unauthorized'
})
.get('/', () => {
console.log("This shouldn't be run")
return "You shouldn't see this"
})

const res = await app.handle(req('/'))
expect(await res.text()).toBe('Unauthorized')
expect(res.status).toBe(401)
})
})
2 changes: 1 addition & 1 deletion test/units/map-response.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ describe('Map Response', () => {

const response = mapResponse(kyuukararin, {
...defaultContext,
status: 304,
status: 304
})

expect(response).toBeInstanceOf(Response)
Expand Down
Loading

0 comments on commit a6bf3d8

Please sign in to comment.