Skip to content

Commit

Permalink
Merge pull request #40 from ArkeeAgency/antoinekm/api-doc
Browse files Browse the repository at this point in the history
add documentation comments
  • Loading branch information
goenning committed Mar 18, 2024
2 parents 12eb837 + f0926a6 commit 7d58b72
Show file tree
Hide file tree
Showing 9 changed files with 120 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/nervous-carrots-complain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"google-indexing-script": patch
---

Add documentation comments
25 changes: 24 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ You can read more about the motivation behind it and how it works in this blog p
2. Make sure you enable both [`Google Search Console API`](https://console.cloud.google.com/apis/api/searchconsole.googleapis.com) and [`Web Search Indexing API`](https://console.cloud.google.com/apis/api/indexing.googleapis.com) on your [Google Project ➤ API Services ➤ Enabled API & Services](https://console.cloud.google.com/apis/dashboard).
3. [Download the JSON](https://github.com/goenning/google-indexing-script/issues/2) file with the credentials of your service account and save it in the same folder as the script. The file should be named `service_account.json`


## Installation

### Using CLI
Expand Down Expand Up @@ -111,6 +110,30 @@ gis seogets.com --client-email your-client-email --private-key your-private-key
```
</details>

<details>
<summary>As a npm module</summary>

You can also use the script as a [npm module](https://www.npmjs.com/package/google-indexing-script) in your own project.

```bash
npm i google-indexing-script
```

```javascript
import { index } from 'google-indexing-script'
import serviceAccount from './service_account.json'

index('seogets.com', {
client_email: serviceAccount.client_email,
private_key: serviceAccount.private_key
})
.then(console.log)
.catch(console.error)
```

Read the [API documentation](https://paka.dev/npm/google-indexing-script) for more details.
</details>

Here's an example of what you should expect:

![](./output.png)
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"cli",
"typescript"
],
"license": "MIT",
"scripts": {
"index": "ts-node ./src/cli.ts",
"build": "tsup",
Expand Down
10 changes: 9 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,15 @@ export type IndexOptions = {
path?: string;
};

export const index = async (input: string = process.argv[2], options: IndexOptions = {}) => {
/**
* Indexes the specified domain or site URL.
* @param input - The domain or site URL to index.
* @param options - (Optional) Additional options for indexing.
*/
export const index = async (
input: string = process.argv[2],
options: IndexOptions = {},
) => {
if (!input) {
console.error("❌ Please provide a domain or site URL as the first argument.");
console.error("");
Expand Down
7 changes: 7 additions & 0 deletions src/shared/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ import fs from "fs";
import path from "path";
import os from "os";

/**
* Retrieves an access token for Google APIs using service account credentials.
* @param client_email - The client email of the service account.
* @param private_key - The private key of the service account.
* @param customPath - (Optional) Custom path to the service account JSON file.
* @returns The access token.
*/
export async function getAccessToken(client_email?: string, private_key?: string, customPath?: string) {
if (!client_email && !private_key) {
const filePath = "service_account.json";
Expand Down
33 changes: 33 additions & 0 deletions src/shared/gsc.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,34 @@
import { Status } from "./types";
import { fetchRetry } from "./utils";

/**
* Converts a given input string to a valid Google Search Console site URL format.
* @param input - The input string to be converted.
* @returns The converted site URL (domain.com or https://domain.com/)
*/
export function convertToSiteUrl(input: string) {
if (input.startsWith("http://") || input.startsWith("https://")) {
return input.endsWith("/") ? input : `${input}/`;
}
return `sc-domain:${input}`;
}

/**
* Converts a given file path to a formatted version suitable for use as a file name.
* @param path - The url to be converted as a file name
* @returns The converted file path
*/
export function convertToFilePath(path: string) {
return path.replace("http://", "http_").replace("https://", "https_").replace("/", "_");
}

/**
* Retrieves the indexing status of a page.
* @param accessToken - The access token for authentication.
* @param siteUrl - The URL of the site.
* @param inspectionUrl - The URL of the page to inspect.
* @returns A promise resolving to the status of indexing.
*/
export async function getPageIndexingStatus(
accessToken: string,
siteUrl: string,
Expand Down Expand Up @@ -58,6 +75,11 @@ export async function getPageIndexingStatus(
}
}

/**
* Retrieves an emoji representation corresponding to the given status.
* @param status - The status for which to retrieve the emoji.
* @returns The emoji representing the status.
*/
export function getEmojiForStatus(status: Status) {
switch (status) {
case Status.SubmittedAndIndexed:
Expand All @@ -78,6 +100,12 @@ export function getEmojiForStatus(status: Status) {
}
}

/**
* Retrieves metadata for publishing from the given URL.
* @param accessToken - The access token for authentication.
* @param url - The URL for which to retrieve metadata.
* @returns The status of the request.
*/
export async function getPublishMetadata(accessToken: string, url: string) {
const response = await fetchRetry(
`https://indexing.googleapis.com/v3/urlNotifications/metadata?url=${encodeURIComponent(url)}`,
Expand Down Expand Up @@ -114,6 +142,11 @@ export async function getPublishMetadata(accessToken: string, url: string) {
return response.status;
}

/**
* Requests indexing for the given URL.
* @param accessToken - The access token for authentication.
* @param url - The URL to be indexed.
*/
export async function requestIndexing(accessToken: string, url: string) {
const response = await fetchRetry("https://indexing.googleapis.com/v3/urlNotifications:publish", {
method: "POST",
Expand Down
12 changes: 12 additions & 0 deletions src/shared/sitemap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@ import Sitemapper from "sitemapper";
import { fetchRetry } from "./utils";
import { webmasters_v3 } from "googleapis";

/**
* Retrieves a list of sitemaps associated with the specified site URL from the Google Webmasters API.
* @param accessToken The access token for authentication.
* @param siteUrl The URL of the site for which to retrieve the list of sitemaps.
* @returns An array containing the paths of the sitemaps associated with the site URL.
*/
async function getSitemapsList(accessToken: string, siteUrl: string) {
const url = `https://www.googleapis.com/webmasters/v3/sites/${encodeURIComponent(siteUrl)}/sitemaps`;

Expand Down Expand Up @@ -34,6 +40,12 @@ async function getSitemapsList(accessToken: string, siteUrl: string) {
return body.sitemap.filter((x) => x.path !== undefined && x.path !== null).map((x) => x.path as string);
}

/**
* Retrieves a list of pages from all sitemaps associated with the specified site URL.
* @param accessToken The access token for authentication.
* @param siteUrl The URL of the site for which to retrieve the sitemap pages.
* @returns An array containing the list of sitemaps and an array of unique page URLs extracted from those sitemaps.
*/
export async function getSitemapPages(accessToken: string, siteUrl: string) {
const sitemaps = await getSitemapsList(accessToken, siteUrl);

Expand Down
3 changes: 3 additions & 0 deletions src/shared/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
/**
* Enum representing indexing status of a URL
*/
export enum Status {
SubmittedAndIndexed = "Submitted and indexed",
DuplicateWithoutUserSelectedCanonical = "Duplicate without user-selected canonical",
Expand Down
26 changes: 26 additions & 0 deletions src/shared/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
/**
* Creates an array of chunks from the given array with a specified size.
* @param arr The array to be chunked.
* @param size The size of each chunk.
* @returns An array of chunks.
*/
const createChunks = (arr: any[], size: number) =>
Array.from({ length: Math.ceil(arr.length / size) }, (_, i) => arr.slice(i * size, i * size + size));

/**
* Executes tasks on items in batches and invokes a callback upon completion of each batch.
* @param task The task function to be executed on each item.
* @param items The array of items on which the task is to be executed.
* @param batchSize The size of each batch.
* @param onBatchComplete The callback function invoked upon completion of each batch.
*/
export async function batch(
task: (url: string) => void,
items: string[],
Expand All @@ -14,6 +27,14 @@ export async function batch(
}
}

/**
* Fetches a resource from a URL with retry logic.
* @param url The URL of the resource to fetch.
* @param options The options for the fetch request.
* @param retries The number of retry attempts (default is 5).
* @returns A Promise resolving to the fetched response.
* @throws Error when retries are exhausted or server error occurs.
*/
export async function fetchRetry(url: string, options: RequestInit, retries: number = 5) {
try {
const response = await fetch(url, options);
Expand All @@ -30,6 +51,11 @@ export async function fetchRetry(url: string, options: RequestInit, retries: num
}
}

/**
* Parses command-line arguments and returns key-value pairs.
* @param argv The array of command-line arguments.
* @returns An object containing parsed key-value pairs.
*/
export function parseCommandLineArgs(argv: string[]) {
const parsedArgs: { [key: string]: string } = {};

Expand Down

0 comments on commit 7d58b72

Please sign in to comment.