-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.ts
106 lines (99 loc) · 2.61 KB
/
index.ts
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import axios, { AxiosRequestConfig } from "axios"
interface Answer {
text: string
attachments: string[]
}
interface Result {
question: string
attachments: string[]
answers: Answer[]
}
interface FinalResult {
status: string
total: number
result: Result[] | string
}
/**
* Class that only contain one function to get data from brainly site
*/
export default class Brainly {
/**
* Static function to get data from brainly site with the provided keyword and limit
* @param {string} query Keyword that is used to get data from brainly
* @param {limit} limit Data limit that is returned, default to 10
* @return {Promise<FinalResult>} Object with property of status, counts, and data
*/
static async getData(
query: string,
limit: number = 10
): Promise<FinalResult> {
const graphqlQuery: string = `query SearchQuery($query: String!, $first: Int!, $after: ID) {
questionSearch(query: $query, first: $first, after: $after) {
edges {
node {
content
attachments{
url
}
answers {
nodes {
content
attachments{
url
}
}
}
}
}
}
}`
const config: AxiosRequestConfig = {
url: "https://brainly.com/graphql/id",
method: "POST",
headers: {
host: "brainly.com",
"Content-Type": "application/json; charset=utf-8",
"User-Agent":
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:65.0) Gecko/20100101 Firefox/65.0"
},
data: {
operationName: "SearchQuery",
variables: {
query: query,
after: null,
first: limit
},
query: graphqlQuery
}
}
try {
const response = await axios.request(config)
const { edges } = await response.data.data.questionSearch
const results: Result[] = edges.map((edge: any) => ({
question: edge.node.content.replace(/(<br \/>)/gi, "\n"),
attachments: edge.node.attachments,
answers: edge.node.answers.nodes.map((node: any) => ({
text: node.content
.replace(/(<br \/>)/gi, "\n")
.replace(/(<([^>]+)>)/gi, ""),
attachments: node.attachments
}))
}))
return new Promise(resolve =>
resolve({
status: "Success",
total: results.length,
result: results.length ? results : "Didn't find any result"
})
)
} catch (err) {
return new Promise((_, reject) => {
reject({
status: "Error",
total: 0,
result: err.message
})
})
}
}
}