NTUEEInfoDep / NTUEECourseMap

A course map website for NTUEE students.
2 stars 28 forks source link

[Backend] Apollo graphql #46

Open ChenBingWei1201 opened 4 months ago

ChenBingWei1201 commented 4 months ago

Maybe I will try to use express & prisma for backend and react-query for frontend, because some unknown problems occurred when I built up my wp final project with apollo server and apollo client. Most of them violate the Rules of Hooks. I haven't found any solution to it.

ChenBingWei1201 commented 4 months ago

By the way, I learn the react-query from this video of building up a food ordering app

ChenBingWei1201 commented 4 months ago

these are the snippets generated by ChatGPT 3.5 for demo only

const prisma = new PrismaClient(); const app = express();

app.use(express.json()); app.use(cors());

interface Post { id: number; title: string; content: string; }

// Get all posts app.get('/api/posts', async (req: Request, res: Response<Post[]>) => { const posts = await prisma.post.findMany(); res.json(posts); });

// Create a new post app.post('/api/posts', async (req: Request, res: Response) => { const { title, content } = req.body; const newPost = await prisma.post.create({ data: { title, content, }, }); res.json(newPost); });

// Update a post app.put('/api/posts/:id', async (req: Request, res: Response) => { const { id } = req.params; const { title, content } = req.body; const updatedPost = await prisma.post.update({ where: { id: parseInt(id) }, data: { title, content, }, }); res.json(updatedPost); });

// Delete a post app.delete('/api/posts/:id', async (req: Request, res: Response<{ message: string }>) => { const { id } = req.params; await prisma.post.delete({ where: { id: parseInt(id) }, }); res.json({ message: 'Post deleted' }); });

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => { console.log(Server running on port ${PORT}); });

- frontend:
```typescript
// src/components/PostList.tsx
import React from 'react';
import { useQuery } from 'react-query';

interface Post {
  id: number;
  title: string;
  content: string;
}

async function fetchPosts(): Promise<Post[]> {
  const response = await fetch('/api/posts');
  if (!response.ok) {
    throw new Error('Failed to fetch posts');
  }
  return response.json();
}

function PostList() {
  const { data: posts, isLoading, isError } = useQuery<Post[]>('posts', fetchPosts);

  if (isLoading) return <div>Loading...</div>;
  if (isError) return <div>Error fetching posts</div>;

  return (
    <div>
      {posts.map(post => (
        <div key={post.id}>
          <h3>{post.title}</h3>
          <p>{post.content}</p>
        </div>
      ))}
    </div>
  );
}

export default PostList;
ChenBingWei1201 commented 3 months ago

I decied to use apollo graphql