All files / src index.ts

100% Statements 42/42
100% Branches 8/8
100% Functions 4/4
100% Lines 37/37

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 751x 1x 1x 1x 1x 1x 1x 1x 1x 1x       2x               2x 2x 2x 2x 2x 2x             2x 2x         1x 2x 2x   2x     1x 121x 121x 121x   121x           121x 3x 3x     118x 118x 1x     118x   3x       1x  
import { Serp } from "./SERP";
import { Logger } from "./helpers/logger";
import { KeywordsData } from "./keywords_data";
import { TrafficAnalytics } from "./traffic_analytics";
import { Appendix } from "./appendix";
import fetch from "node-fetch";
import { DataForSEOLabs } from "./DataForSEO_labs";
import { OnPage } from "./OnPage";
export * from "./typings";
export class DFSEO {
	/**
	 * Logger  of dfseo
	 */
	private logger: Logger = new Logger();
	/**
	 * Authorization  of dfseo api
	 */
	private authorization: string;
	/**
	 * public api methods;
	 */
	public serp: Serp = new Serp(this);
	public onPage: OnPage = new OnPage(this);
	public keywordsData: KeywordsData = new KeywordsData(this);
	public dataForSEOLabs: DataForSEOLabs = new DataForSEOLabs(this);
	public trafficAnalytics: TrafficAnalytics = new TrafficAnalytics(this);
	public appendix: Appendix = new Appendix(this);
 
	/**
	 * Creates an instance of dfseo api.
	 * @param username
	 * @param password
	 */
	constructor(private username: string, private password: string, private useSandbox?: boolean) {
		this.authorization = this.generateAuthorizationString();
	}
	/**
	 * Generates authorization string
	 */
	private generateAuthorizationString(): string {
		const stringToEncode: string = `${this.username}:${this.password}`;
		let base64 = Buffer.from(stringToEncode).toString("base64");
 
		return `Basic ${base64}`;
	}
 
	public async fetch(config: { url: string; method: "GET" | "POST"; data?: any }): Promise<any> {
		const authorization = this.authorization;
		const baseURL = this.useSandbox ? "https://sandbox.dataforseo.com/v3/" : "https://api.dataforseo.com/v3/";
		const headers = { authorization, "Content-Type": "application/json" };
		try {
			const response = await fetch(baseURL + config.url, {
				method: config.method,
				body: JSON.stringify(config.data),
				headers,
			});
 
			if (response.status !== 200) {
				this.logger.error(response.status, response.statusText);
				throw response.statusText;
			}
 
			const data = await response.json();
			if (data.status_code !== 20000 && data.status_code !== 20100) {
				this.logger.error(data.status_code, data.status_message);
			}
 
			return data;
		} catch (e) {
			console.log(e);
		}
		// error handling
	}
}