"Fossies" - the Fresh Open Source Software Archive

Member "cli-1.1280.1/packages/snyk-protect/src/lib/http.ts" (20 Feb 2024, 1350 Bytes) of package /linux/misc/snyk-cli-1.1280.1.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) TypeScript source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file.

    1 import * as http from 'http';
    2 import * as https from 'https';
    3 import { IncomingMessage } from 'http';
    4 import { RequestOptions } from 'https';
    5 
    6 export type SnykResponse = { res: IncomingMessage; body: any };
    7 
    8 export async function request(
    9   url: string,
   10   data?: string | Buffer,
   11   options: RequestOptions = {},
   12 ): Promise<SnykResponse> {
   13   return new Promise((resolve, reject) => {
   14     const client = new URL(url).protocol === 'https:' ? https : http;
   15     const requestOptions = {
   16       ...options,
   17       agent: new client.Agent({ keepAlive: true }),
   18     };
   19     const request = client.request(url, requestOptions, (response) => {
   20       const body: any[] = [];
   21       response.on('data', (chunk: any) => body.push(Buffer.from(chunk)));
   22       response.on('end', () =>
   23         resolve({ res: response, body: Buffer.concat(body).toString('utf-8') }),
   24       );
   25     });
   26     request.on('error', reject);
   27 
   28     if (data) {
   29       request.write(data);
   30     }
   31     request.end();
   32   });
   33 }
   34 
   35 export function postJson(
   36   url: string,
   37   jsonData: any,
   38   options: RequestOptions = {},
   39 ): Promise<SnykResponse> {
   40   const jsonString = JSON.stringify(jsonData);
   41   const requestOptions = {
   42     ...options,
   43     method: 'POST',
   44     headers: {
   45       ...options.headers,
   46       'Content-Type': 'application/json',
   47     },
   48   };
   49   return request(url, jsonString, requestOptions);
   50 }