typeORM combine next.js 无法连接数据库错误

typeORM combine next.js can not connect database with error

我尝试将 TypeORM 与 next.js 框架一起使用。

我的联系人是:

const create =  () => {
    // @ts-ignore
    return createConnection({
        ...config
    });
};
export const getDatabaseConnection = async () => {
    console.log("======getDatabaseConnection====");
    const manager = getConnectionManager();
    const current = manager.has('default') ? manager.get('default'): (await create());
    console.log(current.isConnected)
    await current.connect().catch(e=> console.log(e))
    console.log("======success====");
    console.log(current.isConnected)
    if(current.isConnected){
        console.log("current connected")
    }else{
        await current.connect()
        console.log("current  reconnect")
    }
    return current;
};

控制台是:

======getDatabaseConnection====
false
/mnt/c/workgit/orm/src/entity/Contact.ts:1
import {Entity, Column, ManyToOne, PrimaryGeneratedColumn} from "typeorm";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1167:16)
    at Module._compile (internal/modules/cjs/loader.js:1215:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1272:10)
    at Module.load (internal/modules/cjs/loader.js:1100:32)
    at Function.Module._load (internal/modules/cjs/loader.js:962:14)
    at Module.require (internal/modules/cjs/loader.js:1140:19)
    at require (internal/modules/cjs/helpers.js:75:18)
    at Function.PlatformTools.load (/mnt/c/workgit/orm/node_modules/typeorm/platform/PlatformTools.js:114:28)
    at /mnt/c/workgit/orm/node_modules/typeorm/util/DirectoryExportedClassesLoader.js:39:69
    at Array.map (<anonymous>)
======success====
false

为什么我每次都尝试连接数据库然后连接还是连接不上。 我的 tsconfig.json 是:

{
   "compilerOptions": {
     "emitDecoratorMetadata": true,
     "experimentalDecorators": true,
     "noImplicitAny": true,
     "baseUrl": ".",
     "target": "es5",
     "module": "commonjs",
     "strict": false,
     "esModuleInterop": true,
     "lib": [
       "dom",
       "dom.iterable",
       "esnext"
     ],
     "allowJs": true,
     "skipLibCheck": true,
     "forceConsistentCasingInFileNames": true,
     "noEmit": true,
     "moduleResolution": "node",
     "resolveJsonModule": true,
     "isolatedModules": true,
     "jsx": "preserve"
   },
   "exclude": [
     "node_modules"
   ],
   "include": [
     "next-env.d.ts",
     "**/*.ts",
     "**/*.tsx"
   ]
 }

不能简单地应用类型:package.json 文件中的“模块”,错误:

 [ERR_REQUIRE_ESM]: Must use import to load ES Module: /mnt/c/workgit/orm/.next/server/pages/api/user/signup.js
require() of ES modules is not supported.
require() of /mnt/c/workgit/orm/.next/server/pages/api/user/signup.js from /mnt/c/workgit/orm/node_modules/next/dist/next-server/server/next-server.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename signup.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /mnt/c/workgit/orm/package.json.

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1268:13)
    at Module.load (internal/modules/cjs/loader.js:1100:32)
    at Function.Module._load (internal/modules/cjs/loader.js:962:14)
    at Module.require (internal/modules/cjs/loader.js:1140:19)
    at require (internal/modules/cjs/helpers.js:75:18)
    at DevServer.handleApiRequest (/mnt/c/workgit/orm/node_modules/next/dist/next-server/server/next-server.js:48:175)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async Object.fn (/mnt/c/workgit/orm/node_modules/next/dist/next-server/server/next-server.js:40:218)
    at async Router.execute (/mnt/c/workgit/orm/node_modules/next/dist/next-server/server/router.js:38:67)
    at async DevServer.run (/mnt/c/workgit/orm/node_modules/next/dist/next-server/server/next-server.js:49:494) {
  code: 'ERR_REQUIRE_ESM'

如果您的 ormconfig migrations/entities 属性 指向 .ts 文件,则可能会出现此问题。解决此问题的一种方法是在将这些属性传递给 createConnection 函数时覆盖这些属性,如下所示:

createConnection({
  ...config,
  entities: [Contact],
  migrations: []
});

参考 Github 上的评论:https://github.com/typeorm/typeorm/issues/6241#issuecomment-643690383