最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - Is it possible to keep type safety in ElysiaJS when using seperate route files, espcially when using plugins(JWT)?

programmeradmin3浏览0评论

When using ElysiaJS and a plugin like @elysiajs/jwt in different routes, I am unable to keep typesafety:

 .post(
    "/register",
    async ({ jwt, body, cookie: { auth }, error }) => {
     ....
}

The error I get is You're trying to access jwt on an object that doesn't contain it. (parameter) jwt: any Is there an elegant way to make use Elysia`s intelligent typing system or do I need to create my own global index.d.ts or so?

I want to implement Authentification in Elysiajs using @elysiajs/jwt. My index.ts looks like this:

import { Elysia, type InferContext } from "elysia"
import authRoutes from "./routes/auth"
import { cors } from "@elysiajs/cors"
import { staticPlugin } from "@elysiajs/static"
import profileRoutes from "./routes/profile"
import jwt from "@elysiajs/jwt"
const app = new Elysia()
export const jwtConfig = jwt({
  name: "jwt",
  secret: "Fischl von Luftschloss Narfidort",
})
app
  .use(cors())
  .use(staticPlugin())
  .use(
    jwt({
      name: "jwt",
      secret: "Fischl von Luftschloss Narfidort",
    })
  )

  .guard(
    {
      async beforeHandle({ jwt, cookie: { auth }, error }) {
        const user = auth.cookie.value as string
        const verify = await jwt.verify(user)

        console.log(user, verify)
        if (!user) {
          return error(401, "Unauthorized")
        }
      },
    },
    (app) => app.use(profileRoutes)
  )
  .use(authRoutes)
app.listen(process.env.PORT || 3000)
export type ContextType = InferContext<typeof app>
console.log(
  `

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论