【问题标题】:How can i get all data from server by apollo-server by nodejs我如何通过 nodejs 通过 apollo-server 从服务器获取所有数据
【发布时间】:2021-12-10 05:28:15
【问题描述】:

我想获取参与者、提议、用户等所有数据。

产品包括建议。 建议包括参与者。

如果我使用查询,我想获取所有数据, 测试查询仅显示 userId,但我想要有关用户的所有信息 测试查询仅显示proposalId,但我想要关于proposal的所有信息

棱镜模型

model Product {
  id       Int       @id @default(autoincrement())
  prodName String
  prodCode String
  posts    Post[]
  holdings Holding[]
  proposes Propose[]
}
model Propose {
  id           Int           @id @default(autoincrement())
  user         User          @relation(fields: [userId], references: [id])
  userId       Int
  product      Product       @relation(fields: [productId], references: [id])
  productId    Int
  title        String
  content      String
  totalAmt     Int
  participants Participant[]
  createdAt    DateTime      @default(now())
}
model Participant {
  id             Int      @id @default(autoincrement())
  user           User     @relation(fields: [userId], references: [id])
  userId         Int
  propose        Propose  @relation(fields: [proposeId], references: [id])
  proposeId      Int
  amt            Int
  participatedAt DateTime @default(now())
}

类型

type Participant {
    id: Int!
    user: User
    propose: Propose
    amt: Int
    participatedAt: String
  }
  type seeParticipantResult {
    ok: Boolean!
    participants: [Participant]
    error: String
  }
  type Query {
    seeParticipant: seeParticipantResult
  }

查询

export default {
  Query: {
    seeParticipant: async (_, __, { loggedInUser }) => {
      try {
        const participants = await client.participant.findMany({
          where: {
            userId: loggedInUser.id,
          },
        });
        return {
          ok: true,
          participants,
        };
      } catch (e) {
        return {
          ok: false,
          error: e,
        };
      }
    },
  },
};

测试查询

query Query {
  seeParticipant {
    ok
    participants {
      id
      user {
        username
      }
      propose {
        product {
          prodName
          prodCode
        }
        title
      }
    }
  }
}

结果

  "data": {
    "seeParticipant": {
      "ok": true,
      "participants": [
        {
          "id": 1,
          "user": null,
          "propose": null
        }
      ]
    }
  }
}

它不显示提议和用户。

【问题讨论】:

  • 您有 Participant.propose 的解析器吗?您的解析器正在返回参与者,但没有返回任何加入的关系。

标签: node.js graphql apollo-server prisma


【解决方案1】:

Prisma 不会通过查询自动返回 relation 对象。使用 GraphQL 时,您应该为任何关系字段(例如 GraphQL Schema 中的Participant.user)创建单独的解析器函数。

Participant.user 的解析器可能看起来像这样:

  Participant: {
    user: (parent, args, context) => {
      return client.participant.findUnique({where: {id: parent.id}}).user()
    }
  }

我正在使用 Prisma fluent APIfindUnique 查询 participant 获取连接的 user

请注意,您需要为 Propose 执行类似的操作。

【讨论】:

    猜你喜欢
    • 2016-12-08
    • 2018-10-30
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-05
    • 1970-01-01
    相关资源
    最近更新 更多