Skip to content

Commit

Permalink
🧹 chore: bug fix
Browse files Browse the repository at this point in the history
  • Loading branch information
SaltyAom committed Dec 21, 2023
1 parent 53cabf8 commit 2d11f85
Show file tree
Hide file tree
Showing 12 changed files with 177 additions and 75 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ Change:
Bug fix:
- remove `headers`, `path` from `PreContext`
- remove `derive` from `PreContext`
- Custom type doesn't output custom `error`

# 0.7.31 - 9 Dec 2023
Improvement:
Expand Down
44 changes: 26 additions & 18 deletions example/a.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,32 @@
import { Elysia, t } from '../src'
import { req } from '../test/utils'

import { Type } from '@sinclair/typebox'
import { TypeCompiler } from '@sinclair/typebox/compiler'

const app = new Elysia()
.macro(({ onBeforeHandle }) => {
return {
hi(a: boolean) {
onBeforeHandle(() => {
console.log('A')
})
}
}
.get('/play', () => {

}, {
query: t.Partial(
t.Object({
username: t.String(),
firstName: t.String(),
lastName: t.String(),
email: t.String({
format: 'email',
default: ''
}),
phone: t.String()
})
)
})
.get(
'/',
() => {
return 'b'
},
{
hi: true
}
)
.listen(3000)

// const b = await app.handle(
// new Request('http://localhost/endpoint', {
// method: 'GET'
// })
// )

const res = await app.handle(req('/')).then((r) => r.text())
// console.log(await b.text())
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.0-rc.4",
"version": "0.8.0-rc.6",
"author": {
"name": "saltyAom",
"url": "https://github.com/SaltyAom",
Expand Down
33 changes: 17 additions & 16 deletions src/compose.ts
Original file line number Diff line number Diff line change
Expand Up @@ -738,11 +738,9 @@ export const composeHandler = ({
(name, index) => `
memory = url.indexOf('${name}=')
const a${index} = memory === -1 ? undefined : url.slice(memory + ${
const a${index} = memory === -1 ? undefined : url.slice(memory = memory + ${
name.length + 1
}, (memory = url.indexOf('&', memory + ${
name.length + 1
})) === -1 ? undefined : memory)`
}, (memory = url.indexOf('&', memory)) === -1 ? undefined : memory)`
)
.join('\n')}
Expand Down Expand Up @@ -1020,11 +1018,12 @@ export const composeHandler = ({
{}
) as Object
)) {
fnLiteral += `c.headers['${key}'] ??= ${
typeof value === 'object'
const parsed = typeof value === 'object'
? JSON.stringify(value)
: value
}\n`
: `'${value}'`

if(parsed)
fnLiteral += `c.headers['${key}'] ??= ${parsed}\n`
}

fnLiteral += `if(headers.Check(c.headers) === false) {
Expand All @@ -1046,11 +1045,12 @@ export const composeHandler = ({
{}
) as Object
)) {
fnLiteral += `c.params['${key}'] ??= ${
typeof value === 'object'
const parsed = typeof value === 'object'
? JSON.stringify(value)
: value
}\n`
: `'${value}'`

if(parsed)
fnLiteral += `c.params['${key}'] ??= ${parsed}\n`
}

fnLiteral += `if(params.Check(c.params) === false) {
Expand All @@ -1072,11 +1072,12 @@ export const composeHandler = ({
{}
) as Object
)) {
fnLiteral += `c.query['${key}'] ??= ${
typeof value === 'object'
const parsed = typeof value === 'object'
? JSON.stringify(value)
: value
}\n`
: `'${value}'`

if(parsed)
fnLiteral += `c.query['${key}'] ??= ${parsed}\n`
}

fnLiteral += `if(query.Check(c.query) === false) {
Expand Down
98 changes: 85 additions & 13 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1867,7 +1867,26 @@ export default class Elysia<
seed: plugin.config.seed,
checksum: current,
stack: plugin.stack,
dependencies: plugin.dependencies
dependencies: plugin.dependencies,
routes: plugin.routes,
decorators: plugin.decorators,
store: plugin.store,
type: plugin.definitions.type,
error: plugin.definitions.error,
derive: plugin.event.transform
// @ts-expect-error
.filter((x) => (x.$elysia = 'derive'))
.map((x) => ({
fn: x.toString(),
stack: new Error().stack ?? ''
})),
resolve: plugin.event.transform
// @ts-expect-error
.filter((x) => (x.$elysia = 'derive'))
.map((x) => ({
fn: x.toString(),
stack: new Error().stack ?? ''
}))
})
}

Expand Down Expand Up @@ -1951,7 +1970,26 @@ export default class Elysia<
seed: plugin.config.seed,
checksum: current,
stack: plugin.stack,
dependencies: plugin.dependencies
dependencies: plugin.dependencies,
routes: plugin.routes,
decorators: plugin.decorators,
store: plugin.store,
type: plugin.definitions.type,
error: plugin.definitions.error,
derive: plugin.event.transform
// @ts-expect-error
.filter((x) => (x.$elysia = 'derive'))
.map((x) => ({
fn: x.toString(),
stack: new Error().stack ?? ''
})),
resolve: plugin.event.transform
// @ts-expect-error
.filter((x) => (x.$elysia = 'derive'))
.map((x) => ({
fn: x.toString(),
stack: new Error().stack ?? ''
}))
})
this.event = mergeLifeCycle(
this.event,
Expand Down Expand Up @@ -1986,18 +2024,41 @@ export default class Elysia<
return this as any
}

mount(handle: (request: Request) => MaybePromise<Response>): this
mount(
handle:
| ((request: Request) => MaybePromise<Response>)
| Elysia<any, any, any, any, any, any, any>
): this
mount(
path: string,
handle: (request: Request) => MaybePromise<Response>
handle:
| ((request: Request) => MaybePromise<Response>)
| Elysia<any, any, any, any, any, any, any>
): this

mount(
path: string | ((request: Request) => MaybePromise<Response>),
handle?: (request: Request) => MaybePromise<Response>
path:
| string
| ((request: Request) => MaybePromise<Response>)
| Elysia<any, any, any, any, any, any, any>,
handle?:
| ((request: Request) => MaybePromise<Response>)
| Elysia<any, any, any, any, any, any, any>
) {
if (typeof path === 'function' || path.length === 0 || path === '/') {
const run = typeof path === 'function' ? path : handle!
if (
path instanceof Elysia ||
typeof path === 'function' ||
path.length === 0 ||
path === '/'
) {
const run =
typeof path === 'function'
? path
: path instanceof Elysia
? path.compile().fetch
: handle instanceof Elysia
? handle.compile().fetch
: handle!

const handler: Handler<any, any> = async ({ request, path }) =>
run(
Expand Down Expand Up @@ -2026,8 +2087,11 @@ export default class Elysia<
}

const length = path.length

if (handle instanceof Elysia) handle = handle.compile().fetch

const handler: Handler<any, any> = async ({ request, path }) =>
handle!(
(handle as Function)!(
new Request(
replaceUrlPath(request.url, path.slice(length) || '/'),
request
Expand All @@ -2041,6 +2105,7 @@ export default class Elysia<
type: 'none'
} as any
)

this.all(
path + (path.endsWith('/') ? '*' : '/*'),
handler as any,
Expand Down Expand Up @@ -3839,14 +3904,20 @@ export default class Elysia<
handle = async (request: Request) => this.fetch(request)

/**
* Handle can be either sync or async to save performance.
* Use handle can be either sync or async to save performance.
*
* Beside benchmark purpose, please use 'handle' instead.
*/
fetch = (request: Request): MaybePromise<Response> =>
(this.fetch = this.config.aot
fetch = (request: Request): MaybePromise<Response> => {
if(process.env.NODE_ENV === "production")
console.warn(
"Performance degradation found. Please call Elysia.compile() before using 'fetch'"
)

return (this.fetch = this.config.aot
? composeGeneralHandler(this)
: createDynamicHandler(this))(request)
}

private handleError = async (
context: Context,
Expand Down Expand Up @@ -4072,7 +4143,8 @@ export type {
TraceHandler,
TraceProcess,
TraceReporter,
TraceStream
TraceStream,
Checksum
} from './types'

export type { Static, TSchema } from '@sinclair/typebox'
6 changes: 2 additions & 4 deletions src/type-system.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,9 +197,7 @@ export const ElysiaType = {
}),
t.Number(property)
],
{
default: property?.default
}
property
)
)
.Decode((value) => {
Expand All @@ -225,7 +223,7 @@ export const ElysiaType = {
default: ''
}),
t.Object(properties, options)
])
], options)
)
.Decode((value) => {
if (typeof value === 'string')
Expand Down
22 changes: 22 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -726,7 +726,20 @@ export type Checksum = {
seed?: unknown
checksum: number
stack?: string
routes: InternalRoute[]
decorators: DecoratorBase['request']
store: DecoratorBase['store']
type: DefinitionBase['type']
error: DefinitionBase['error']
dependencies?: Record<string, Checksum[]>
derive: {
fn: string
stack: string
}[]
resolve: {
fn: string
stack: string
}[]
}

// @ts-ignore
Expand Down Expand Up @@ -795,3 +808,12 @@ export interface MacroManager<
local: Prettify<LifeCycleStore & RouteSchema>
}
}

// Route extends RouteSchema = {},
// Decorators extends DecoratorBase = {
// request: {}
// store: {}
// derive: {}
// resolve: {}
// },
// Path extends string = ''
8 changes: 4 additions & 4 deletions test/validator/body.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ describe('Body Validator', () => {
})
)

expect(await res.json()).toEqual({
expect(await res.json<any>()).toEqual({
name: 'sucrose',
job: 'alchemist',
trait: 'dog'
Expand Down Expand Up @@ -78,7 +78,7 @@ describe('Body Validator', () => {
})
)

expect(await res.json()).toEqual({
expect(await res.json<any>()).toEqual({
name: 'sucrose',
job: 'alchemist'
})
Expand All @@ -102,7 +102,7 @@ describe('Body Validator', () => {
})
)

expect(await res.json()).toEqual({
expect(await res.json<any>()).toEqual({
name: 'sucrose',
job: 'alchemist',
age: 16
Expand All @@ -129,7 +129,7 @@ describe('Body Validator', () => {
})
)

expect(await res.json()).toEqual({
expect(await res.json<any>()).toEqual({
name: 'sucrose',
job: 'alchemist',
age: 16,
Expand Down
Loading

0 comments on commit 2d11f85

Please sign in to comment.