微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

type-graphql/typorm 实体不被视为模块

如何解决type-graphql/typorm 实体不被视为模块

我是 GraphQL 和 AWS/无服务器的新手,我一直在尝试将 type-graphqltypeorm 一起使用(装饰器的组合看起来很整洁)在 Lambda 上创建 GraphQL api。>

但是出了点问题,当我尝试访问 GraphQL 游乐场时,serverless-offline 抱怨我的实体文件

看起来它正在尝试使用打字稿来编译 handler.js 插件输出serverless-webpack 文件。我不确定这是不是问题,还是我使用 type-graphqltypeorm 装饰器的方式存在普遍问题?

最初我收到此错误

TSError: ⨯ Unable to compile TypeScript:
  src/entity/Talent/Talent.ts:13:7 - error TS2451: Cannot redeclare block-scoped variable 'type_graphql_1'.
  
  13 const type_graphql_1 = require("type-graphql");
           ~~~~~~~~~~~~~~
  
    src/entity/Location.ts:13:7
      13 const type_graphql_1 = require("type-graphql");
               ~~~~~~~~~~~~~~
      'type_graphql_1' was also declared here.

据我所知,如果将它们视为模块,则这些 require 语句将是块范围的,这不会成为问题。

之后,我将 isolatedModules: true 添加到我的 tsconfig.json 中,错误变为:

TSError: ⨯ Unable to compile TypeScript:
  src/entity/Location.ts:1:1 - error TS1208: 'Location.ts' cannot be compiled under '--isolatedModules' because it is considered a global script file. Add an import,export,or an empty 'export {}' statement to make it a module.

我的 Location.ts 文件包含多个导入和一个导出,所以我不确定为什么它被视为全局脚本文件

(如果我删除位置,Talent.ts 也是如此,我假设我的所有实体文件都是如此)

Location.ts

import { Field,Float,ObjectType } from "type-graphql";
import { Entity,PrimaryGeneratedColumn,Column,BaseEntity } from "typeorm";

@ObjectType()
@Entity({ name: "locations" })
export class Location extends BaseEntity {
  @Field()
  @PrimaryGeneratedColumn("uuid")
  id: string;

  @Field()
  @Column({ nullable: true })
  placeName?: string;

  @Field()
  @Column({ nullable: true })
  line1?: string;

  @Field()
  @Column({ nullable: true })
  line2?: string;

  @Field()
  @Column({ nullable: true })
  town?: string;

  @Field()
  @Column({ nullable: true })
  county?: string;

  @Field()
  @Column({ nullable: true })
  city?: string;

  @Field()
  @Column({ nullable: true })
  postcode?: string;

  @Field(() => Float)
  @Column({ type: "decimal",precision: 8 })
  latitude: number;

  @Field(() => Float)
  @Column({ type: "decimal",precision: 8 })
  longitude: number;
}

Talent.ts

import { Field,ObjectType } from "type-graphql";
import {
  Entity,BaseEntity,OnetoOne,JoinColumn,ManyToOne,OnetoMany,} from "typeorm";

import { TalentType } from "./TalentType";
import { TalentAnswer } from "./TalentAnswer";
import { Location } from "../Location";
import { User } from "../User";

@ObjectType()
@Entity({ name: "talents" })
export class Talent extends BaseEntity {
  @Field()
  @PrimaryGeneratedColumn("uuid")
  id: string;

  @Field(() => TalentType)
  @OnetoOne(() => TalentType)
  @JoinColumn()
  type: TalentType;

  @Field(() => User)
  @ManyToOne(() => User,(user) => user.talents)
  user: User;

  @Field(() => Location)
  @OnetoOne(() => Location,{ eager: true })
  @JoinColumn()
  location: Location;

  @Field(() => [TalentAnswer])
  @OnetoMany(() => TalentAnswer,(answer) => answer.talent,{
    eager: true,})
  @JoinColumn()
  answers: TalentAnswer[];
}

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".","paths": {
      "@libs/*": ["src/libs/*"]
    }
    "lib": ["ESNext"],"moduleResolution": "node","noUnusedLocals": true,"noUnusedParameters": true,"removeComments": true,"sourceMap": true,"target": "ESNext","module": "Commonjs","isolatedModules": true,"outDir": "lib","types": ["node","reflect-Metadata","aws-lambda"],"allowSyntheticDefaultImports": true,"emitDecoratorMetadata": true,"experimentalDecorators": true
  },"include": ["src/**/*.ts"],"exclude": [
    "node_modules/**/*",".serverless/**/*",".webpack/**/*","_warmup/**/*",".vscode/**/*"
  ]
}

serverless.ts

import type { AWS } from "@serverless/typescript";

const serverlessConfiguration: AWS = {
  service: "api",frameworkVersion: "2",custom: {
    webpack: {
      webpackConfig: "./webpack.config.js",includeModules: true,},stage: "${opt: stage,'dev'}",databaseId: `${RDS_DATABASE_NAME}-db-\${self:custom.stage}`,plugins: ["serverless-webpack","serverless-offline"],provider: {
    name: "aws",runtime: "nodejs12.x",region: "eu-west-2",stage: "${self:custom.stage}",apiGateway: {
      minimumCompressionSize: 1024,shouldStartNameWithService: true,environment: {
      AWS_NODEJS_CONNECTION_REUSE_ENABLED: "1",STAGE: "${self:custom.stage}",RDS_DATABASE_URL: { "Fn::GetAtt": ["RdsDatabase","Endpoint.Address"] },RDS_DATABASE_NAME,RDS_DATABASE_USER,RDS_DATABASE_PASSWORD,lambdaHashingVersion: "20201221",functions: { 
    graphql: {
      handler: 'src/functions/graphql/handler.graphqlHandler',events: [
        {
          http: {
            method: "post",path: "graphql",cors: true,{
          http: {
            method: "get",]
    }
  },resources: {...
  ...}
}

在以下代码上运行 ts-node 时,这绝对没问题:

import { getRepository } from "typeorm";
import { Database } from "./database";
import { Talent } from "./entity/Talent/Talent";

(async () => {
  await new Database().getConnection();

  const repo = getRepository(Talent);
  const talents = await repo.find();
  console.log(talents);
})();

但是当我运行 serverless-offline 并尝试访问 GraphQL 游乐场时,我收到了上述错误

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。