GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Windmill Hub
  • Discord
  • Discussions
  • Windmill
  • Login

This view

  • Original page
  • New address

GeezerVison is showing hub.windmill.dev — Search Post — reddit script | Windmill Hub

Back to Reddit integration
0

Search Post

by hugo697
Published Mar 25, 2024

Search posts by title. [See the docs here](https://www.reddit.com/dev/api/#GET_search)

Script reddit Verified
Use in Windmill

The script

Submitted by hugo697 Bun
Verified 571 days ago
All edits
Permalink
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(
12
	resource: Reddit,
13
	subreddit: string,
14
	searchQuery: string,
15
	limit: number
16
) {
17
	const endpoint = `/r/${subreddit}/search`
18
	const params = {
19
		q: searchQuery,
20
		limit: limit
21
	}
22
	return await makeRequest(resource, endpoint, { params })
23
}
24

25
async function makeRequest(resource: Reddit, endpoint: string, options = {}) {
26
	try {
27
		const access_token = await getAccessToken(resource)
28
		const headers = {
29
			Authorization: `Bearer ${access_token}`,
30
			'User-Agent': resource.userAgent
31
		}
32
		const baseUrl = 'https://oauth.reddit.com'
33
		const url = `${baseUrl}${endpoint}`
34
		const response = await axios(url, {
35
			headers,
36
			...options
37
		})
38
		return response.data
39
	} catch (error: Error | any) {
40
		console.error(error.message)
41
	}
42
}
43

44
async function getAccessToken(resource: Reddit) {
45
	try {
46
		const auth = {
47
			username: resource.clientId,
48
			password: resource.clientSecret
49
		}
50
		const response = await axios.post('https://www.reddit.com/api/v1/access_token', null, {
51
			params: { grant_type: 'password', username: resource.username, password: resource.password },
52
			auth
53
		})
54
		return response?.data?.access_token
55
	} catch (error) {
56
		throw new Error('Error getting access token')
57
	}
58
}
59

You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.