-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrank-checker.service.ts
57 lines (52 loc) · 1.56 KB
/
rank-checker.service.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
import { Injectable } from '@nestjs/common';
import axios from 'axios';
import * as cheerio from 'cheerio';
@Injectable()
export class RankCheckerService {
async checkRank(url: string, keyword: string): Promise<number> {
try {
const searchUrl = `https://www.google.com/search?q=${encodeURIComponent(
keyword,
)}`;
const { data } = await axios.get(searchUrl);
const $ = cheerio.load(data);
let rank = -1;
$('a').each((index, element) => {
const link = $(element).attr('href');
if (link && link.includes(url)) {
rank = index + 1;
return false;
}
});
return rank;
} catch (error) {
throw new Error('Error fetching rank data');
}
}
async getKeywords(url: string): Promise<string[]> {
try {
const { data } = await axios.get(url);
const $ = cheerio.load(data);
const keywords = [];
$('meta[name="keywords"]').each((index, element) => {
const content = $(element).attr('content');
if (content) {
keywords.push(...content.split(',').map((keyword) => keyword.trim()));
}
});
if (keywords.length === 0) {
$('meta[name="description"]').each((index, element) => {
const content = $(element).attr('content');
if (content) {
keywords.push(
...content.split(' ').map((keyword) => keyword.trim()),
);
}
});
}
return keywords;
} catch (error) {
throw new Error('Error fetching keywords');
}
}
}