UNPKG

@azteam/google-api

Version:

N/A

114 lines (99 loc) 3.24 kB
import HttpClient from '@azteam/http-client'; import GoogleOAuth2API from './GoogleOAuth2API'; import {SEARCH_CONSOLE_SCOPE} from './scope'; const SEARCH_CONSOLE_ENDPOINT = 'https://www.googleapis.com/webmasters/v3/sites'; class GoogleSearchConsoleAPI extends GoogleOAuth2API { siteUrl = null; constructor(accountType, credential, domain, options = {}) { super( accountType, { ...credential, scope: SEARCH_CONSOLE_SCOPE, }, options ); this.siteUrl = `https://${domain}/`; this.apiKey = credential.api_key; } getAuthLink(redirectURI, state, arrayScope = [SEARCH_CONSOLE_SCOPE]) { return super.getAuthLink(redirectURI, state, arrayScope); } async hasScope(arrayScope = [SEARCH_CONSOLE_SCOPE]) { return super.hasScope(arrayScope); } async searchAnalytics(startDate, endDate, options = {}) { const client = await this._getAuthClient(), res = await client.post( `${SEARCH_CONSOLE_ENDPOINT}/${encodeURIComponent(this.siteUrl)}/searchAnalytics/query`, { startDate, endDate, ...options, }, false ); if (res.error) { throw new Error(res.error.message); } if (res.rows) { return res.rows; } return null; } async submitSitemap(sitemapUrl) { const client = await this._getAuthClient(), res = await client.put( `${SEARCH_CONSOLE_ENDPOINT}/${encodeURIComponent(this.siteUrl)}/sitemaps/${encodeURIComponent(sitemapUrl)}`, {}, false ); if (res.error) { throw new Error(res.error.message); } return true; } async indexInspect(inspectionUrl) { const client = await this._getAuthClient(), res = await client.post( 'https://searchconsole.googleapis.com/v1/urlInspection/index:inspect', { siteUrl: this.siteUrl, inspectionUrl, }, false ); if (res.error) { throw new Error(res.error.message); } if (res.inspectionResult) { return res.inspectionResult; } return res; } async testMobileFriendly(url) { const clientOptions = { timeout: 120000, }; if (this.proxy) { clientOptions.proxy = this.proxy; } const client = new HttpClient(clientOptions), res = await client.post( `https://searchconsole.googleapis.com/v1/urlTestingTools/mobileFriendlyTest:run?key=${this.apiKey}`, { url, requestScreenshot: true, }, false ); if (res.error) { throw new Error(res.error.message); } if (res.mobileFriendliness) { return res; } return null; } } export default GoogleSearchConsoleAPI;