ChemPal Documentation - v0.0.13-beta.5
    Preparing search index...

    Class Pubchem

    A utility class for interacting with the PubChem API to retrieve chemical compound information.

    This class provides methods to search for compounds, retrieve their CID (Compound ID), and query detailed molecular properties using PubChem's SDQ (Structure Data Query) agent.

    const pubchem = new Pubchem("2-Acetoxybenzenecarboxylic acid");
    console.log("Result:", await pubchem.getSimpleName());
    // Result: Aspirin
    export class Pubchem {
    /** Base URL for PubChem API endpoints */
    private readonly baseURL = "https://pubchem.ncbi.nlm.nih.gov";

    /**
    * Creates a new Pubchem instance for querying compound information
    * @param query - The chemical compound name or identifier to search for
    * @source
    */
    constructor(private readonly query: string) {
    this.query = query;
    }

    /**
    * Retrieves the first matching compound name from PubChem's autocomplete API
    * @returns Promise resolving to the first matching compound name
    *
    * @example
    * ```typescript
    * const compound = await pubchem.getCompound();
    * console.log(compound); // "aspirin"
    * ```
    * @source
    */
    async getCompound(): Promise<string | undefined> {
    try {
    const response = await fetch(
    `${this.baseURL}/rest/autocomplete/compound/${encodeURIComponent(this.query)}`,
    );
    const data = await response.json();
    assertIsCompoundResponseResponse(data);
    return data.dictionary_terms.compound[0];
    } catch (error) {
    console.error("Error fetching compound:", error);
    }
    }

    /**
    * Retrieves the CID (Compound ID) for the compound by first getting the compound name
    * and then looking up its CID
    * @returns Promise resolving to the Compound ID (CID)
    *
    * @example
    * ```typescript
    * const cid = await pubchem.getCID();
    * console.log(cid); // 2244
    * ```
    * @source
    */
    async getCID(): Promise<number | undefined> {
    try {
    const compound = await this.getCompound();
    if (!compound) return undefined;
    const response = await fetch(
    `${this.baseURL}/rest/pug/concepts/name/JSON?name=${encodeURIComponent(compound)}`,
    );
    const data = await response.json();
    assertIsCIDResponse(data);
    return data.ConceptsAndCIDs.CID[0];
    } catch (error) {
    console.error("Error fetching CID:", error);
    }
    }

    /**
    * Queries PubChem's SDQ (Structure Data Query) agent to retrieve detailed molecular properties
    * @returns Promise resolving to the SDQ response containing detailed compound data
    *
    * @example
    * ```typescript
    * const sdqData = await pubchem.querySdqAgent();
    * console.log(sdqData.SDQOutputSet[0].rows[0].mw); // Molecular weight
    * ```
    * @source
    */
    async querySdqAgent(sdqQuery: SDQQuery): Promise<SDQResponse | undefined> {
    try {
    const sdqAgentQuery = {
    select: "*",
    collection: "compound",
    order: ["cid,asc"],
    start: 1,
    limit: 10,
    where: { ands: [sdqQuery] },
    width: 1000000,
    listids: 0,
    };
    console.debug({ sdqAgentQuery });
    const queryURL = JSON.stringify(sdqAgentQuery).replace(/"/g, "%22").replace(/ /g, "%20");

    console.debug(
    `Querying URL: ${this.baseURL}/sdq/sdqagent.cgi?infmt=json&outfmt=json&query=${queryURL}`,
    );
    const response = await fetch(
    `${this.baseURL}/sdq/sdqagent.cgi?infmt=json&outfmt=json&query=${queryURL}`,
    );
    const data = await response.json();
    assertIsSdqAgentResponse(data);
    return data;
    } catch (error) {
    console.error("Error querying SDQ agent:", error);
    }
    }

    /**
    * Retrieves the simple compound name from the SDQ agent query results
    * @returns Promise resolving to the compound name
    *
    * @example
    * ```typescript
    * const name = await pubchem.getSimpleName();
    * console.log(name); // "2-acetyloxybenzoic acid"
    * ```
    * @source
    */
    async getSimpleName(): Promise<string | undefined> {
    try {
    const cid = await this.getCID();
    if (!cid) return undefined;
    const data = await this.querySdqAgent({ cid });
    if (!data) return undefined;
    return data.SDQOutputSet[0].rows[0].cmpdname;
    } catch (error) {
    console.error("Error fetching simple name:", error);
    }
    }

    /**
    * Retrieves the compound name from the SDQ agent query results
    * @returns Promise resolving to the compound name
    *
    * @example
    * ```typescript
    * const name = await pubchem.getCompoundNameFromAlias("aspirin");
    * ```
    * @source
    */
    async getCompoundNameFromAlias(cmpdsynonym: string): Promise<string | undefined> {
    try {
    const data = await this.querySdqAgent({ cmpdsynonym });
    if (!data) return undefined;
    return data.SDQOutputSet[0].rows[0].cmpdname;
    } catch (error) {
    console.error("Error fetching compound name from alias:", error);
    }
    }
    }
    Index

    Constructors

    • Creates a new Pubchem instance for querying compound information

      Parameters

      • query: string

        The chemical compound name or identifier to search for

      Returns Pubchem

    Methods

    • Retrieves the first matching compound name from PubChem's autocomplete API

      Returns Promise<undefined | string>

      Promise resolving to the first matching compound name

      const compound = await pubchem.getCompound();
      console.log(compound); // "aspirin"
        async getCompound(): Promise<string | undefined> {
      try {
      const response = await fetch(
      `${this.baseURL}/rest/autocomplete/compound/${encodeURIComponent(this.query)}`,
      );
      const data = await response.json();
      assertIsCompoundResponseResponse(data);
      return data.dictionary_terms.compound[0];
      } catch (error) {
      console.error("Error fetching compound:", error);
      }
      }
    • Retrieves the CID (Compound ID) for the compound by first getting the compound name and then looking up its CID

      Returns Promise<undefined | number>

      Promise resolving to the Compound ID (CID)

      const cid = await pubchem.getCID();
      console.log(cid); // 2244
        async getCID(): Promise<number | undefined> {
      try {
      const compound = await this.getCompound();
      if (!compound) return undefined;
      const response = await fetch(
      `${this.baseURL}/rest/pug/concepts/name/JSON?name=${encodeURIComponent(compound)}`,
      );
      const data = await response.json();
      assertIsCIDResponse(data);
      return data.ConceptsAndCIDs.CID[0];
      } catch (error) {
      console.error("Error fetching CID:", error);
      }
      }
    • Queries PubChem's SDQ (Structure Data Query) agent to retrieve detailed molecular properties

      Parameters

      Returns Promise<undefined | SDQResponse>

      Promise resolving to the SDQ response containing detailed compound data

      const sdqData = await pubchem.querySdqAgent();
      console.log(sdqData.SDQOutputSet[0].rows[0].mw); // Molecular weight
        async querySdqAgent(sdqQuery: SDQQuery): Promise<SDQResponse | undefined> {
      try {
      const sdqAgentQuery = {
      select: "*",
      collection: "compound",
      order: ["cid,asc"],
      start: 1,
      limit: 10,
      where: { ands: [sdqQuery] },
      width: 1000000,
      listids: 0,
      };
      console.debug({ sdqAgentQuery });
      const queryURL = JSON.stringify(sdqAgentQuery).replace(/"/g, "%22").replace(/ /g, "%20");

      console.debug(
      `Querying URL: ${this.baseURL}/sdq/sdqagent.cgi?infmt=json&outfmt=json&query=${queryURL}`,
      );
      const response = await fetch(
      `${this.baseURL}/sdq/sdqagent.cgi?infmt=json&outfmt=json&query=${queryURL}`,
      );
      const data = await response.json();
      assertIsSdqAgentResponse(data);
      return data;
      } catch (error) {
      console.error("Error querying SDQ agent:", error);
      }
      }
    • Retrieves the simple compound name from the SDQ agent query results

      Returns Promise<undefined | string>

      Promise resolving to the compound name

      const name = await pubchem.getSimpleName();
      console.log(name); // "2-acetyloxybenzoic acid"
        async getSimpleName(): Promise<string | undefined> {
      try {
      const cid = await this.getCID();
      if (!cid) return undefined;
      const data = await this.querySdqAgent({ cid });
      if (!data) return undefined;
      return data.SDQOutputSet[0].rows[0].cmpdname;
      } catch (error) {
      console.error("Error fetching simple name:", error);
      }
      }
    • Retrieves the compound name from the SDQ agent query results

      Parameters

      • cmpdsynonym: string

      Returns Promise<undefined | string>

      Promise resolving to the compound name

      const name = await pubchem.getCompoundNameFromAlias("aspirin");
      
        async getCompoundNameFromAlias(cmpdsynonym: string): Promise<string | undefined> {
      try {
      const data = await this.querySdqAgent({ cmpdsynonym });
      if (!data) return undefined;
      return data.SDQOutputSet[0].rows[0].cmpdname;
      } catch (error) {
      console.error("Error fetching compound name from alias:", error);
      }
      }

    Properties

    baseURL: "https://pubchem.ncbi.nlm.nih.gov"

    Base URL for PubChem API endpoints

    query: string

    The chemical compound name or identifier to search for