1 | import axios from 'axios' |
2 |
|
3 | type Reddit = { |
4 | clientId: string |
5 | clientSecret: string |
6 | username: string |
7 | password: string |
8 | userAgent?: string |
9 | } |
10 |
|
11 | export async function main(resource: Reddit, subreddit: string, article: string) { |
12 | try { |
13 | const endpoint = `/r/${subreddit}/comments/${article}` |
14 | return await makeRequest(resource, endpoint) |
15 | } catch (error) { |
16 | console.error('Error getting comments:') |
17 | } |
18 | } |
19 |
|
20 | async function makeRequest(resource: Reddit, endpoint: string, options = {}) { |
21 | try { |
22 | const access_token = await getAccessToken(resource) |
23 | const headers = { |
24 | Authorization: `Bearer ${access_token}`, |
25 | 'User-Agent': resource.userAgent |
26 | } |
27 | const baseUrl = 'https://oauth.reddit.com' |
28 | const url = `${baseUrl}${endpoint}` |
29 | const response = await axios(url, { |
30 | headers, |
31 | ...options |
32 | }) |
33 | return response.data |
34 | } catch (error: Error | any) { |
35 | console.error(error.message) |
36 | } |
37 | } |
38 |
|
39 | async function getAccessToken(resource: Reddit) { |
40 | try { |
41 | const auth = { |
42 | username: resource.clientId, |
43 | password: resource.clientSecret |
44 | } |
45 | const response = await axios.post('https://www.reddit.com/api/v1/access_token', null, { |
46 | params: { grant_type: 'password', username: resource.username, password: resource.password }, |
47 | auth |
48 | }) |
49 | return response?.data?.access_token |
50 | } catch (error) { |
51 | throw new Error('Error getting access token') |
52 | } |
53 | } |
54 |
|