使用GraphQL、Reaction和Prisma,我只能创建一个ID为UUID的用户,并创建一个包含与该用户相关的所有输入数据的嵌套对象数组。我的目标是在Reaction中显示与用户相关的所有输入数据。如何通过突变创建该用户?
我的代码是:
Schema.graphql
type Query {
info: String!
feed: [Inputdata!]!
user(id:ID!): User!
}
type Mutation {
post(question: String!, answer: String!): Inputdata!
createuser(id: String!): User!
}
type Inputdata {
id: ID!
question: String!
answer: String!
enteredById: String!
}
type User{
id:ID!
data: [Inputdata]
}
Index.js
const fs = require('fs');
const path = require('path');
const { ApolloServer } = require('apollo-server');
const { PrismaClient } = require('@prisma/client');
const resolvers = {
Query: {
info: () => `This is the API of the Questionaire app`,
feed: async (parent, args, context) => {
return context.prisma.inputdata.findMany();
},
user: async (parent, args, context, info) => {
if(!args.id){
throw new Error('id required')
}
return context.prisma.users.find(user => user.id === +args.id)
}
},
User: {
data(parent, args, context, info){
//parent is the root object (User is the parent here)
return context.prisma.data.filter(data => data.userid === parent.id)
}
},
Mutation: {
post: (parent, args, context, info) => {
let newInputData = context.prisma.inputdata.create({
data: {
question: args.question,
answer: args.answer,
},
})
return newInputData
},
createuser: (context) => {
let newUser = context.prisma.users.create({
data: {
// need to fill with data? just want to create user-object with uuid
}
})
return newUser
}
}
}
const prisma = new PrismaClient()
const server = new ApolloServer({
typeDefs: fs.readFileSync(
path.join(__dirname, 'schema.graphql'),
'utf8'
),
resolvers,
context: {
prisma,
}
})
server
.listen()
.then(({ url }) =>
console.log(`Server is running on ${url}`)
);
Schema.prisma
datasource db {
provider = "sqlite"
url = "file:./dev.db"
}
generator client {
provider = "prisma-client-js"
}
model Inputdata {
id String @unique
createdAt DateTime @default(now())
question String
answer String
enteredBy User? @relation(fields: [enteredById], references: [id])
enteredById String?
}
model User {
id String @id @unique
Inputdata Inputdata[]
}
1条答案
按热度按时间i7uq4tfw1#
您是否尝试在用户之前创建inputdata?然后,您必须在创建用户之后创建另一个变体,以使用用户id更新输入。
但最好是在输入数据中创建用户突变(如果用户不存在,则使用
connectOrCreate
)。取决于您的用例。