2016-11-23 126 views
1

我試圖在打字稿中使用typeorm庫在TypeScript 2 Express服務器和Angular 2之間創建DTO/DAO模式。如何防止裝飾者在TypeScript中導入節點模塊?

爲了簡潔起見,我將這些對象稱爲DTO,但它們只是一堆字段和註釋。

import {autoserialize} from "cerialize"; 
import {DTOReport} from "./reports.dto"; 

import { PrimaryGeneratedColumn} from "typeorm/decorator/columns/PrimaryGeneratedColumn" 
import { CreateDateColumn } from "typeorm/decorator/columns/CreateDateColumn"; 
import { Column } from "typeorm/decorator/columns/Column"; 
import { JoinColumn } from "typeorm/decorator/relations/JoinColumn"; 
import { OneToOne } from "typeorm/decorator/relations/OneToOne"; 
import { ManyToOne } from "typeorm/decorator/relations/ManyToOne"; 
import { OneToMany } from "typeorm/decorator/relations/OneToMany"; 
import { Table } from "typeorm/decorator/tables/Table"; 
import { ColumnTypes } from "typeorm/metadata/types/ColumnTypes"; 

@Table() 
export class DTOSourceFile { 
    @PrimaryGeneratedColumn() 
    @autoserialize 
    id: number; 

    @Column() 
    @autoserialize 
    locationURL: string; 

    @CreateDateColumn() 
    @autoserialize 
    createdAt: Date; 

    @OneToMany(type => DTOReport, report => report.source, {nullable: true}) 
    @autoserialize report: DTOReport; 
    @autoserialize reportId: number; 

    @Column(ColumnTypes.TEXT) 
    @autoserialize 
    originalname: string; 

    @Column(ColumnTypes.JSON) 
    @autoserialize 
    mutler: string; 
} 

我小心地只導入裝飾器。但是,在編譯時,我看到一個請求返回到根index.ts文件。

"use strict"; 
const ColumnTypes_1 = require("../../metadata/types/ColumnTypes"); 
const ColumnTypeUndefinedError_1 = require("../error/ColumnTypeUndefinedError"); 
const index_1 = require("../../index"); // < --- THIS 
const PrimaryColumnCannotBeNullableError_1 = require("../error/PrimaryColumnCannotBeNullableError"); 
/** 
* Column decorator is used to mark a specific class property as a table column. 
* Only properties decorated with this decorator will be persisted to the database when entity be saved. 
* Primary columns also creates a PRIMARY KEY for this column in a db. 
*/ 
function PrimaryColumn(typeOrOptions, options) { 
    let type; 
    if (typeof typeOrOptions === "string") { 
     type = typeOrOptions; 
    } 
    else { 
     options = typeOrOptions; 
    } 
    return function (object, propertyName) { 
     const reflectedType = ColumnTypes_1.ColumnTypes.typeToString(Reflect.getMetadata("design:type", object, propertyName)); 
     // if type is not given implicitly then try to guess it 
     if (!type) 
      type = ColumnTypes_1.ColumnTypes.determineTypeFromFunction(Reflect.getMetadata("design:type", object, propertyName)); 
     // if column options are not given then create a new empty options 
     if (!options) 
      options = {}; 
     // check if there is no type in column options then set type from first function argument, or guessed one 
     if (!options.type) 
      options = Object.assign({ type: type }, options); 
     // if we still don't have a type then we need to give error to user that type is required 
     if (!options.type) 
      throw new ColumnTypeUndefinedError_1.ColumnTypeUndefinedError(object, propertyName); 
     // check if column is not nullable, because we cannot allow a primary key to be nullable 
     if (options.nullable) 
      throw new PrimaryColumnCannotBeNullableError_1.PrimaryColumnCannotBeNullableError(object, propertyName); 
     // implicitly set a primary to column options 
     options = Object.assign({ primary: true }, options); 
     // create and register a new column metadata 
     const args = { 
      target: object.constructor, 
      propertyName: propertyName, 
      propertyType: reflectedType, 
      mode: "regular", 
      options: options 
     }; 
     index_1.getMetadataArgsStorage().columns.add(args); // < --- THIS 
    }; 
} 
exports.PrimaryColumn = PrimaryColumn; 

//# sourceMappingURL=PrimaryColumn.js.map 

Angular 2的webpack編譯器產生的錯誤清楚地顯示了問題,因爲它會嘗試加載節點依賴關係。

WARNING in ./~/typeorm/driver/sqlserver/SqlServerDriver.js 
Module not found: Error: Can't resolve 'mssql' in '/Users/jmurphy/projects/ubq/web/node_modules/typeorm/driver/sqlserver' 
@ ./~/typeorm/driver/sqlserver/SqlServerDriver.js 256:25-41 
@ ./~/typeorm/connection/ConnectionManager.js 
@ ./~/typeorm/index.js 
@ ./~/typeorm/decorator/columns/PrimaryGeneratedColumn.js 
@ ./src/app/dtos/lens.dto.ts 
@ ./src/app/lens/lens.component.ts 
@ ./src/app/app.module.ts 
@ ./src/app/index.ts 
@ ./src/main.ts 
@ multi main 
Child html-webpack-plugin for "index.html": 
     Asset  Size Chunks  Chunk Names 
    index.html 2.88 kB  0 
webpack: bundle is now VALID. 

有沒有一種方法可以讓TypeORM裝飾在瀏覽器項目中存在,但不嘗試加載節點的依賴?

鏈接:

TypeORM來源: https://github.com/typeorm/typeorm/blob/master/src/decorator/columns/PrimaryColumn.ts

+0

您能否包含PrimaryColumn.ts的源代碼? –

+1

@OweRReLoaDeD - 我追加了鏈接 –

+0

也許我沒有正確理解這一點,但在TS中有一個導入https://github.com/typeorm/typeorm/blob/master/src/decorator/columns/PrimaryColumn .ts#L4這就是爲什麼JS中有一個導入? –

回答

1

我覺得這個庫沒有被設計在Web瀏覽器的工作,但也許有一個解決方案。裝飾器使用getMetadataArgsStorage函數,其聲明爲/index.ts/index.ts導入了很多導致您遇到問題的事情。

您可以看到heregetMetadataArgsStorage函數如何使用defaultContainerMetadataArgsStorage

如果getMetadataArgsStorageindex.ts轉移到一個新的文件,也許它會工作你,但是你要需要一個PR發送到GitHub上的項目。

問題是this line因爲ConnectionManager進口的所有驅動程序:

import * as fs from "fs"; 
import {Connection} from "./Connection"; 
import {ConnectionNotFoundError} from "./error/ConnectionNotFoundError"; 
import {MysqlDriver} from "../driver/mysql/MysqlDriver"; 
import {ConnectionOptions} from "./ConnectionOptions"; 
import {DriverOptions} from "../driver/DriverOptions"; 
import {Driver} from "../driver/Driver"; 
import {MissingDriverError} from "./error/MissingDriverError"; 
import {PostgresDriver} from "../driver/postgres/PostgresDriver"; 
import {AlreadyHasActiveConnectionError} from "./error/AlreadyHasActiveConnectionError"; 
import {Logger} from "../logger/Logger"; 
import {SqliteDriver} from "../driver/sqlite/SqliteDriver"; 
import {OracleDriver} from "../driver/oracle/OracleDriver"; 
import {SqlServerDriver} from "../driver/sqlserver/SqlServerDriver"; 
import {OrmUtils} from "../util/OrmUtils"; 
import {CannotDetermineConnectionOptionsError} from "./error/CannotDetermineConnectionOptionsError"; 

/** 
* ConnectionManager is used to store and manage all these different connections. 
* It also provides useful factory methods to simplify connection creation. 
*/ 
export class ConnectionManager { 
// ... 

我建議你到你的使用情況解釋typeorm的作者。也可能會提到,如果不是所有的驅動程序總是默認導入,那將會很好。最好只加載所需的驅動程序(在你的情況下都不是)。

+2

我在這裏創造一個叉做什麼,你剛纔概述:https://github.com/rightisleft/typeorm/commit/84baefd7e1ecfb7024b724ec6f94c8797bd61798 –

+1

如果它工作和你的PR解釋您的使用案例的原作者,他們很可能會接受它。祝你好運 ;) –

相關問題