import express from "express";
import cors from "cors";
import { PrismaClient } from "@prisma/client";
import { graphqlHTTP } from "express-graphql";
import { makeExecutableSchema } from "@graphql-tools/schema";
export interface Context {
prisma: PrismaClient;
}
const prisma = new PrismaClient();
const typeDefs = `
type User {
id:Int!
name: String
email: String!
}
type Post {
id: Int!
title: String!
content:String!
}
type Query {
allUsers: [User!]!
allPosts: [Post!]!
singleDetail(id:Int): Post!
}
type Mutation {
createPost(
title: String!
content:String!
):Post!
deletePost(
id: Int
):Post!
createUser(
name: String
email:String!
):User!
}
`;
type argsPostType = {
title: string;
content: string;
};
type argsDeletePostType = {
id: number;
};
// type argsDetailPostType = {
// authorId: number;
// id: number;
// title: string;
// content: string;
// };
type argsUserType = {
name: string;
email: string;
};
const resolvers = {
Query: {
allUsers: () => {
return prisma.user.findMany();
},
allPosts: () => {
return prisma.post.findMany();
},
singleDetail: (args:any) => {
return prisma.post.findUnique({
where:{
id:args.post.id
},
select:{
id:true,
title:true,
content:true,
}
})
},
},
Mutation: {
createPost: (parent: any, args: argsPostType, context: any, info: any) => {
const newPost = prisma.post.create({
data: {
title: args.title,
content: args.content,
author: {
connect: {
id: 1,
},
},
published: true,
},
});
return newPost;
},
deletePost: (
parent: any,
args: argsDeletePostType,
context: any,
info: any
) => {
const deletedPost = prisma.user.update({
where: {
id: 1,
},
data: {
posts: {
delete: {
id: args.id,
},
},
},
});
return deletedPost;
},
createUser: (parent: any, args: argsUserType, context: any, info: any) => {
const newUser = prisma.user.create({
data: {
name: args.name,
email: args.email,
},
});
return newUser;
},
},
};
export const schema = makeExecutableSchema({
resolvers,
typeDefs,
});
const app = express();
app.use(cors());
app.use(
"/graphql",
graphqlHTTP({
schema,
graphiql: true,
})
);
if (process.env.NODE_ENV !== "production") {
require("dotenv").config();
}
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`接続完了! ${PORT}.`);
});