无法解构“db.config.connection”的属性“client”,因为它未定义

问题描述 投票:0回答:1

无法解构“db.config.connection”的属性“client”,因为它未定义..任何人都可以告诉我哪里出错了..谢谢...

config/database.ts

import path from 'path';
import { fileURLToPath } from 'url';

// Derive __filename and __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
import { DatabaseConfig } from '../src/types/strapi'; 

export default ({ env }: { env: (key: string, defaultValue?: any) => any }): DatabaseConfig => {
  // Resolve the filename with environment variable or default value
  const filename = path.join(
    __dirname,
    '..',
    '..',
    env('DATABASE_FILENAME', path.join('.tmp', 'data.db'))
  );

  // Debugging output
  console.log('Resolved Filename Path:', filename); 
  console.log('DATABASE_CLIENT:', env('DATABASE_CLIENT', 'sqlite')); 

  // Database configuration
  const config: DatabaseConfig = {
    connection: {
      client: env('DATABASE_CLIENT', 'sqlite'), 
      connection: {
        filename: filename, 
      },
      useNullAsDefault: true, 

    },
  };

  // Return the configuration object
  return config;
};

src/types/strapi.d.ts
export interface DatabaseConfig {
  connection: {
    client: string;
    connection: {
      filename?: string;
      host?: string;
      port?: number;
      database?: string;
      user?: string;
      password?: string;
    };
    useNullAsDefault?: boolean;
  };
}

tscongfig.json

{
  "extends": "@strapi/typescript-utils/tsconfigs/server",
  "compilerOptions": {
    "typeRoots": ["./node_modules/@types", "./src/types"],
    "target": "ES2021",           
    "module": "node16",           
    "moduleResolution": "Node16",   
    "esModuleInterop": true,        
    "forceConsistentCasingInFileNames": true,
    "rootDir": "./src",             
    "outDir": "./build",          
    "skipLibCheck": true,           
    "strict": false,                
    "allowJs": true,               
    "checkJs": false,               
    "resolveJsonModule": true ,
    "types":["node"]      // Allow importing JSON modules
  },
  "include": ["src/**/*.ts"],       // Include all .ts files in src
  "exclude": ["node_modules", "build", ".cache", ".tmp"]
}

.env 文件 DATABASE_CLIENT=sqlite DATABASE_FILENAME=.tmp/data.db

package.json
{
  "name": "strapi-backend",
  "private": true,
  "version": "0.1.0",
  "description": "A Strapi application",
  "scripts": {
    "build": "tsc && strapi build",
    "develop": "tsc && strapi develop",
    "start": "strapi start"
  },
  "devDependencies": {
    "@types/koa": "^2.15.0",
    "@types/node": "^22.5.5",
    "strapi-to-typescript": "^2.0.15",
    "typescript": "^5.6.2"
  },
  "dependencies": {
    "@strapi/plugin-cloud": "4.25.11",
    "@strapi/plugin-i18n": "4.25.11",
    "@strapi/plugin-users-permissions": "4.25.11",
    "@strapi/strapi": "4.25.11",
    "better-sqlite3": "8.6.0",
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "react-router-dom": "^5.3.4",
    "sqlite3": "^5.1.7",
    "styled-components": "^5.3.11"
  },
  "author": {
    "name": "A Strapi developer"
  },
  "strapi": {
    "uuid": "1165bdd3-f9da-4cad-88bb-00136497d786"
  },
  "engines": {
    "node": ">=18.0.0 <=20.x.x",
    "npm": ">=6.0.0"
  },
  "license": "MIT"
}

//src/api/user/controller/user.ts

import { DatabaseConfig } from '../../../../src/types/strapi';


const dbConfig = strapi.config.get('database.connection') as DatabaseConfig['connection'];

if (dbConfig) {
  console.log(dbConfig.client);
  console.log(dbConfig.connection.filename);
} else {
  console.error('Database configuration is missing or incorrect.');
}

我正在开发一个 Strapi 应用程序..任何人都可以告诉我哪里错了

TypeError:无法解构“db.config.connection”的属性“client”,因为它未定义。

javascript typescript sqlite path strapi
1个回答
0
投票

根据我的笔记,我自己解决了这个问题。以下是我会仔细检查以确保其有效的事情。对于上下文,我正在努力设置单元测试。

  • 仔细检查您的环境变量。环境中至少需要
    DATABASE_FILENAME=.tmp/data.db
  • 您正在使用打字稿,因此在我从here窃取的 setupStrapi 辅助函数中,您将进行一个小更新。
export async function setupStrapi() {
  let instance: Required<StrapiI>;
  if (!instance) {
-    await Strapi().load();
+    await Strapi({ distDir: "./dist" }).load();
    await waitForServer();

    instance = strapi;
  }

  return instance;
}
  • 最后插件
    "strapi-plugin-sitemap"
    也导致了这个错误。版本至少需要为 3.2.1。
    "strapi-plugin-sitemap": "3.2.1"
© www.soinside.com 2019 - 2024. All rights reserved.