Socialify

Folder ..

Viewing exchange-token.ts
57 lines (51 loc) • 1.7 KB

 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import axios from 'axios';
import type { VercelRequest, VercelResponse } from '@vercel/node';

export default async function exchangeAccessToken(req: VercelRequest, res: VercelResponse) {
  if (req.method !== 'POST') {
    res.status(405).send('Method Not Allowed');
    return;
  }

  const { code } = req.body;
  if (!code) {
    return res.status(400).send('Authorization code is required');
  }

  const payload = {
    client_id: process.env.VITE_CLIENT_ID,
    client_secret: process.env.VITE_CLIENT_SECRET,
    code,
    grant_type: 'authorization_code',
    redirect_uri: process.env.VITE_REDIRECT_URI,
  };

  const url = 'https://anilist.co/api/v2/oauth/token';

  try {
    const response = await axios.post(url, payload, {
      headers: {
        'Content-Type': 'application/json',
        'Accept-Encoding': 'identity',
      },
    });

    if (response.data.access_token) {
      res.json({ accessToken: response.data.access_token });
    } else {
      throw new Error('Access token not found in the response');
    }
  } catch (error: unknown) {
    // First, check if it's an instance of Error
    if (error instanceof Error) {
      // Now you can safely read the message property
      const message = error.message;
      // If it's an axios error, it may have a response object
      const details = axios.isAxiosError(error) && error.response ? error.response.data : message;
      res.status(500).json({
        error: 'Failed to exchange token',
        details,
      });
    } else {
      // If it's not an Error object, handle it as a generic error
      res.status(500).json({
        error: 'Failed to exchange token',
        details: 'An unknown error occurred',
      });
    }
  }
}