elysiajs / elysia Goto Github PK
View Code? Open in Web Editor NEWErgonomic Framework for Humans
Home Page: https://elysiajs.com
License: MIT License
Ergonomic Framework for Humans
Home Page: https://elysiajs.com
License: MIT License
adding this to track Node.js support for elysia as per our discussion on discord.
Hi,
I'm trying to use this in an Expo project. It works really good, the only odd thing are these errors when running tsc --noEmit --skipLibCheck
:
Any idea to fix this?
It's a monorepo with npm workspaces
which includes the bun-based backend app and the expo-based mobile app.
Hey!
This is a generic message asking you if you would like that this package should be mentioned in the future/new "Ecosystem" section inside the typebox repository.
Would be great if you (any maintainer) could simply drop a reponse in sinclairzx81/typebox#435.
Want it to be part of the documentation?
Yes -> Then please comment with the package name and a short description for it, for more info see the issue.
No -> Please simply comment "no thanks - packageNameHere"
Sorry for posting an "issue" for this, I hope it did not bother to much, feel free to close it!
I would really like to switch from Baojs to Elysia, but i need the websocket headers to authenticate the messages
On Elysia i cant get them:
Elysia-log:
"raw": ServerWebSocket {
"binaryType": "uint8array",
"close": [Function: close],
"cork": [Function: cork],
"data": {
"request": Request (0 KB) {
method: "GET",
url: "http://localhost:3005/search/proxy_search_wsp/1"
},
"store": {},
"set": {
"headers": {},
"status": 200
},
"publish": {
"name": "publish"
},
"query": -1,
"params": {
"wsp": "1"
},
"id": 1684826648522,
"message": undefined,
"transformMessage": []
},
"getBufferedAmount": [Function: getBufferedAmount],
"isSubscribed": [Function: isSubscribed],
"publish": [Function: publish],
"publishBinary": [Function: publishBinary],
"publishText": [Function: publishText],
"readyState": 1,
"remoteAddress": "127.0.0.1",
"send": [Function: send],
"sendBinary": [Function: sendBinary],
"sendText": [Function: sendText],
"subscribe": [Function: subscribe],
"unsubscribe": [Function: unsubscribe]
},
"data": {
"request": Request (0 KB) {
method: "GET",
url: "http://localhost:3005/search/proxy_search_wsp/1"
},
"store": {},
"set": {
"headers": {},
"status": 200
},
"publish": {
"name": "publish"
},
"query": -1,
"params": {
"wsp": "1"
},
"id": 1684826648522,
"message": undefined,
"transformMessage": []
},
"isSubscribed": [Function: isSubscribed],
"publish": [Function: publish],
"publishToSelf": [Function: publishToSelf],
"send": [Function: send],
"subscribe": [Function: subscribe],
"unsubscribe": [Function: unsubscribe],
"cork": [Function: cork],
"close": [Function: close]
} {
"term": "tt"
}
Would appreciate help!
Related to: #58
I tried to run elysia on wrangler(cloudflare workers), and I got this error.
The code here below
import { Elysia, t } from "elysia";
// import { swagger } from "@elysiajs/swagger";
const app = new Elysia()
// .use(swagger())
.get("/", () => "Hello Elysia")
.get("/id/:id", (context) => context.params.id)
.post(
"/post",
async (event) => {
const body = event.body;
return body;
},
{
body: t.Object({
username: t.String(),
password: t.String(),
}),
}
);
export default app;
package.json
{
"name": "hi-elysia",
"version": "1.0.44",
"scripts": {
"dev": "wrangler dev src/index.ts"
},
"devDependencies": {
"elysia": "0.6.0-alpha.2",
"superjson": "^1.13.1",
"tsx": "^3.12.7",
"wrangler": "^3.3.0"
},
"module": "src/index.js"
}
The error message
โ Starting local server...
service core:user:elysia-test: Uncaught ReferenceError: process is not defined
at index.js:7397:27
When sending an invalid web socket message i got this error
error: send requires a non-empty message
at message (/home/syler/github/socket-test/server/node_modules/elysia/dist/ws/index.js:1:1395)
CLOSE
OPEN
65 | let s = e.data.transformMessage[r](t);
66 | s !== void 0 && (t = s);
67 | }
68 | if (e.data.message?.Check(t) === !1)
69 |
70 | return void e.send(new r("message", e.data.message, t).cause);
The error is because .cause
is undefined
here, ValidationError
does not have a cause because at some point you changed the code from this to this, the fix is to change .cause
to .message
here
Any plans to support Remix with custom server adapter similar to @remix-run/express
?
i follow you tutorial this https://elysiajs.com/plugins/jwt.html
mycode :
.use(jwt({
name:"jwtBego",
secret:"myfist"
}))
.get("/masuk",async({jwt,cookie,setCookie,params})=>{
setCookie('auth', await jwt.sign(params), {
httpOnly: true,
maxAge: 7 * 86400,
})
return `Sign in as ${cookie.auth}`
})
but get error like this
SyntaxError: Import named 'getSchemaValidator' not found in module '/home/minto/belajar/elysyaPro/elyapp/manelysia/node_modules/elysia/build/es/index.js'.
[nodemon] app crashed - waiting for file changes before starting...
whats solution
elysia
is after fastify
, koa
and restify
.Hi, is there any plans to add a compression plugin (gzip/brotli) at some point? What's the recommended way of doing it right now, create our own plugin/middleware?
import { Elysia } from "elysia";
import { cors } from "@elysiajs/cors";
import { swagger } from "@elysiajs/swagger";
const app = new Elysia()
.use(swagger())
.use(cors())
.get("/", () => "Hello Elysia");
export default {
async fetch(req: Request) {
return await app.handle(req);
},
};
I tried to deploy this using wrangler, but it seems that the build contains some eval call.
Uncaught Error: EvalError: Code generation from strings disallowed for this
context
at index.js:5549:15 in composeHandler
at index.js:7173:407 in add
at index.js:7290:21 in get
at index.js:7533:8
at index.js:7283:18 in use
at index.js:7595:20
[code: 10021]
Is there any way to work around this?
I tried using elysia for the first time and followed the instructions as mentioned on the homepage
The code worked until i installed the swagger plugin and now it gets this syntax error inside the node_modules
itself.
My system is using windows 11 with WSL2 [Ubuntu 20.04.5 LTS (Focal Fossa)]
I want to render 1 html file, is that possible?
Structur folder like this:
-src
-views
- index.html
logic code:
const app = new Elysia()
.get("/myhtml",()=>{
WHATS THE LOGIC HERE..... AND IF USE Ejs , Handlebars, and other.....
})
For the following route:
app
.get('/qtest', ({query}) => {
return {
query
}
}, {
query: t.Object({
pageNum: t.Optional(t.Numeric({ default: 1 })),
pageSize: t.Optional(t.Numeric({ default: 10 })),
}),
})
curl localhost:5000/qtest
gives me Invalid query: 'pageNum'. Expected number
How do I supply query params which are optional
Is there a way to fire an event like with "onRequest", but with both the request and response objects? Basically, something like "onResponse".
I would like to log each response from the server. It would be nice for simple logging, something like: GET / 200 2ms
Hey there, thanks for your framework!
I understand that this can be a challenge, but I think it would be a great idea to add a feature that allows developers to import server's types from a remote server. This would make it much easier to access the necessary types, regardless of where the server is located.
For example, how Deno does it, Using a triple-slash directive:
/// <reference types="https://deno.land/x/[email protected]/types.d.ts" />
or Deno Friendly CDNs
import React from "https://cdn.skypack.dev/react?dts";
How Get Body Value
// server.ts
import { Elysia, t} from 'elysia'
import { swagger } from '@elysiajs/swagger'
const app = new Elysia()
.use(swagger())
.post("/add",async({body})=>{
const val = await body
console.log(val)
})
.listen(8080)
export type App = typeof app
console.log(`๐ฆ Elysia is running at ${app.server?.hostname}:${app.server?.port}`)
I tried writing a simple test for a simple elysia app that has only one get function. but it failed giving me unknown errors. I was unable to debug it because the error was referencing to a dist/index.js which is minified, so hard to read.
steps to recreate
-- first install and create new elysia application
bun create elysia test-elysia
cd elysia-test
bun install supertest @types/supertest vitest
// app.ts
import { Elysia } from "elysia";
const app = new Elysia().get("/", () => "Hello Elysia");
export default app;
// app.spec.ts
import { it, expect } from "vitest";
import supertest from "supertest";
import app from "./app";
it("should say Hello ", async () => {
const response = await supertest(app).get("/").expect(200);
expect(response.body).toMatchInlineSnapshot();
});
Expected: the test to run and pass
Got: error
ReferenceError: e is not defined
โฏ Module.composeHandler node_modules/elysia/dist/compose.js
:133:377
โฏ b._addHandler node_modules/elysia/dist/index.js:27:1707
โฏ b.get node_modules/elysia/dist/index.js:27:4604
โฏ src/app.ts:3:26
โฏ src/index.spec.ts:3:31
Test Files 1 failed (1)
Tests no tests
Start at 22:24:10
Duration 1.45s (transform 228ms, setup 1ms, collect 0ms,
tests 0ms, environment 0ms, prepare 185ms)
While trying to implement a logging library inspired by tracing crate from Rust ecosystem, I stumbled upon the decorate
, state
, and derive
methods. It's not immediately clear the call-time and the usage of the state
and derive
methods from their names. Below is my proposal to potentially improve the naming of those methods:
state
-> setStore
setStore
, it's immediately clear that the value is stored in store
property.derive
-> split into deecorateOnRequest
and setStoreOnRequest
derive
is not accurate because user does not always have to derive from the existing context, it also useful to set decoration or state that is unique for each request. For example, one of the main feature of the tracing
crate is to set a request-bound identifier to correlate logs that being emitted non-sequencially (asynchronous). derive
can be used for that purpose, set a decoration closure function called log that bound to a unique identifier. The split is to maintain consistency with setStore
and decorate
methods while also establish correlated meanings that setStore
and decorate
is assigned once on the server startup instead of called before each request.Hi, it seems like HMR is not working. Is this feature supposed to work? I expected so because the dev script includes --hot
.
How to reproduce:
bun create elysia elysia-playground
bun run dev
which will execute bun run --hot src/index.ts
$ bun run --hot src/index.ts
๐ฆ Elysia is running at 0.0.0.0:3000
Dir change: src/
Dir change: src
Dir change: src
Dir change: src
Dir change: src
bun version: 0.4.0
elysia-playground (master *) % bun pm ls
elysia-playground node_modules (2)
โโโ [email protected]
โโโ [email protected]
OS: Mac Ventura 13.0
Chrome Version 107.0.5304.87
any chance?
i followed the tutorial on this web https://elysiajs.com/plugins/static.html
and I also installed package @elysia/static and re-run . why get an error like this @elysiajs/static
root@minto-Lenovo-V145-14AST:/home/minto/belajar/elysyaPro/elyapp/manelysia# bun run dev
root@minto-Lenovo-V145-14AST:/home/minto/belajar/elysyaPro/elyapp/manelysia# bun run dev
$ bun run --hot src/index.ts
error: Could not resolve: "@elysia/static". Maybe you need to "bun install"?
import { staticPlugin } from '@elysia/static'
^
/home/minto/belajar/elysyaPro/elyapp/manelysia/src/index.ts:2:30 64error: script "dev" exited with code 1 (SIGHUP)
version
root@minto-Lenovo-V145-14AST:/home/minto/belajar/elysyaPro/elyapp/manelysia# bun --version
0.4.0
Hello, really like the framework btw :)
I was wondering if the params for the .group function can be typed so that I can abstract it in a class ?
I want to create a group wrapper class e.g.
interface Group {
getPrefix: () => string;
getGroup: () => ElysiaGroup;
}
so that I can do something like:
const group = new Group();
app.group(group.getPrefix(), group.getGroup());
would really appreciate this!!!
Thanks!
.group("users", app =>
app.get("/", ()=>{
return true
}
)
The above code will generate a 404 error when going to /users
. The trailing slash must be added to find the route. /users/
is required for the routing to be found.
This is also the situation regardless of the group.
If the path is
.get("/users", ()=>{})
going to /users/
also fails.
I think /users
should default to the "/users/"
route and vice versa.
I wonder if it would be possible to add version tags to the repository (for all versions, also for the patch versions), as thatb would make it easier to compare things when trying to help with the project.
I created a new Elysia app using bun create elysia elysia-app
, and when I go to add WebSocket support:
import { Elysia, ws } from "elysia";
const app = new Elysia()
.use(ws())
.ws('/ws', {
message(ws) {
console.log('New ws message!');
}
})
.listen(3000);
console.log(
`๐ฆ Elysia is running at ${app.server?.hostname}:${app.server?.port}`
);
I get the following error message that wraps from new Elysia()
to before .listen(3000)
:
TS2589: Type instantiation is excessively deep and possibly infinite.
The Elysia ecosystem includes a great collection of plugins (including websockets). It would be great if the team could add an official SSE plugin.
@sinclair/[email protected]
i get some typescript errors that i suspect are due to version sync.
I understand that rexporting feels convenient, but isn't that what peer deps are for?
server/src/index.ts
import { Elysia } from 'elysia'
import {swagger} from '@elysiajs/swagger'
import cors from '@elysiajs/cors'
export const app = new Elysia()
.get('/', () => 'Hello Elysia')
.get('/ping', () => 'pong pong')
.use(swagger())
.use(cors())
.listen(3005)
console.log(`๐ฆ Elysia is running at ${app.server?.hostname}:${app.server?.port}`)
export type ElysiaApp = typeof app
Note that the actual request is working just fine, just the typechecking is not working...
App logs correct response from server:
Client type when hovering:
const client: {
[x: string]: {
get: (params: {
$body: unknown;
} & {
$query?: Record<string, string | number | boolean> | undefined;
$fetch?: RequestInit | undefined;
}) => Promise<void>;
};
}
Link to the repo here: https://gitlab.com/Huynht/elysia-test/
Does the eden client only work in bun frontends?
EDIT: solved on discord, culprit was an outdated version of the swagger plugin
I typically use code first approach to building my graphql APIs. That would be things like https://github.com/hayes/pothos or https://nexusjs.org/
and for those I would prefer to plug them into elysia using just graphql-js. apollo-server and yoga have extra performance overhead I'd like to avoid.
I would like to report that I'm experiencing a type error after updating to version 0.3.2.
I have tested the packages @elysiajs/cookie
, @elysiajs/static
, and @elysiajs/swagger
.
import { cookie } from "@elysiajs/cookie";
import { staticPlugin } from "@elysiajs/static";
import { swagger } from "@elysiajs/swagger";
import { Elysia } from "elysia";
new Elysia()
.use(staticPlugin())
.use(cookie())
.use(swagger())
Each plugins has type error like this:
Argument of type 'Promise<(app: Elysia<ElysiaInstance<{ store: Record<string, unknown>; request: {}; schema: {}; meta: Record<unique symbol, {}> & Record<unique symbol, {}> & Record<unique symbol, {}>; }>>) => Elysia<...>>' is not assignable to parameter of type 'Promise<{ default: (elysia: Elysia<any>) => MaybePromise<Elysia<never>>; }> | MaybePromise<(app: Elysia<ElysiaInstance<{ store: Record<string, unknown>; request: {}; schema: {}; meta: Record<...> & ... 1 more ... & Record<...>; }>>) => MaybePromise<...>>'.
Type 'Promise<(app: Elysia<ElysiaInstance<{ store: Record<string, unknown>; request: {}; schema: {}; meta: Record<unique symbol, {}> & Record<unique symbol, {}> & Record<unique symbol, {}>; }>>) => Elysia<...>>' is not assignable to type 'Promise<{ default: (elysia: Elysia<any>) => MaybePromise<Elysia<never>>; }>'.
Type '(app: Elysia<ElysiaInstance<{ store: Record<string, unknown>; request: {}; schema: {}; meta: Record<unique symbol, {}> & Record<unique symbol, {}> & Record<unique symbol, {}>; }>>) => Elysia<...>' is not assignable to type '{ default: (elysia: Elysia<any>) => MaybePromise<Elysia<never>>; }'.
Additionally, I have encountered a runtime issue with @elysiajs/swagger
.
31 | const typebox_1 = require("../typebox");
32 | const index_1 = require("../custom/index");
33 | const index_2 = require("../format/index");
34 | class TypeSystemDuplicateTypeKind extends Error {
35 | constructor(kind) {
36 | super(`Duplicate kind '${kind}' detected`);
^
error: Duplicate kind 'File' detected
at new TypeSystemDuplicateTypeKind (/node_modules/@sinclair/typebox/system/system.js:36:8)
at CreateType (/node_modules/@sinclair/typebox/system/system.js:56:18)
at /node_modules/elysia/dist/custom-types.js:1:1031
at /node_modules/elysia/dist/index.js:1:9516
For your reference, the tested package versions are as follows:
elysia: 0.3.2
@elysiajs/cookie: 0.3.0
@elysiajs/static: 0.3.2
@elysiajs/swagger: 0.3.0
When using groups, you can't use the ws() method on the app as inside the group, "app" is a fresh instance of Elysia. So to define a websocket endpoint inside of a group, you have to add the plugin once more to the group instance.
This does not work:
import { Elysia, ws } from "elysia";
const app = new Elysia()
.use(ws())
.get("/", () => "Welcome to Elysia!")
.group("/group", (app) => app.ws("/websocket", {})
.listen(3000);
This works:
import { Elysia, ws } from "elysia";
const app = new Elysia()
.use(ws())
.get("/", () => "Welcome to Elysia!")
.group("/group", (app) => app.use(ws()).ws("/websocket", {})
.listen(3000);
Is this intended as such? If yes, I would try to clarify that in the docs.
As the title says set.headers removes all the headers set by the @elysiajs/cors
plugin.
Using the cors plugin causes Elysia not to properly set content-type to "application/json" when an object is returned from a handler. After looking into it a bit it seems like Elysia is currently not setting the content-type if any headers are present. It might make more sense if content-type is always set unless a content-type header is present. I believe this is controlled by handlers.ts mapEarlyResponse
and handlers.ts mapResponse
. I'd be interested in working on this if desired.
I'm sorry lmao, I don't know how to describe it properly (that's why the title might be confusing asf), but:
My code has an POST
endpoint which listens on /api/profile/:username
. Previously, there was also an DELETE
endpoint on /api/profile/:username/modules
. I've removed that one though, as I've implemented another route for that. There also exists an DELETE
endpoint for /api/profile/:username
.
The thing is, when (still) trying to use DELETE
on /api/profile/:username/modules
, even though it's not implemented anymore, it'll straight up use DELETE
on /api/profile/:username
(but it also remove the /modules
at the end, so it's really using the supplied username).
I don't think this should happen. It should rather display a 404 because well, /api/profile/:username/modules
doesn't exist anymore.
How did I find out about this? Maaayyybee.. Just maaayyybe, I've accidently deleted accounts within my project without knowing until now ๐ฅฒ
If you need PoC code, lmk!
Regards,
~ Northernside
I'd like to have the ability to check for certain cookies before allowing a WebSocket connection, as well as have access to the Elysia context. Here's some demo code:
import { Elysia, ws } from 'elysia'
import cookie from '@elysiajs/cookie';
new Elysia()
.use(cookie())
.use(ws())
.state('count', 0)
.ws('/ws', {
beforeHandle({ cookie, store }) {
if (!cookie['authToken']) return new Response(null, { status: 401 });
console.log(store.count);
}
})
.listen(8080)
When I run tsc
, I get these errors for cookie
in the params and store.count
:
index.ts:9:18 - error TS2339: Property 'cookie' does not exist on type '{ request: Request; headers: Record<string, string | null>; query: Record<string, unknown>; params: Record<never, string>; body: unknown; store: {}; set: { headers: Record<...>; status?: number | undefined; redirect?: string | undefined; }; } & Record<...>'.
9 beforeHandle({ cookie, store }) {
~~~~~~
index.ts:12:22 - error TS2339: Property 'count' does not exist on type '{}'.
12 console.log(store.count);
~~~~~
Found 2 errors in the same file, starting at: index.ts:9
Ideally, I should be able to access anything available on the context in these WebSocket handlers as I would in regular HTTP endpoints.
I'm currently using Bun 0.6.8
, and bun pm ls
outputs
โโโ @elysiajs/[email protected]
โโโ [email protected]
โโโ [email protected]
โโโ [email protected]
EDIT: This might not be relevant for right now, but I'd like to see the notion of a derive in the context of WebSockets, e.g. some way to add data to the "ws" objects passed into open / message / close. This'd be real handy if I wanted to attach certain data, such as user IDs.
I created a project using bun create elysia hi-elysia
Whenever I try to run bun with bun run --hot src/index.ts
I receive the following error:
SyntaxError: Import named 'TypeCompiler' not found in module '/.../node_modules/@sinclair/typebox/compiler/index.js'.
If I omit the --hot or --watch option the server starts normally.
Thanks for any help in advance!
Group index routes don't work with trailing slashes.
/group
and /group/
should give the same result.
Suppose you have a group /g
and within that group you had /
. I would expect either /g
or /g/
to hit the same route. Currently the route is only accessible at /g
and /g/
returns 404. This also breaks Eden since it always seems to add the trailing slash. Here's a Code Sandbox demonstrating the issue. This can be seen by navigating to /g
and then to /g/
.
Hi,
I recently got into bun and was looking for a nice webframework which supports filesystem based routing. I like it because it - by design - enforces a clear structure for the project and you know where to find a certain route. Elysia does a few other things really really well in my opinion so I thought about using it but as far as I see it does not support fs based routes. Is this a thing you considered? Maybe also in a hybrid approach like I did here: https://github.com/m1212e/bun-fs-router-plugin
Hello,
I have been looking at the framework, and I congratulate you.
I don't know much about programming. I am recently learning. I use Laravel and have been learning alpine.js
So my question is:
Can I use alpine.js without having to use pure JavaScript or typescript?
with Zod you can have the static type inference and a validator at the same time (https://zod.dev/)
Continue from saltyaom/kingworld#15
import { KingWorld } from 'kingworld'; new KingWorld() .get('/', () => 'Hi') .get('/error', () => { throw new Error('test') }) .onError(error => { console.log(error.name === 'test'); }) .listen(8080)If you start the app and visit http://localhost:8080/error should only see "false" in the logs, instead I see this.
โ bun-test git:(main) โ bun run ./src/index.ts [0.09ms] ".env" false 1 | import { KingWorld } from 'kingworld'; 2 | 3 | new KingWorld() 4 | .get('/', () => 'Hi') 5 | .get('/error', () => { 6 | throw new Error('test') ^ error: test at /Users/xo/code/bun-test/src/index.ts:6:14 at /Users/xo/code/bun-test/node_modules/kingworld/build/es/index.js:285:24 at handle (/Users/xo/code/bun-test/node_modules/kingworld/build/es/index.js:220:17)
I understand that the all error log is annoying, tbh I also looking for a way to disable error logging.
From what I found, if an Error is thrown in the async function in Bun, it will always log an error, the bug is now reported and pending on Bun.
Please keep this issue until oven-sh/bun#1435 is fixed, to see if the issue still occurs.
Continue from saltyaom/kingworld#14
Currently this returns 200 HM as there seems to be a bug in bun. Tracking in https://discord.com/channels/876711213126520882/1044751397993840770/1044751397993840770
return new Response(JSON.stringify({
field: 'value'
}), {
status: 200,
statusText: 'test'
});
Probably blocking until Bun 0.3.0 released
When trying to bundle elysia using bun build --target bun
it fails to bundle because it cannot resolve @elysiajs/fn
, the error is error: Could not resolve: "@elysiajs/fn". Maybe you need to "bun install"?
.
After explicitly installing the package it bundles properly, the only thing that is needed to reproduce the error is to import elysia and try to bundle.
import { Elysia } from "elysia";
Continue from saltyaom/kingworld#12
I was hoping something like this could be added?
import KingWorld from 'kingworld' const server = new KingWorld() .get('/', () => 'Hello KingWorld') .listen(0) console.log('๐ฆ KINGWORLD is running at :%s', server.port)This would also help in this case.
import KingWorld from 'kingworld' const server = new KingWorld() .get('/', () => 'Hello KingWorld') .listen(process.env.PORT ?? 0) console.log('๐ฆ KINGWORLD is running at :%s', server.port)
Also, I believe I didn't write this down on documentation yet, but to access the port you can either:
access .server property which is instance of Bun.server to access port and hostname.
callback function as 2nd parameter on .listen like express/fastify
So basically:const app = new KingWorld() // listen can accept 2nd parameter callback for accessing `Bun.serve` .listen(process.env.PORT ?? 8080, ({ hostname, port }) => { console.log( `๐ฆ KingWorld running at http://${hostname}:${port}` ) }) // Or access it via `.server`, both are the same, as `.listen` is sync. console.log( `๐ฆ KingWorld running at http://${app.server?.hostname}:${app.server?.port}` )
Perfect, that fixes being able to pass in process.env.PORT. ๐
Still have 2 issues in regards to ports though.
It doesn't allow port 0. This is used when wanting a random port to be assigned.
Unix socket paths aren't allowed (I don't think bun has support for them yet though).Looks like the port 0 issue is related to bun itself not this lib oven-sh/bun#1544.
I tried to run the following code with the group.
new Elysia()
.group("/", app =>
app.get('/', () => "", {
schema: {
response: {
200: t.String(),
400: t.String()
}
}
})
).listen(8080);
And, the following error occurs on the server.
u?.response?.Check is not a function. (In 'u?.response?.Check(d)', 'u?.response?.Check' is undefined)
My elysia version is 0.3.1
Is there a way to do validation with the Elysia Typebuilder? similar to zod.parse, where it would return true or false, or throw an error message. I would like to use the schemas I declared in Elysia also outside of body parsing, inside my application code.
At the moment it is not possible to import CommonJS into ESM because the exports defined in package.json
(of all projects) are sorted incorrectly.
Example: (run with node main.js
)
// main.js
import Elysia from 'elysia';
new Elysia.Elysia();
Error: (yes, i've "type": "module"
in my package.json
)
SyntaxError: Cannot use import statement outside a module
The sorting is important. Node.js
& Deno
apparently check from top to bottom. This means that if it is ESM-context, import
is used instead of require
or node
.
Therefore node
must move further up and point to CommonJS (in all exports
):
{
"bun": "./dist/index.js",
+ "node": "./dist/cjs/index.js"
"require": "./dist/cjs/index.js",
"import": "./dist/index.js",
"default": "./dist/index.js",
- "node": "./dist/index.js"
}
Furthermore, type or runtime errors occur when CommonJS is imported into ESM, because SWC
breaks named exports for ESM in CommonJS build (i.e. module.exports
):
โ SWC
(function (e, t) {
for (var r in t) Object.defineProperty(e, r, { enumerable: !0, get: t[r] });
})(exports, {
Elysia: function () {
return h;
},
default: function () {
return u;
}
});
Runtime Error
import { Elysia } from 'elysia';
^^^^^^
SyntaxError: Named export 'Elysia' not found. The requested module 'elysia' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from 'elysia';
const { Elysia } = pkg;
OR Type error
import Elysia from 'elysia';
const app = new Elysia.Elysia() // Property 'Elysia' does not exist on type 'typeof Elysia'.ts(2339)
โ TSC (without SWC)
exports.Elysia = Elysia;
exports.default = Elysia;
I can make (or help you with) the changes to exports
in all package.json
, but I don't know how you wanna handle SWC
.
An alternative would be to drop CommonJS and only support ESM โ "moduleResolution": "nodenext"
& "type": "module"
(i.e. specify all imports and exports with .js
extension). This would work for Node.js
and Deno
too.
This issue should be reported to Discord server
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.