NodeJS 使用TypeScript导入@fastify/oauth2

hmae6n7t  于 2023-04-11  发布在  Node.js
关注(0)|答案(1)|浏览(113)

我正在尝试导入并注册插件@fastify/oauth2。我使用以下依赖项:

"devDependencies": {
    "@types/node": "^18.15.5",
    "@types/qs": "^6.9.7",
    "nodemon": "^2.0.21",
    "pino-pretty": "^9.4.0",
    "rimraf": "^4.4.1",
    "ts-node": "^10.9.1",
    "tsc-alias": "^1.8.4",
    "typescript": "^4.9.5"
  },
  "dependencies": {
    "@fastify/cors": "^8.2.0",
    "@fastify/oauth2": "^7.0.1",
    "@trpc/client": "^10.18.0",
    "@trpc/server": "^10.18.0",
    "@types/luxon": "^3.2.0",
    "axios": "^1.3.4",
    "dotenv": "^16.0.3",
    "fastify": "^4.15.0",
    "luxon": "^3.3.0",
    "mysql2": "^3.2.0",
    "zod": "^3.21.4"
  }

这是我的tsconfig:

{
  "compilerOptions": {
    "baseUrl": ".",
    "target": "es2016",
    "module": "commonjs",
    "composite": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "outDir": "lib",
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": ["src/**/*"]
}

但当我尝试注册插件像这样:

server.register(fastifyOauth2, {
  name: 'facebookOAuth2',
  credentials: {
    client: {
      id: process.env.FACEBOOK_APP_ID,
      secret: process.env.FACEBOOK_APP_SECRET
    },
    auth: fastifyOauth2.FACEBOOK_CONFIGURATION
  },
  // register a fastify url to start the redirect flow
  startRedirectPath: '/login/facebook',
  // facebook redirect here after the user login
  callbackUri: 'http://localhost:1337/login/facebook/callback'
});

Typescript显示以下错误:
TS2769: No overload matches this call.   Overload 2 of 3, '(plugin: FastifyPluginAsync<FastifyOAuth2Options, RawServerDefault, FastifyTypeProviderDefault, FastifyBaseLogger>, opts?: FastifyRegisterOptions<...> | undefined): FastifyInstance<...> & PromiseLike<...>', gave the following error.     Argument of type 'FastifyOauth2' is not assignable to parameter of type 'FastifyPluginAsync<FastifyOAuth2Options, RawServerDefault, FastifyTypeProviderDefault, FastifyBaseLogger>'
这是库中的错误还是我只是使用错误?
我试着像下面这样导入它,虽然它们都解决了,但它们都给出了相同的错误:

import fastifyOauth2 from '@fastify/oauth2';
import { fastifyOauth2 } from '@fastify/oauth2';
import * as fastifyOauth2 from '@fastify/oauth2';
xzlaal3s

xzlaal3s1#

Oauth2插件配置中的客户端id和secret必须是string类型,而您提供的变量类型为string | undefined(process.env变量)。
你需要在配置中的env变量中添加类型Assert,以“告诉”编译器将其作为字符串处理:process.env.FACEBOOK_APP_ID as string
插件注册代码看起来像这样:

server.register(fastifyOauth2, {
  name: 'facebookOAuth2',
  credentials: {
    client: {
      id: process.env.FACEBOOK_APP_ID as string,
      secret: process.env.FACEBOOK_APP_SECRET as string,
    },
    auth: fastifyOauth2.FACEBOOK_CONFIGURATION
  },
  // register a fastify url to start the redirect flow
  startRedirectPath: '/login/facebook',
  // facebook redirect here after the user login
  callbackUri: 'http://localhost:1337/login/facebook/callback'
});

相关问题