【问题标题】:Decorators not working - TypeGraphql & TypeORM Netlify Functions装饰器不起作用 - TypeGraphql 和 TypeORM Netlify 函数
【发布时间】:2021-08-14 14:21:31
【问题描述】:

我正在尝试运行使用 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

【问题讨论】:

  • 请分享您如何在Country 实体中定义code 字段
  • 对是否正在读取 tsconfig 的简单测试是将 outDir 更改为其他位置,然后查看该更改是否反映在构建中
  • @ranjan_purbey 我这样做了,但 netlify 没有注册更改。所以在部署或运行​​ lambda 函数时不会读取文件
  • 在部署到云端而不是在本地运行时,您是否遇到同样的错误?
  • @ranjan_purbey 是的,同样的错误

标签: typescript typeorm netlify typegraphql netlify-function


【解决方案1】:

我做了以下配置我创建了一个总结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'] });
  }

【讨论】:

  • 感谢您的回答,我试过了,但得到了同样的错误。我认为问题更多来自 netlify 无法读取 tsconfig.json。如果我从yarn start 运行代码,那么它会编译并运行
猜你喜欢
  • 2020-07-29
  • 2021-08-04
  • 2021-01-01
  • 2017-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-14
相关资源
最近更新 更多