Built Twitter Like App - 14

Add User API

Add file pages/api/users/index.tsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { NextApiRequest, NextApiResponse } from "next";

import prisma from '../../../libs/prismadb';

export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if( req.method !=='GET'){
return res.status(405).end();
}

try{
const users = await prisma.user.findMany({
orderBy:{
createdAt:'desc'
}
});

return res.status(200).json(users);
} catch(error){
console.log(error);
return res.status(400).end();
}
}

Add file pages/api/users/[userId].tsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { NextApiRequest, NextApiResponse } from "next";

import prisma from '../../../libs/prismadb';

export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if( req.method !=='GET'){
return res.status(405).end();
}

try{
const { userId } = req.query;

if ( userId || typeof userId!== 'string' ){
throw new Error('Invalid ID');
};

const existingUser = await prisma.user.findUnique({
where: {
id: Number(userId)
}
});

const followersCount = await prisma.followingId.count({
where: {
id: Number(userId)
}
});

return res.status(200).json( {...existingUser,followersCount });
} catch(error){
console.log(error);
return res.status(400).end();
}
}

Add User Hook

Add file hooks/useUsers.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import useSWR from 'swr';

import fetcher from '../libs/fetcher';

const useUsers = () => {
const {
data,
error,
isLoading,
mutate
} = useSWR('/api/users', fetcher)

return {
data,
error,
isLoading,
mutate
}
};

export default useUsers;

Add file hooks/useUser.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import useSWR from 'swr';

import fetcher from '../libs/fetcher';

const useUser = (userId:string) => {
const {
data,
error,
isLoading,
mutate
} = useSWR('/api/users/${userId}', fetcher)

return {
data,
error,
isLoading,
mutate
}
};

export default useUser;

请我喝杯咖啡吧~

支付宝
微信