Coder Social home page Coder Social logo

documentation's Issues

Elysia doesn't parse html body content for GET requests

What is the type of issue?

Documentation is incorrect, Documentation is confusing, Example code is not working

What is the issue?

Using the example code found at https://elysiajs.com/patterns/mvc.html#service:

import { Elysia, t } from "elysia";

abstract class Service {
  static fibo(number: number): number {
    if (number < 2) return number;

    return Service.fibo(number - 1) + Service.fibo(number - 2);
  }
}

const app = new Elysia()
  .get(
    "/fibo",
    ({ body }) => {
      console.log(body);
      return Service.fibo(body);
    },
    {
      body: t.Numeric(),
    }
  )
  .listen(3000);

And running with postman:
Screenshot 2024-06-03 at 7 42 20 PM

I get a validation error:

{
  "type": "validation",
  "on": "body",
  "property": "root",
  "message": "Expected union value",
  "expected": 0,
  "errors": [
    {
      "type": 62,
      "schema": {
        "anyOf": [
          {
            "format": "numeric",
            "default": 0,
            "type": "string"
          },
          {
            "type": "number"
          }
        ]
      },
      "path": "",
      "message": "Expected union value"
    }
  ]
}

Removing the validation check I log out undefined when printing: console.log(body); as well as get a {"name":"RangeError","message":"Maximum call stack size exceeded."} response.

I assume according to best practices you shouldn't send HTTP body with GET requests. Do the docs need to be updated with .post(...) or is there a way to allow Elysia to parse GET body content?

Related Issue: #313

Where did you find it?

https://elysiajs.com/patterns/mvc#service

with Cloudflare Workers

What is the type of issue?

Documentation is missing

What is the issue?

If I'm not mistaken, the documentation doesn't say how to use it with Cloudflare Workers.

It took me a while to realize that I had to set aot to false when using it with Cloudlfare Workers.

I hope this helps others.

Where did you find it?

No response

Add date on blogs

Please display the date of creation on the blog list and entries so we can appreciate if they're new or old.

[Quick Start]: Is it necessary to set up a bun build script?

What is the type of issue?

Documentation is confusing, Example code is not working

What is the issue?

Hello,

While reading the “Quick Start” document, I noticed that the "build" command is defined in the “Manual Installation” chapter.

{
  "scripts": {
    "dev": "bun --watch src/index.ts",
    "build": "bun build src/index.ts",
    "start": "NODE_ENV=production bun src/index.ts",
    "test": "bun test"
  }
}

However, when running the command in bun 1.1.10, the transpiled JavaScript source code is output to the standard output.

While using the --outdir flag allows exporting js files, it raises the question of whether these JS files are actually necessary.

Isn’t bun build intended for frontend solutions like React?

Running js files instead of ts files in production doesn’t seem to provide any benefits.

Therefore, to avoid confusion, how about removing the build script from the documentation?

Thank you.

Where did you find it?

https://elysiajs.com/quick-start.html#manual-installation

Grammar mistakes.

Hi, I noticed grammar mistakes when reading documentation section about Handler. Some sentences do not necessarily have mistakes, but are not clear to understand.
Examples:

  • However, if you prefers an explicity Response class... should be changed to: However, if you prefer an explicity Response class....
  • Helping you can focus on business logic rather than boilerplate code should be changed to: Helping you focus on business logic rather than boilerplate code
  • Context provide several property to help you get information about the request should be changed to: Context provides several properties to help you get information about the request.

Do you think I could take care of it as my first contribution to this project?

Inconsistency in Documentation Regarding Accessing Header from headers Context

What is the type of issue?

No response

What is the issue?

new Elysia()
    .derive(({ headers }) => {
        const auth = headers['Authorization']
        ....

Headers are case insensetive while accessing directly from request. request.headers.get('Authorization') and request.headers.get('AUTHorization') gives the result. But with the headers context and accessing the Header with bracket notation, the case matters. In the headers context, all the headers are saved on lower case. thus we need to use headers['authorization'] and same for other and custom headers.

We need to fix the snippet, and need to mention about it on the Documentation as well.

Where did you find it?

While going from top in the documentation.

Encountered on Essential -> Context -> Derive.

import { Elysia } from 'elysia'

new Elysia()
    .derive(({ headers }) => {
        const auth = headers['Authorization']
       // HERE
       // const auth = headers['authorization']

        return {
            bearer: auth?.startsWith('Bearer ') ? auth.slice(7) : null
        }
    })
    .get('/', ({ bearer }) => bearer)

Typo in "Guard" example

What is the type of issue?

Example code is not working

What is the issue?

See elysiajs/elysia#528

The example under "Guard" seems to have a typo. The GET request has a body. According to MDN, this is not a good idea. The author of the discussion I referenced, couldn't even get the example to run.

app
    .get('/user/:id', ({ body }) => signUp(body))
    .post('/profile', ({ body }) => signIn(body), {
        beforeHandle: isUserExists
    })

Where did you find it?

https://elysiajs.com/life-cycle/before-handle#guard

Arabic translate

It is really great project, I fall in and want translate it to Arabic. Friday I will start, so if you have considerations or ideas put it here

package.json automatically generated does not match manual installation section

What is the type of issue?

Documentation is incorrect

What is the issue?

This is the scripts section in package.json when generated using bun create elysia app

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "dev": "bun run --watch src/index.ts"
}

This is what's currently what's written in manual installation section:

"scripts": {
  "dev": "bun --watch src/index.ts",
  "build": "bun build src/index.ts",
  "start": "NODE_ENV=production bun src/index.ts",
  "test": "bun test"
}

Suggested changes:

  • In the automatically generated Elysia template, it should be including the "build" and "start" commands for convenience
  • In the manual installation section in docs, the "test" script should be removed because that's redundant. bun test does its thing by default

Where did you find it?

https://elysiajs.com/quick-start.html

Several documentation pages seems gone

I've bookmarked some of Elysia documentation pages a while back (couldn't remember how long it was), and when I tried to visit them today, it seems some of them become unavailable (404), is this intentional?

Some of the pages that I know is unavailable are:

https://elysiajs.com/patterns/dependency-injection.html
https://elysiajs.com/patterns/reference-models.html
https://elysiajs.com/patterns/creating-documentation.html
https://elysiajs.com/patterns/testing.html

Some if not all of it can be viewed through web archive, and still visible on the search engine results, but obviously when clicked it will lead to 404 page

Property 'html' does not exist on type 'Context<{ body: unknown; params: Record<never, string>; query: undefined; headers: undefined; response: unknown; }, {}> & {}'

a simple app following the documentation instructions. but still get err

index.tsx

import Elysia from "elysia";
import { html } from "@elysiajs/html";
import * as tHTML from "typed-html";
import staticPlugin from "@elysiajs/static";
import Home from "./components/Home";
import { About } from "./components/About";

new Elysia()
    .use(html())
    .use(staticPlugin())
    .get("/", ({ html }) =>
        html(
            <BaseHTML>
                <Home />
            </BaseHTML>
        )
    )
    .get("/about", ({ headers, html }) => {
        if (headers?.[`hx-request`]) {
            return <About />;
        }
        return html(
            <BaseHTML>
                <About />
            </BaseHTML>
        );
    })
    .listen(3000, ({ hostname, port }) =>
        console.log(`🦊 running on http://${hostname}:${port}`)
    );

const BaseHTML = ({ children }: tHTML.Children) => {
    return (
        <html lang="en">
            <head>
                <meta charset="UTF-8" />
                <meta
                    name="viewport"
                    content="width=device-width, initial-scale=1.0"
                />
                <title>FireBEH</title>
                <link rel="stylesheet" href="public/style.css" />
                <script src="public/htmx.min.js"></script>
            </head>
            <body class="px-4 grid grid-rows-[min-content,1fr]">
                <nav class="flex justify-between">
                    <h1 class="py-4">FireBEH🔥</h1>
                    <div class="flex items-center">
                        <button
                            hx-get="/about"
                            hx-target="#pageContent"
                            hx-push-url="/about"
                        >
                            About
                        </button>
                    </div>
                </nav>
                <div class="flex justify-center items-center" id="pageContent">
                    {children}
                </div>
            </body>
        </html>
    );
};

error:

[{
	"owner": "typescript",
	"code": "2339",
	"severity": 8,
	"message": "Property 'html' does not exist on type 'Context<{ body: unknown; params: Record<never, string>; query: undefined; headers: undefined; response: unknown; }, {}> & {}'.",
	"source": "ts",
	"startLineNumber": 11,
	"startColumn": 18,
	"endLineNumber": 11,
	"endColumn": 22
}]

Just a test!

What is the type of issue?

Something else

What is the issue?

Nothing!

Where did you find it?

No response

[MISTAKE] Wrong on parse example

JSDOC description of life-cicle hook
image

new Elysia()
    .onParse((request, contentType) => {
        if(contentType === "application/json")
            return request.json()
    })

but in documentation - wrong example
https://elysiajs.com/life-cycle/parse.html#example
image
image

and so strange in JSDOC description....

image

maybe it should

new Elysia()
    .onParse(({ request }, contentType) => {
        if(contentType === "application/json")
            return request.json()
    })

tRPC plugin default endpoint does not work or missing opts in docs

What is the type of issue?

Documentation is missing, Example code is not working

What is the issue?

I am using elysia + tRPC plugin and started a small setup based on the docs here
The issue is that is i configure a client on localhost:3000 i get a 404 issue.

Screenshot 2024-04-25 at 15 16 57

This can be fixed by adding the and endpoint(without the trailing slash, otherwise its 404 again), but it should be mentioned that it is needed. I don't assume this is a bug on the trpc plugin, though a default "/" could be assumed and used.

Screenshot 2024-04-25 at 15 17 17

Edit: forgot to add server code

import { z } from "zod";
import { initTRPC } from "@trpc/server";

const t = initTRPC.create();
const publicProcedure = t.procedure;

const appRouter = t.router({
  greet: publicProcedure
    .input(z.object({ name: z.string() }))
    .query(async ({ input }) => ({ greet: input.name })),

  storeGreet: publicProcedure
    .input(z.object({ name: z.string() }))
    .mutation(async (opts) => {
      console.log({ opts });
      const { input } = opts;
      return { greet: input.name };
    }),
});

export type AppRouter = typeof appRouter;
export default appRouter;

Where did you find it?

(https://elysiajs.com/plugins/trpc.html

with drizzle/sqlite

What is the type of issue?

Example code is not working

What is the issue?

import { Elysia, t } from 'elysia'

import { createInsertSchema } from 'drizzle-typebox'
import { sqliteTable, text } from 'drizzle-orm/sqlite-core'
import { createId } from '@paralleldrive/cuid2'

const user = sqliteTable('user', {
    id: text('id').primaryKey().$defaultFn(createId),
    username: text('username').notNull(),
    password: text('password').notNull(),
})

const createUser = createInsertSchema(user)

const auth = new Elysia({ prefix: '/auth' })
    .put(
        '/sign-up',
        ({ body }) => createUser(body),
        {
            body: t.Omit(createUser, ['id'])
        }
    )

Where did you find it?

Error: This expression is not callable.
Type 'TObject<{ id: TOptional; username: TString; password: TString; }>' has no call signatures.

Typo inside `life-cycle.md`

What is the type of issue?

Something else

What is the issue?

Hi,

I found a typo in the Life Cycle documentation page.

We need to set "Content-Type" headers as "text/html" to for browser to render HTML.

I think it should actually be:

We need to set "Content-Type" headers as "text/html" for browser to render HTML.
So without the to.

Should I just create a small PR to fix it as a first contribution?

Where did you find it?

The documentation page: https://elysiajs.com/essential/life-cycle

A fatal error occurs while building the application

After entering the bun run build command I see the following messages in the terminal:

> bun run build
$ vitepress build docs

  vitepress v1.0.1

⠼ building client + server bundles...
🌼   daisyUI 4.4.20
├─ ✔︎ 2 themes added            https://daisyui.com/docs/themes
╰─ ★ Star daisyUI on GitHub     https://github.com/saadeghi/daisyui


🌼   daisyUI 4.4.20
├─ ✔︎ 2 themes added            https://daisyui.com/docs/themes
╰─ ★ Star daisyUI on GitHub     https://github.com/saadeghi/daisyui

⠴ building client + server bundles...
🌼   daisyUI 4.4.20
├─ ✔︎ 2 themes added            https://daisyui.com/docs/themes
╰─ ★ Star daisyUI on GitHub     https://github.com/saadeghi/daisyui


<--- Last few GCs --->

[868:0x65d63f0]   156492 ms: Mark-Compact 2019.2 (2089.4) -> 2013.3 (2092.9) MB, 644.57 / 0.00 ms  (average mu = 0.563, current mu = 0.158) allocation failure; scavenge might not succeed
[868:0x65d63f0]   157547 ms: Mark-Compact 2022.7 (2093.7) -> 2018.8 (2114.2) MB, 1040.39 / 0.00 ms  (average mu = 0.319, current mu = 0.014) allocation failure; scavenge might not succeed


<--- JS stacktrace --->

FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory
----- Native stack trace -----

 1: 0xca5580 node::Abort() [node]
 2: 0xb781f9  [node]
 3: 0xeca4d0 v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, v8::OOMDetails const&) [node]
 4: 0xeca7b7 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, v8::OOMDetails const&) [node]
 5: 0x10dc505  [node]
 6: 0x10f4388 v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [node]
 7: 0x10ca4a1 v8::internal::HeapAllocator::AllocateRawWithLightRetrySlowPath(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [node]
 8: 0x10cb635 v8::internal::HeapAllocator::AllocateRawWithRetryOrFailSlowPath(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [node]
 9: 0x10a8c86 v8::internal::Factory::NewFillerObject(int, v8::internal::AllocationAlignment, v8::internal::AllocationType, v8::internal::AllocationOrigin) [node]
10: 0x1503a16 v8::internal::Runtime_AllocateInYoungGeneration(int, unsigned long*, v8::internal::Isolate*) [node]
11: 0x193cef6  [node]
error: script "build" was terminated by signal SIGABRT (Abort)
[1]    867 abort      bun run build
> 

Probably an inaccuracy in the documents

In plugin section of documentation there is such code example

import { Elysia } from 'elysia'

const plugin = <const Prefix>({
    prefix = '/v1'
}: { prefix: Prefix }) => new Elysia({ prefix })
    .get(`/${prefix}/hi`, () => 'Hi')

const app = new Elysia()
    .use(plugin({
        prefix: '/v2'
    }))
    .listen(8080)

plugin-doc

But this code will not work properly because in get line ${prefix} is unnecessary and will cause route to be /v2/v2/hi, which is i belive incorrect

Essential Route Docs | demo inconsistencies

What is the type of issue?

Documentation is incorrect, Documentation is confusing

What is the issue?

Route demos have inconsistencies

The demos at https://elysiajs.com/essential/route.html#route have some things that need to be corrected.

first demo

The "/" route" responds "hello", but the code shows "Landing" as the response.
The example code defines a get request for the "/hello" route.
In the demo, the request is a post on route "localhost/hi".

second demo

According to the code example, the post route should return 'hi', but the playground returns "world".

4th demo(all('/')

It should return "hi" for all routes, but in the playground, all endpoints are implemented independently with a "hello" response.

404 demo

The demo has a working post route, which is not defined in the example, and the "not found" route does not return the specified text.

Where did you find it?

https://elysiajs.com/essential/route.html#route

404 on Eden page

The file https://github.com/elysiajs/documentation/blob/main/docs/plugins/overview.md still links to https://elysiajs.com/plugins/eden/overview.html, which is 404. I found https://elysiajs.com/plugins/eden/overview.html as the first Google result..

Incorrect Example + Description on Global Schema

What is the type of issue?

Documentation is confusing

What is the issue?

On Essential -> Schema -> Global Schema,

Its is mentioned that we can define global schema using:

.schema followed by a life cycle event in camelCase:

Its not clear.

The provided code

    .schema({ 
        query: t.Object({ 
            name: t.String() 
        }) 
    }) 
    .get('/query', ({ query: { name } }) => name)

the code is incorrect, it throws an error:

  • This expression is not callable. (IDE help)
  • TypeError: Object is not a function (near '...}).schema({...') (Runtime)

Defining a guard on top level does the job of validating the request.

    .guard({
        query: t.Object({
            name: t.String()
        }),
    })
    .get('/query', ({ query: { name } }) => name)

If this is the case, We may need to to rephrase some description and update the example. I can send PR for this

If we can use the .schema, how can we do that?

Where did you find it?

Essential -> Schema -> Global Schema

@elysiajs/jwt ^1.0.2 breaks type inference for handler functions

I added @elysiajs/jwt ^1.0.2 to my project and initialised it with the .use hook. Everything seems to work fine however it breaks the type inference causing the handler method parameters to implicitly return a type of any.

    app.use(jwt({
        secret: env.JWT_SECRET,
        algorithms: ["HS256"],
        maxAge: "1d",
        clockTolerance: 0
    }))
    .get("/", async ({query, jwt, set, cookie: { auth }}) => {
            const verified = await jwt.verify(auth.value)
            if (!verified) {
                set.status = 401
                return 'Unauthorized'
            }
            const users = await AuthenticationController.all(query);
            return ApiResponse.success(users);
        },
        {
            detail: { tags: ["Authentication"] }
        }
    )

jwt, query, set, and auth now implicitly have the type of any

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.