elysiajs / elysia

Ergonomic Framework for Humans
https://elysiajs.com
MIT License
10.25k stars 219 forks source link

[bugreport] TypeError: undefined is not an object (evaluating 'this.raw') #195

Closed eelkevdbos closed 1 year ago

eelkevdbos commented 1 year ago

When destructuring the ws param in open(ws) { }, the method starts throwing: TypeError: undefined is not an object (evaluating 'this.raw'). It looks vaguely related to #174.

My environment

{
  "devDependencies": {
    "bun-types": "^1.0.1"
  },
  "peerDependencies": {
    "typescript": "^5.2.2"
  },
  "dependencies": {
    "@elysiajs/html": "^0.7.0",
    "@kitajs/html": "^2.2.2",
    "@kitajs/ts-html-plugin": "^1.0.2",
    "elysia": "^0.7.3"
  }
}

Snippet to reproduce:

new Elysia()
  .ws('/ws/:channel', {
    params: t.Object({
      channel: t.String(),
    }),
    open({ subscribe, data: { params } }) {
      subscribe(params.channel) // throws TypeError
    },
  })

Snippet that does not throw:

new Elysia()
  .ws('/ws/:channel', {
    params: t.Object({
      channel: t.String(),
    }),
    open(ws) {
      ws.subscribe(ws.data.params.channel)
    },
  })
erra0002 commented 1 year ago

This is expected behavior, destructuring assignment is not "supported" in javascript for class methods like subscribe, because the context and therefore "this" is lost. You have to use ws.subsribe(...)