Coder Social home page Coder Social logo

elysia's People

Contributors

aaditeynair avatar aleclarson avatar amirrezamahyari avatar anujjoshi63 avatar archerhume avatar arthurfiorette avatar bogeychan avatar brunoeduardodev avatar cdfzo avatar cheersmas avatar dependabot[bot] avatar dungps avatar gaurishhs avatar hansaskov avatar hisamafahri avatar inplex-sys avatar itohatweb avatar itpcc avatar kilianb avatar kitanga avatar mkassabov avatar ntzrbtr avatar paperdave avatar print-varunsharma avatar ricardo-devis-agullo avatar saketverma-03 avatar saltyaom avatar silvio2402 avatar spicyzboss avatar yamcodes avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

elysia's Issues

WebSocket beforeHandle unable to access use'd plugins / state / derive's

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.

Expo Types Issue

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:

CleanShot 2023-03-29 at 18 53 27

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.

Elysia WebSocket API TypeScript Error: "Type instantiation is excessively deep and possibly infinite"

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.

Static File Not work

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

Allow use of dynamic ports?

Continue from saltyaom/kingworld#12

Question

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)

Answer:

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}`
)

Pending:

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.

Type definition for .group params

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!

using JWT get Error : Import named 'getSchemaValidator' not found in module

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

Parameters as last object in the slug causes following "unwanted/unexpected" slugs to be ignored and still used for the intended one

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

Version tags in the repository?

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.

Support compression

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?

Support for Alpine.js

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?

get "EvalError: Code generation from strings disallowed for this context" when deploying to cloudflare worker

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?

Websocket definition in groups

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.

service core:user:elysia-test: Uncaught ReferenceError: process is not defined at index.js:7397:27

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

Filesystem based routing?

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

Group "/" and "" routes are separate and should be the same

.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.

Proposal: Rename and split some methods to better represent their intended usage

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
    By renaming it to 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.

error always log

Continue from saltyaom/kingworld#15

Question

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)

Answer

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.

Elysia fails to bundle without explicitly installing `@elysiajs/fn`

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";

Not getting Headers from Websocket implementation

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!

Improve ESM support through CommonJS

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.

Import named 'TypeCompiler' not found

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!

HMR not working

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:

  1. Create a new Elysia project: bun create elysia elysia-playground
  2. Start the dev server with --hot: bun run dev which will execute bun run --hot src/index.ts
  3. Change something in the code, i.e. Hello Elysia to Hello in src/index.ts
  4. It seems like the change is noticed as the console output states but there is no page refresh and manual triggered page refresh still only shows Hello Elysia
$ 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

How to get Value Input Body Request

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}`)

[Feature Request] Getting server types from remote server

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";

Mention in Typebox Readme.md under "Ecosystem"

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!

multiple status response does not work with the group

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

Groups routes don't work with trailing slash.

Group index routes don't work with trailing slashes.

Expectation

/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/.

https://codesandbox.io/p/sandbox/loving-swartz-ugxbrq

OnResponse

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

Autocomplete and typechecking for eden client not working in vite-react-ts setup

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

client/src/mainl.tsx
image

Note that the actual request is working just fine, just the typechecking is not working...

App logs correct response from server:
image

Suggestions not working:
image

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

Plugin type error after updating Elysia version

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

Elysia fails when testing with vitest and supertest

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;
  • and the test
// 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)

Elysia throws error if `Headers#toJSON` doesn't exist

Output

image

Code

Is this check / fallback still required?

elysia/src/compose.ts

Lines 211 to 219 in 08a4375

fnLiteral += _demoHeaders.toJSON
? `c.headers = c.request.headers.toJSON()\n`
: `c.headers = {}
for (const key of c.request.headers.keys())
h[key] = c.request.headers.get(key)
if (headers.Check(c.headers) === false)
${composeValidation('headers')}
`

[bug] WebSocket validation error does not work correctly

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

Validation with Elysia Typebuilder

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.

Optional query params

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

Cors plugin breaks content-type mapping.

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.