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; }
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}`) } }
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); });
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" } } }
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); });
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); });
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, }; }); };
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); }
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 }; }); }
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); }