首页 > 解决方案 > 我如何通过 nodejs 通过 apollo-server 从服务器获取所有数据

问题描述

我想获取所有数据,例如参与者、建议、用户。

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

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

棱镜模型

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
        }
      ]
    }
  }
}

它没有显示建议和用户。

标签: node.jsgraphqlapollo-serverprisma

解决方案


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

这就是解析器的样子Participant.user

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

我正在使用Prisma fluent API从.userfindUniqueparticipant

请注意,您需要为Propose.


推荐阅读