1

我正在尝试运行使用 typeorm 库的 typqgraphql 服务器。这两个库都大量使用装饰器。运行时netlify dev出现以下错误:

{"errorMessage":"Column type for Country#code is not defined and cannot be guessed. Make sure you have turned on an \"emitDecoratorMetadata\": true option in tsconfig.json. Also make sure you have imported \"reflect-metadata\" on top of the main entry file in your application (before any entity imported).If you are using JavaScript instead of TypeScript you must explicitly provide a column type.","errorType":"ColumnTypeUndefinedError","stackTrace":["new ColumnTypeUndefinedError2 (/home/etudor/users-api/node_modules/src/error/ColumnTypeUndefinedError.ts:9:9)","/home/etudor/users-api/node_modules/typeorm/src/decorator/columns/Column.ts:143:23","__decorateClass (/home/etudor/users-api/.netlify/functions-serve/users-api-gql/src/users-api-gql.js:50:24)","Object.<anonymous> (/home/etudor/users-api/src/models/Country.entity.ts:21:3)","Module._compile (node:internal/modules/cjs/loader:1108:14)","Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)","Module.load (node:internal/modules/cjs/loader:988:32)","Function.Module._load (node:internal/modules/cjs/loader:828:14)","Module.require (node:internal/modules/cjs/loader:1012:19)","require (node:internal/modules/cjs/helpers:93:18)"],"level":"error"}

或者这个错误

Error: Unable to infer GraphQL type from TypeScript reflection system. You need to provide explicit type for 'name' of 'Role' class.
  Object.findType (/home/etudor/users-api/node_modules/type-graphql/dist/helpers/findType.js:19:15)

我的根目录中有 tsconfig.json 并且还尝试将其移动到 netlify/functions 目录中。

{
  "version": "2.4.2",
  "compilerOptions": {
    "lib": [
      "es5",
      "es6",
      "esnext.asynciterable"
    ],
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "sourceMap": true,
    "outDir": "./dist",
    "skipLibCheck": true,
    "strict": true
  },
  "exclude": [
    "node_modules",
    "tests"
  ]
}

显然 netlify 没有读取我的 tsconfig.json 文件或没有注册装饰器。

这是我的 netlify 功能

import 'reflect-metadata'
import { getApp } from '../../../src/server'
import ServerlessHttp from 'serverless-http'


const app = getApp()

exports.handler = ServerlessHttp(app)

国家实体

@Entity()
export class Country extends BaseEntity {
  @PrimaryColumn()
  uuid: string = generateUuid('ctr')

  @Column()
  name!: string

  @Column()
  code!: string

角色实体

@ObjectType({ simpleResolvers: true })
@Entity()
export class Role extends BaseEntity {
  @Field(() => ID)
  @PrimaryColumn()
  uuid!: string

  @Field()
  @Column()
  name!: string

  @Field({
    nullable: true,
  })
  @Column({ nullable: true })
  description?: string
4

1 回答 1

0

我做了以下配置我创建了一个总结json的常量最重要的部分是通过导入添加类实体名称(用户、客户端和用户客户端是带有装饰器的实体)

export const connectionConfig: any = {
  type: 'mysql',
  host: '#####',
  port: ###,
  username: '###',
  password: '####',
  database: '####',
  synchronize: true,
  logging: false,
  entities: [
    User,
    Client,
    UserClient       
  ],
  migrations: ['../migration/**/*.ts'],
  subscribers: ['../subscriber/**/*.ts'],
  cli: {
    entitiesDir: '../entity',
    migrationsDir: '../migration',
    subscribersDir: '../subscriber'
  }
};

最后,您可以创建一个类来初始化您的 typeorm。函数 getConnection 将由您的无服务器项目中的服务或存储库级别调用。

import { Connection, createConnection } from 'typeorm';
import { connectionConfig } from '../constants/typeorm';

// eslint-disable-next-line import/prefer-default-export
export class TypeOrm {
  private static conn: Connection;

  static async getConnection() {
    if (!this.conn) {
      this.conn = await createConnection(connectionConfig);
    }
    return this.conn;
  }

  static async closeConnection() {
    if (this.conn) {
      console.log('Is been disconnected');
      await this.conn.close();
    }
  }
}

从服务或存储层调用

 static async getAll(): Promise<User[]> {
    const conn = await TypeOrm.getConnection();
    return conn.getRepository(User).find({ relations: ['userClients'] });
  }
于 2021-05-26T16:35:13.730 回答