Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

users.$userId.ts

31 lines881 Bytes

1import { createFileRoute } from '@tanstack/react-router'
2import type { User } from '~/utils/users'
3​
4export const Route = createFileRoute('/api/users/$userId')({
5 server: {
6 handlers: {
7 GET: async ({ params, request }) => {
8 console.info(`Fetching users by id=${params.userId}... @`, request.url)
9 try {
10 const res = await fetch(
11 'https://jsonplaceholder.typicode.com/users/' + params.userId,
12 )
13 if (!res.ok) {
14 throw new Error('Failed to fetch user')
15 }
16​
17 const user = (await res.json()) as User
18​
19 return Response.json({
20 id: user.id,
21 name: user.name,
22 email: user.email,
23 })
24 } catch (e) {
25 console.error(e)
26 return Response.json({ error: 'User not found' }, { status: 404 })
27 }
28 },
29 },
30 },
31})