本文整理匯總了TypeScript中node-fetch.default函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript default函數的具體用法?TypeScript default怎麽用?TypeScript default使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了default函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。
示例1: test
test('regex restriction, request body matches regex - match', async () => {
const route = fakeServer.http
.post()
.to(path)
.withBodyThatMatches(lettersRegex)
[method]();
const actualBody = 'abc';
const res = await fetch(`http://localhost:${port}${path}`, {
method: 'POST',
headers: {'Content-Type': 'text/plain'},
body: actualBody,
});
expect(res.status).toEqual(defaultStatus);
expect(fakeServer.hasMade(route.call)).toEqual(true);
const callsMade = fakeServer.callsMade(route.call);
expect(callsMade[0].path).toEqual(path);
expect(callsMade[0].body).toEqual(actualBody);
});
示例2: test
test('route defined with path and body regex - chaining assertions, specific path and body match path and body regex - assertion success', async () => {
const pathRegex = '/[a-zA-Z]+$';
const actualPath = '/somePath';
const bodyRegex = '[0-9]+$';
const actualBody = '123';
const route = fakeServer.http
.post()
.to(pathRegex)
.withBodyThatMatches(bodyRegex)
[method]();
const res = await fetch(`http://localhost:${port}${actualPath}`, {
method: 'POST',
headers: {'Content-Type': 'text/plain'},
body: actualBody,
});
expect(res.status).toEqual(defaultStatus);
expect(fakeServer.hasMade(route.call.withPath(actualPath).withBodyText(actualBody))).toEqual(true);
expect(fakeServer.hasMade(route.call.withBodyText(actualBody).withPath(actualPath))).toEqual(true);
});
示例3: main
export default function main(): Promise<Counts> {
const username = process.env.GITHUB_USERNAME;
if (typeof username === 'undefined')
return Promise.reject('GITHUB_USERNAME is not defined');
const accessToken = process.env.GITHUB_ACCESS_TOKEN;
if (typeof accessToken === 'undefined')
return Promise.reject('GITHUB_ACCESS_TOKEN is not defined');
const urlString = url.format({
...url.parse(`https://api.github.com/users/${username}`),
query: qs.stringify({ access_token: accessToken })
});
return fetch(urlString, {})
.then((response) => response.json())
.then((json: GitHubResponse): Counts => {
return {
'GitHub Followers': json.followers,
'GitHub Following': json.following,
'GitHub Public Gists': json.public_gists,
'GitHub Public Repos': json.public_repos
};
});
}
示例4: introspectServer
export async function introspectServer(url: string, method: string, headerStrings: string[]): Promise<string> {
const headers: { [name: string]: string } = {};
for (const name of Object.getOwnPropertyNames(defaultHeaders)) {
headers[name] = defaultHeaders[name];
}
for (const str of headerStrings) {
const matches = str.match(headerRegExp);
if (matches === null) {
return panic(`Not a valid HTTP header: "${str}"`);
}
headers[matches[1]] = matches[2];
}
let result;
try {
const response = await fetch(url, {
method,
headers: headers,
body: JSON.stringify({ query: introspectionQuery })
});
result = await response.json();
} catch (error) {
return panic(`Error while fetching introspection query result: ${error.message}`);
}
if (result.errors) {
return panic(`Errors in introspection query result: ${JSON.stringify(result.errors)}`);
}
const schemaData = result;
if (!schemaData.data) {
return panic(`No introspection query result data found, server responded with: ${JSON.stringify(result)}`);
}
return JSON.stringify(schemaData, null, 2);
}
示例5: fetch
return (query, variables?, operationName?) => {
return fetch(url, {
method: 'POST',
headers: new Headers({
"content-type": 'application/json',
...headersObj,
}),
body: JSON.stringify({
operationName,
query,
variables,
})
}).then(responce => {
if (responce.ok)
return responce.json();
return responce.text().then(body => {
throw Error(`${responce.status} ${responce.statusText}\n${body}`);
});
});
}
示例6: getLights
export async function getLights() {
const [body, rooms] = await Promise.all([
fetch(`${api}/lights`).then(res => res.json()),
findAll(),
]);
let correctedBody = body;
if (body) {
rooms.forEach(({ roomId, lightId }) => {
if (body.hasOwnProperty(lightId)) {
body[lightId].roomId = roomId;
}
});
correctedBody = toArray(body);
}
return correctedBody;
}
示例7: readAuthTimestamp
async readAuthTimestamp(bucketAddress: string): Promise<number> {
const authTimestampDir = this.getAuthTimestampFileDir(bucketAddress)
let fetchResponse: Response
try {
const authNumberFileUrl = `${this.readUrlPrefix}${authTimestampDir}/${AUTH_TIMESTAMP_FILE_NAME}`
fetchResponse = await fetch(authNumberFileUrl, {
redirect: 'manual',
headers: {
'Cache-Control': 'no-cache'
}
})
} catch (err) {
// Catch any errors that may occur from network issues during `fetch` async operation.
const errMsg = (err instanceof Error) ? err.message : err
throw new errors.ValidationError(`Error trying to fetch bucket authentication revocation timestamp: ${errMsg}`)
}
if (fetchResponse.ok) {
try {
const authNumberText = await fetchResponse.text()
const authNumber = parseInt(authNumberText)
if (Number.isFinite(authNumber)) {
return authNumber
} else {
throw new errors.ValidationError(`Bucket contained an invalid authentication revocation timestamp: ${authNumberText}`)
}
} catch (err) {
// Catch any errors that may occur from network issues during `.text()` async operation.
const errMsg = (err instanceof Error) ? err.message : err
throw new errors.ValidationError(`Error trying to read fetch stream of bucket authentication revocation timestamp: ${errMsg}`)
}
} else if (fetchResponse.status === 404) {
// 404 incidates no revocation file has been created.
return 0
} else {
throw new errors.ValidationError(`Error trying to fetch bucket authentication revocation timestamp: server returned ${fetchResponse.status} - ${fetchResponse.statusText}`)
}
}
示例8: function
exports.handler = async function(event: APIGatewayProxyEvent, context: Context, callback: APIGatewayProxyCallback){
// Try to grab data from dataservice and proxy it
try{
// Grabbing data from data service
const res = await fetch(dataURL);
const body = await res.text();
// Returning data
return {
statusCode: 200,
body,
};
}
catch(e){
return {
statusCode: 500,
body: "An error has occured while getting data"
}
}
}
示例9: expect
it('should return 403 if scope is not granted', () => {
// given
const authHeader = 'Bearer 4b70510f-be1d-4f0f-b4cb-edbca2c79d41';
addAuthenticationEndpointWithoutRequiredScopes();
// when
const promise = fetch('http://127.0.0.1:30002/resource/user', {
method: 'GET',
headers: {
authorization: authHeader
}
})
.then((res) => {
return res.status;
});
// then
return expect(promise).to.become(HttpStatus.FORBIDDEN);
});
示例10: fetch
const createAction = (
action: LikeAction,
id: string,
title?: string,
): Promise<StatusResponse> => {
const url = new URL(
'https://script.google.com/macros/s/AKfycbwErydNjqBnj4xo_AHcAro-UziMCuciiMEORMQMuJ-fxhk4XxE/exec',
);
url.searchParams.set('id', id);
url.searchParams.set('action', action);
if (title) {
url.searchParams.set('description', title);
}
return fetch(url.toString()).then(result => {
return {
code: result.status,
message: result.statusText,
};
});
};
示例11: exec
async function exec() {
const resp = await fetch(endpoint, {
method: "POST",
headers: {
Authorization: `bearer ${authToken}`,
},
body: `{"query":${JSON.stringify(query)}}`,
});
if (resp.status !== 200) {
throw new Error(`error, ${resp.status} ${await resp.text()}`);
}
const data = await resp.json();
const text = data.data.search.nodes
.filter((v: any) => ignoreOrgs.indexOf(v.repository.owner.login) === -1)
.filter((v: any) => {
const createdAt = new Date(v.createdAt);
return start.getTime() <= createdAt.getTime() && createdAt.getTime() < end.getTime();
})
.map((v: any) => `* ${v.title} ${v.createdAt}\n * ${v.url}`).join("\n");
console.log(text);
}
示例12: getUsers
async function getUsers(): Promise<void> {
let usersRequest = await fetch(
api,
{
headers: headers
}
);
let usersResponse = await usersRequest.json();
if (usersRequest.ok) {
await Promise.all(usersResponse.map(async (user) => {
await createUser(user.login);
console.log(`User ${user.login} created`);
}));
}
else {
// Something horrible happened;
console.error(usersResponse);
}
}
示例13: getStockSymbol
getStockSymbol(input: string, callback: SClientCallback) {
var url = `http://dev.markitondemand.com/Api/v2/Lookup/json?input=${input}`;
fetch(url)
.then(function(res) {
if (res.status === 200) {
return res.json();
}
else {
callback(
{
url: res.url,
status: res.status,
statusText: res.statusText
}, null);
}
})
.then(function(data) {
if (callback) {
callback(null, data)
}
});
}
示例14: GetLUISInfo
GetLUISInfo(sourceText: string, callback: LuisCallback) {
var luisBaseUrl = "https://api.projectoxford.ai/luis/v1/application";
var applicationId = "07c4c72e-d229-4c7b-96db-2034c036d30e";
var subscriptionKey = "c2ba4a70587642b7a4cada97a40584ed";
var requestUri = `${luisBaseUrl}?id=${applicationId}&subscription-key=${subscriptionKey}&q=${sourceText}`;
fetch(requestUri).then((res) => {
if (res.status === 200) {
return res.json();
}
else {
callback(
{
url: res.url,
status: res.status,
statusText: res.statusText
}, null);
}
}).then((data) => {
if (callback) {
callback(null, data)
}
});
}
示例15: async
const generateRundeckToken: () => Promise<string> = async () => {
const date = new Date();
const response = await _fetch(
BASE_URL + '/api/25/token', {
headers: {
"X-Rundeck-Auth-Token": process.env.MASTER_RUNDECK_TOKEN,
"accept": "application/json",
"Content-type": "application/json"
},
body: {
"user": date.getTime(),
"role": [
"ROLE_user"
],
"duration": "10080m"
}
}
).json();
const tokenInfo = response.token;
return tokenInfo;
};