當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript node-fetch類代碼示例

本文整理匯總了TypeScript中node-fetch的典型用法代碼示例。如果您正苦於以下問題:TypeScript node-fetch類的具體用法?TypeScript node-fetch怎麽用?TypeScript node-fetch使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了node-fetch類的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: it

    it('should support fields', async () => {
      // the custom fields not already be in the base fields
      expect(User.fields.custom.fields).to.be.undefined;

      let result = await fetch(urlPrefix + '/api/user/custom', {
        method: 'put',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ organization: 1 })
      });
      let json = await result.json();
      expect(_.keys(json.fields)).to.eql(['custom', 'acmeY']);

      // should also merge nested fields
      expect(_.keys(json.fields.custom.fields)).to.eql(['nested1', 'nested2']);

      // it should NOT modify the base fields
      expect(User.fields.custom.fields).to.be.undefined;

      expect(json.fields.custom.fields.nested1.label).to.eql('Nested 1');

      result = await fetch(urlPrefix + '/api/organization/custom', {
        method: 'put',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ foo: 1 })
      });

      json = await result.json();
      expect(_.keys(json.fields)).to.eql([]);
    });
開發者ID:tyranid-org,項目名稱:tyranid,代碼行數:33,代碼來源:express.test.ts

示例2: fetch

export default function request({
  token, name
}: any): Promise<StampRally> {
  const urlObj = url.parse('https://api.rallyapp.jp/stamp_rallies/');
  urlObj.query = { view_type: 'admin' };
  return fetch(
    url.format(urlObj),
    {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Token token="' + token + '"',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        name,
        display_name: 'stamprally',
        tagline: 'tagline',
        description: 'description',
        display: false,
        open: false,
        display_start_datetime: '2016-01-01T00:00:00Z',
        display_end_datetime: '2016-12-31T00:00:00Z',
        start_datetime: '2016-01-01T00:00:00Z',
        end_datetime: '2016-12-31T00:00:00Z'
      })
    }
  )
  .then((response: any) => response.json())
  .then((stampRally: StampRally) => stampRally);
}
開發者ID:bouzuya,項目名稱:rally-rxjs,代碼行數:31,代碼來源:stamp-rally-create.ts

示例3: downloadPackage

export function downloadPackage(type: PackageType, metadata: PackageMetadata): Promise<string> {
    let { version, dist: { platform, format, url } } = metadata;

    let packageBaseName = `${type}-${version}-${platform}`
    let packageName = `${packageBaseName}.${format}`;
    let metadataFileName = `${packageBaseName}.json`;

    let packagePath = Path.join(config.downloadsPath, packageName);
    let metadataFilePath = Path.join(config.downloadsPath, metadataFileName);

    if (FS.existsSync(packagePath) && FS.existsSync(metadataFilePath)) {
        return Promise.resolve(packagePath);
    }

    let tmpPackagePath = Tmp.tmpNameSync();

    return Promise
        .resolve(fetch(url))
        .then(res => {
            let resStream = res.body;
            let writeStream = FS.createWriteStream(tmpPackagePath);

            resStream.pipe(writeStream);

            return Promise.for(writeStream, 'close', [resStream]);
        })
        .then(() => {
            FS.copySync(tmpPackagePath, packagePath);

            let metadataJSON = JSON.stringify(metadata, undefined, 4);
            FS.writeFileSync(metadataFilePath, metadataJSON);

            return packagePath;
        });
}
開發者ID:vilic,項目名稱:rvm,代碼行數:35,代碼來源:index.ts

示例4: getZfxFormContent

  public static async getZfxFormContent(transaction_id: string, vendor_form_id: string, zfx_form_version: string, context_id: string) {
    const headers = {
      'Content-Type': 'application/json',
      'X-Auth-ContextId': context_id,
      'X-Auth-SharedKey': zipFormSharedKey
     };
    // const response = await fetch(`${zipFormURL}/api/transactions/${transaction_id}/documents/${vendor_form_id}/${zfx_form_version}`, {
    //   method: 'GET',
    //   headers
    // });

    const response = await fetch(`https://h5.zipformonline.com/api/transactions/0f1ee286-e455-4e3b-8003-702aa25b925a/documents/B3466E24-24E0-4355-95FD-EB84E7AEBDE5/812.0`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'X-Auth-ContextId': '9b4b8ab6-2504-40b2-be22-afbf7f12ec54',
        'X-Auth-SharedKey': '36441E42-40E8-4A63-AC52-269765422884'
      }
    });
    const data = await response.buffer();
    if (data) {
      // const base64data = new Buffer(data, 'utf-8');
      const fileupload = await this.uploadFileToS3(data, 'khanh.test');
      console.log(fileupload);
      // console.log(data.body);
      return data;
    } else {
      const errMsg = `Error getting content for =${vendor_form_id}`;
      console.log(errMsg, data);
      throw new Error(errMsg);
    }
  }
開發者ID:,項目名稱:,代碼行數:32,代碼來源:

示例5: test_fetchUrlWithHeadersObject

function test_fetchUrlWithHeadersObject() {
	var requestOptions: _fetch.RequestInit = {
		method: "POST",
		headers: {
			'Content-Type': 'application/json'
		}
	};
	handlePromise(fetch("http://www.andlabs.net/html5/uCOR.php", requestOptions));
}
開發者ID:ASnow,項目名稱:DefinitelyTyped,代碼行數:9,代碼來源:node-fetch-tests.ts

示例6: deployModel

async function deployModel(service, stage, datamodel) {
  await fetch(`http://localhost:4466/management`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      query: `mutation {
      addProject(input: {
        name: "${service}"
        stage: "${stage}"
      }) {
        clientMutationId
      }
    }`,
    }),
  })

  const variables = {
    input: {
      name: service,
      stage,
      types: datamodel,
    },
  }

  await fetch(`http://localhost:4466/management`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      query: `mutation ($input: DeployInput!) {
        deploy(input: $input) {
          clientMutationId
        }
      }`,
      variables,
    }),
  })
}
開發者ID:dhruvcodeword,項目名稱:prisma,代碼行數:41,代碼來源:regenerateSchema.ts

示例7: getPackageMetadata

export function getPackageMetadata(range = '*'): Promise<PackageMetadata> {
    let versionsUrl = `${config.registry}/sdks.json`;

    return Promise
        .resolve(fetch(versionsUrl))
        .then(res => res.json<VersionsData>())
        .then(data => {
            let { tags, packages } = data;
            let versions = Object.keys(packages);

            let version = match(range, versions, tags);

            if (!version) {
                throw new ExpectedError(`No matching version found for "${range}"`);
            }

            let { dists } = packages[version];
            let priorPlatformName = `${process.platform}-${process.arch}`

            let possiblePlatformNames = [
                priorPlatformName,
                process.platform
            ];

            let dist: Distribution;
            let platformName: string;

            for (let platformName of possiblePlatformNames) {
                if (hasOwnProperty.call(dists, platformName)) {
                    let rawDist = dists[platformName];

                    dist = {
                        platform: platformName,
                        format: rawDist.format,
                        url: rawDist.url,
                        strip: rawDist.strip
                    };

                    break;
                }
            }

            if (!dist) {
                throw new ExpectedError(`No matching distribution package found for platform "${priorPlatformName}"`);
            }

            return {
                version,
                dist
            };
        });
}
開發者ID:vilic,項目名稱:rvm,代碼行數:52,代碼來源:index.ts

示例8: test_fetchUrlWithOptions

function test_fetchUrlWithOptions() {
	var headers = new _fetch.Headers();
	headers.append("Content-Type", "application/json");
	var requestOptions: _fetch.RequestInit = {
		method: "POST",
		headers: headers,
		mode: 'same-origin',
		credentials: 'omit',
		cache: 'default',
		redirect: 'manual'
	};
	handlePromise(fetch("http://www.andlabs.net/html5/uCOR.php", requestOptions));
}
開發者ID:ASnow,項目名稱:DefinitelyTyped,代碼行數:13,代碼來源:node-fetch-tests.ts

示例9: if

 private async createRequest<T>(method: "GET" | "POST" | "PUT" | "DELETE", path: string, payload?: Object)
 {
     method = method.toUpperCase() as any;
     
     const url = new uri(`https://api.sendwithus.com/api/v1/${path}`);
     const options = {
         headers: this.buildDefaultHeaders(),
         method: method,
         body: undefined as string,
     };
     
     if ((method === "GET" || method === "DELETE") && payload)
     {
         for (const prop in payload)
         {
             const value = payload[prop];
             
             //qs array values should be joined by a comma, e.g. fields=field1,field2,field3
             url.addQueryParam(prop, Array.isArray(value) ? value.join(",") : value);
         }
     }
     else if (payload)
     {
         options.body = JSON.stringify(payload);
         
         options.headers.append("Content-Type", "application/json");
     }
     
     //Fetch will only throw an exception when there is a network-related error, not when the service returns a non-200 response.
     const result = await fetch(url.toString(), options);
     let json = await result.text() as any;
     
     try
     {
         json = JSON.parse(json);
     }
     catch (e)
     {
         //Set ok to false to throw an error with the body's text.
         result.ok = false;
     }
     
     if (!result.ok)
     {
         throw new Error(result.statusText, result.status);
     }
     
     return json as T; 
 }
開發者ID:nozzlegear,項目名稱:swu-logs,代碼行數:49,代碼來源:client.ts

示例10: fetch

export default function request({ token, stampRallyId }: any): Promise<Spot[]> {
  const urlObj = url.parse(
    'https://api.rallyapp.jp/stamp_rallies/' + stampRallyId + '/spots'
  );
  urlObj.query = { view_type: 'admin' };
  return fetch(
    url.format(urlObj),
    {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Token token="' + token + '"',
        'Content-Type': 'application/json'
      }
    }
  )
  .then((response: any) => response.json())
  .then(({ spots }) => spots);
}
開發者ID:bouzuya,項目名稱:rally-rxjs,代碼行數:19,代碼來源:spot-index.ts


注:本文中的node-fetch類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。