Free preview
Add Bundle queries and mutations
Part of End to End React with Prisma 2
Objective: Create all of the bundle queries and the create mutation.
Let’s add the createBundle mutation as well as the bundle and bundles queries. These will seem pretty similar to the feeds queries and mutations that we’ve already made.
utils/api/typeDefs.ts
import { gql } from 'apollo-server-micro'
export const typeDefs = gql`
type Feed {
id: String
name: String
url: String
}
type Bundle {
id: String
name: String
description: String
}
input FeedInput {
id: String
}
input BundleInput {
id: String
}
input FeedCreateInput {
id: String
url: String
name: String
}
input BundleCreateInput {
id: String
name: String
description: String
}
type Query {
hello: String
feed(data: FeedInput): Feed
bundle(data: BundleInput): Bundle
feeds: [Feed]
bundles: [Bundle]
}
type Mutation {
createFeed(data: FeedCreateInput): Feed
createBundle(data: BundleCreateInput): Bundle
}
`
utils/api/resolvers.ts
export const resolvers = {
Query: {
hello: (parent, args, context) => `hi!`,
feed: (parent, { data: { id } }, { prisma }) =>
prisma.feed.findOne({ where: { id } }),
bundle: (parent, { data: { id } }, { prisma }) =>
prisma.bundle.findOne({ where: { id } }),
feeds: (parent, args, { prisma }) => prisma.feed.findMany(),
bundles: (parent, args, { prisma }) => prisma.bundle.findMany(),
},
Mutation: {
createFeed: async (parent, { data }, { prisma, user }) => {
const result = await prisma.feed.create({ data: { ...data } })
return result
},
createBundle: async (parent, { data }, { prisma, user }) => {
const result = await prisma.bundle.create({
data: { ...data },
})
return result
},
},
}
Let’s try the createBundle mutation:
mutation createBundleMutation($data: BundleCreateInput) {
createBundle(data: $data) {
...BundleFragment
}
}
fragment BundleFragment on Bundle {
id
name
description
}
Variables
{
"data": {
"name": "My bundle",
"description": "This bundle is about fun stuff",
"id": "1"
}
}
Next, we can run a bundles and bundle query to make sure it works:
{
bundles {
id
name
description
}
}
query bundleQuery($data: BundleInput) {
bundle(data: $data) {
...BundleFragment
}
}
fragment BundleFragment on Bundle {
id
name
description
}
{
"data": { "id": "1" }
}
Ensure that they return the bundle that we just created either as an array or a single object.