I'm struggling to find a configuration that works for TypeORM in a TypeScript project in all environments.
For example, starting with this ormconfig.js:
var dotenv = require("dotenv")
dotenv.config()
var connectionOptions = [
{
"name": "default",
"type": "postgres",
"url": process.env.DATABASE_URL,
},
{
"name": "testing",
"type": "postgres",
"url": `${process.env.DATABASE_URL}_test`,
}];
module.exports = connectionOptions
But then, when I try to start the application, I get this error:
No repository for "User" was found. Looks like this entity is not registered in current "default" connection?
So, I add the entities to the config:
var dotenv = require("dotenv")
dotenv.config()
var connectionOptions = [
{
"name": "default",
"type": "postgres",
"url": process.env.DATABASE_URL,
"entities": ["src/entity/**/*"],
},
{
"name": "testing",
"type": "postgres",
"url": `${process.env.DATABASE_URL}_test`, // TODO: fix
"entities": ["src/entity/**/*"],
}];
module.exports = connectionOptions
At this point, running the app in dev (ts-node-dev src/main.ts) works. But when I compile it and try to run the JavaScript, I get this error:
C:\Users\pupeno\Documents\Flexpoint Tech\js\exp7\backend\src\entity\User.ts:1
import {BaseEntity, Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn} from "typeorm"
^^^^^^
SyntaxError: Cannot use import statement outside a module
It's trying to load the User.ts source file instead of the compiled User.js.
The way I'm running my app in prod is by running node build/src/main.js, the problem is that ormconfig.js is still at the top level, printing __dirname and __filename shows:
C:\Users\pupeno\Documents\Flexpoint Tech\js\exp7\backend
C:\Users\pupeno\Documents\Flexpoint Tech\js\exp7\backend\ormconfig.js
How are you supposed to configure TypeORM to work in both development and production?
Renaming my entity to User.entity.ts and setting entities this way:
var dotenv = require("dotenv")
dotenv.config()
var connectionOptions = [
{
"name": "default",
"type": "postgres",
"url": process.env.DATABASE_URL,
"entities": [__dirname + '/**/*.entity{.ts,.js}'],
},
{
"name": "testing",
"type": "postgres",
"url": `${process.env.DATABASE_URL}_test`, // TODO: fix
"entities": [__dirname + '/**/*.entity{.ts,.js}'],
}];
console.log(connectionOptions)
module.exports = connectionOptions
cause the same error, as Node tries to load a TypeScript file:
(node:19344) UnhandledPromiseRejectionWarning: C:\Users\pupeno\Documents\Flexpoint Tech\js\exp7\backend\src\entity\User.entity.ts:1
import {BaseEntity, Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn} from "typeorm"
^^^^^^
SyntaxError: Cannot use import statement outside a module