electron-vite-vue icon indicating copy to clipboard operation
electron-vite-vue copied to clipboard

[Help] Unsuccessful to integrate TypeORM

Open maximluo opened this issue 1 year ago • 1 comments

I try to integrate TypeORM in it, but unsuccessful to import the entity .ts file when initializing the database.

The project structure is

electron
|--database
|--|--index.ts
|--|--entity
|--|--|--test.entity.ts

Here is the code that I use in electron/database/index.ts

import "reflect-metadata";
import { DataSource } from "typeorm";

     this.appDataSource = new DataSource({
        type: "sqlite",
        database: dbPath,
        entities: ["./entity/*.ts"],
      });

The content of test.entity.ts

import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column()
    age: number
}

Case 1 With the above config, when I run to debug, the database file can be created but failed to create the table.

Case 2 If I change the property of entities from file path to entity class by using import.

import { User } from "./entity/test.entity.ts"

     this.appDataSource = new DataSource({
        type: "sqlite",
        database: dbPath,
        entities: [User],
      });

The table can be created successfully.

Case 3 I took a deep step, by change the property of 'entities' with app.getAppPath()

     this.appDataSource = new DataSource({
        type: "sqlite",
        database: dbPath,
        entities: [path.join(app.getAppPath(), "./electron/database/entity/*.entity.ts")],
      });

It would occurs and error,

import {
^^^^^^

SyntaxError: Cannot use import statement outside a module

From the error message, we could know by using app.getAppPath() to get the absoluted path is working, the relative path in Case 1 is not working. But I have no idea to solve this error.

Maybe change the module in tsconfig.json from ESNext to commonjs?

In official document of TypeORM, about the entities property,

entities - Entities, or Entity Schemas, to be loaded and used for this data source. Accepts both entity classes, entity schema classes, and directories paths to load from. Directories support glob patterns. Example: entities: [Post, Category, "entity/.js", "modules/**/entity/.js"].

In the example, we can notice the path is js, not ts. Is that means we need to translate ts to js and put these js files into dist-electron, but for vite-plugin-electron, the entry only supports for single file not for a path with glob pattern.

How to do this op?

maximluo avatar Dec 28 '23 10:12 maximluo

have you ever try import.meta.glob?

subframe7536 avatar Mar 09 '24 15:03 subframe7536