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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 | 1x 1x 1x 1x 1x 1x 1x 8x 8x 1x 1x 7x 7x 6x 6x 8x 1x 1x 6x 6x 6x 5x 8x 2x 2x 8x 8x 1x 1x 8x 1x 1x 18x 18x 1x 1x 18x 3x 3x 18x 1x 1x 13x 13x 12x 12x 18x 1x 1x 18x 18x 1x 1x 18x 1x 1x 18x 1x 1x 10x 10x 1x 1x 10x 5x 5x 10x 1x 1x 1x 1x 1x 1x 1x 1x 27x 27x 1x 1x 1x 19x 19x 19x 18x 18x 18x 19x 9x 9x 19x 1x 1x 1x 10x 10x 10x 8x 8x 8x 8x 8x 10x 5x 5x 10x 1x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 6x 6x 10x 1x 1x 1x 3x 3x 3x 2x 3x 1x 3x 3x 1x 1x 1x 2x 2x 2x 1x 2x 2x 1x | // PubChem types (CompoundResponse, CIDResponse, SDQQuery, SDQResponse,
// SDQOutputSet, SDQOutputRow/SDQResultItem) are declared globally in types/pubchem.d.ts
/**
* Type guard to assert that data is a valid CIDResponse
* @param data - The data to validate
* @source
*/
import { Logger } from '@/utils/Logger';
import { getErrorMessage } from '@/helpers/exceptions';
const logger = new Logger('Pubchem');
function assertIsCIDResponse(data: unknown): asserts data is CIDResponse {
if (typeof data !== 'object' || data === null) {
throw new Error('data is not an object');
}
if (
!('ConceptsAndCIDs' in data) ||
typeof data.ConceptsAndCIDs !== 'object' ||
data.ConceptsAndCIDs === null
) {
throw new Error('data.ConceptsAndCIDs is not an object');
}
if (
!('CID' in data.ConceptsAndCIDs) ||
!Array.isArray(data.ConceptsAndCIDs.CID) ||
data.ConceptsAndCIDs.CID.length === 0
) {
throw new Error('data.ConceptsAndCIDs.CID is not an array');
}
if (data.ConceptsAndCIDs.CID.length === 0) {
throw new Error('data.ConceptsAndCIDs.CID is empty');
}
if (typeof data.ConceptsAndCIDs.CID[0] !== 'number') {
throw new Error('data.ConceptsAndCIDs.CID[0] is not a number');
}
}
/**
* Type guard to assert that data is a valid CompoundResponse
* @param data - The data to validate
* @source
*/
function assertIsCompoundResponseResponse(data: unknown): asserts data is CompoundResponse {
if (typeof data !== 'object' || data === null) {
throw new Error('data is not an object');
}
if (!('status' in data) || typeof data.status !== 'object') {
throw new Error('data.status is not an object');
}
if (!('total' in data) || typeof data.total !== 'number') {
throw new Error('data.total is not a number');
}
if (
!('dictionary_terms' in data) ||
typeof data.dictionary_terms !== 'object' ||
data.dictionary_terms === null
) {
throw new Error('data.dictionary_terms is not an object');
}
if (!('compound' in data.dictionary_terms) || !Array.isArray(data.dictionary_terms.compound)) {
throw new Error('data.dictionary_terms.compound is not an array');
}
if (data.dictionary_terms.compound.length === 0) {
throw new Error('data.dictionary_terms.compound is empty');
}
if (typeof data.dictionary_terms.compound[0] !== 'string') {
throw new Error('data.dictionary_terms.compound[0] is not a string');
}
}
/**
* Type guard to assert that data is a valid SDQResponse
* @param data - The data to validate
* @source
*/
function assertIsSdqAgentResponse(data: unknown): asserts data is SDQResponse {
if (typeof data !== 'object' || data === null) {
throw new Error('data is not an object');
}
if (!('SDQOutputSet' in data) || typeof data.SDQOutputSet !== 'object') {
throw new Error('data.SDQOutputSet is not an object');
}
}
/**
* 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.
*
* @category Utils
* @example
* ```typescript
* const pubchem = new Pubchem("2-Acetoxybenzenecarboxylic acid");
* console.log("Result:", await pubchem.getSimpleName());
* // Result: Aspirin
* ```
* @source
*/
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) {
logger.error(`Error fetching compound: ${getErrorMessage(error)}`, { 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) {
logger.error(`Error fetching CID: ${getErrorMessage(error)}`, { 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,
};
logger.debug('SDQ agent query', { sdqAgentQuery });
const queryURL = JSON.stringify(sdqAgentQuery).replace(/"/g, '%22').replace(/ /g, '%20');
logger.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) {
logger.error(`Error querying SDQ agent: ${getErrorMessage(error)}`, { 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) {
logger.error(`Error fetching simple name: ${getErrorMessage(error)}`, { 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) {
logger.error(`Error fetching compound name from alias: ${getErrorMessage(error)}`, { error });
}
}
}
|