typescriptconnectionnext.jstypeorm

typeORM combine next.js can not connect database with error


I try to using TypeORM with next.js framework.

my connection is:

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;
};

the console is:

======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

Why every time I try to connect database and then connection is still not connected. my tsconfig.json is:

{
   "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"
   ]
 }

can not simply apply type:"module" in package.json file, for error:

 [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'

Solution

  • The problem might arise if your ormconfig migrations/entities property points to .ts files. One way to overcome the issue is by overwriting these properties when passing it to createConnection function like following:

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

    Refer this comment on Github: https://github.com/typeorm/typeorm/issues/6241#issuecomment-643690383