Example #1
0
test('Response data can be deduplicated with graphql-deduplicator', async t => {
  const { uri, data: { book } } = await startServer(t)

  const query = `
    query {
      books {
        __typename
        id
        name
        author {
          __typename
          id
          name
          lastName
        }
      }
    }
  `

  const body = await request({
    uri,
    method: 'POST',
    json: true,
    body: { query },
  }).promise()

  const deduplicated = await request({
    uri,
    method: 'POST',
    json: true,
    body: { query },
    headers: {
      'X-GraphQL-Deduplicate': true
    }
  }).promise()

  t.deepEqual(body, {
    data: {
      books: Array(5).fill(book)
    }
  })

  t.deepEqual(deduplicated, {
    data: {
      books: [
        book,
        ...Array(4).fill({
          __typename: book.__typename,
          id: book.id
        })
      ]
    }
  })

  t.deepEqual(body.data, inflate(deduplicated.data))
})
http.createServer((req, resp) => {
  if (req.url === '/doodle.png') {
    const x = rpn('http://mysite.com/doodle.png');
    req.pipe(x);
    x.pipe(resp);
  }
});
Example #3
0
  /**
   * @param {string} url
   * @param {{}} form
   * @param {Token?} token
   */
  postForm<T = any>(
    url: string,
    form:
      | FormData
      | {
          file: UploadFileStream;
          path: string;
          uploadToken: string | null;
        } & Partial<UploadFileRequest>,
    token?: Token | undefined,
  ): Promise<T> {
    const header = this.authenticator.getHeader(token);

    const options = {
      method: 'POST',
      url,
      formData: form,
      headers: header,
      json: true,
    };

    return request(options).then(
      response => {
        if (response.statusCode < 200 || response.statusCode >= 300) {
          return Promise.reject(response.body);
        }

        return response;
      },
      error => {
        return Promise.reject(error);
      },
    );
  }
Example #4
0
	public async resolve(value: any): Promise<IObject> {
		if (value == null) {
			throw new Error('resolvee is null (or undefined)');
		}

		if (typeof value !== 'string') {
			return value;
		}

		if (this.history.has(value)) {
			throw new Error('cannot resolve already resolved one');
		}

		this.history.add(value);

		const object = await request({
			url: value,
			headers: {
				Accept: 'application/activity+json, application/ld+json'
			},
			json: true
		});

		if (object === null || (
			Array.isArray(object['@context']) ?
				!object['@context'].includes('https://www.w3.org/ns/activitystreams') :
				object['@context'] !== 'https://www.w3.org/ns/activitystreams'
		)) {
			log(`invalid response: ${value}`);
			throw new Error('invalid response');
		}

		return object;
	}
Example #5
0
    async function httpRequest(args: { path: string, method: string, body?: any, formData?: any, query?: any, json?: boolean }) {
        const options: any = {
            uri: `${Configuration.baseUrl}${args.path}`,
            method: args.method,
            resolveWithFullResponse: true
        };

        if (args.formData) {
            options.formData = args.formData;
        } else if (args.body) {
            options.body = args.body;
        } else if (args.query) {
            options.qs = args.query;
        }

        if (args.json) {
            options.json = true;
        }
        // console.log(options);
        try {
            return await request(options);
        } finally {
            // console.log(`request sent ${options.method} ${options.uri}`);
        }
    }
Example #6
0
  private _request<T = any>(
    httpMethod: string,
    url: string,
    params: any,
    token: Token | string | undefined,
  ): Promise<T> {
    const header = this.authenticator.getHeader(token);
    const options: HTTPRequest = {
      method: httpMethod,
      url,
      headers: header,
      json: true,
      resolveWithFullResponse: true,
      simple: false,
    };

    switch (httpMethod) {
      case 'POST':
      case 'PUT':
        options.body = params;
        break;
      default:
        options.qs = params;
    }

    return request(options).then(response => {
      if (response.statusCode < 200 || response.statusCode >= 300) {
        return Promise.reject(new Error(JSON.stringify(response.body)));
      }

      return response.body;
    });
  }
	return new Promise<null>((resolve, reject) => {
		let params: any = {
			timestamp: tsPost,
			commentTimestamp: tsComment
		};

		let reqPath = path.join('/v1/server/posts', tsPost.toString(), 'comments', tsComment.toString());
		let url = postAuthor + reqPath;

		if(idtoken && sigtoken) {
			params.idToken = idtoken;
			let signature = utils.computeSignature('DELETE', url, params, sigtoken);
			url += '?idToken=' + idtoken
			url += '&signature=' + signature;
		}

		// We'll use HTTP only for localhost
		if(url.indexOf('localhost') < 0 && !commons.settings.forceHttp) url = 'https://' + url;
		else url = 'http://' + url

		log.debug('Requesting DELETE', url);

		request({
			method: 'DELETE',
			uri: url,
			timeout: commons.settings.timeout
		})
		.then((response) => {
			log.debug('Deleted a comment on', postAuthor.toString());
			resolve(response);
		}).catch(reject);
	});
Example #8
0
 private async getSitemap() {
   try {
     if (helper.isUrl(this.url) && helper.isXml(this.url)) {
       return await request(this.url);
     }
   } catch (error) {
     console.error(`Error on Request Catch : ${error}`);
     throw error;
   }
 }
Example #9
0
export async function getTrainPredictions(station: Wmata.Station): Promise<Array<Wmata.TrainPrediction>> {
    let options = {
        url: `https://api.wmata.com/StationPrediction.svc/json/GetPrediction/${station.Code}`,
        headers: {
            api_key: wmataApiKey
        },
        json: true
    };
    return request(options)
        .then(response => response.Trains);
};
Example #10
0
export async function getNearestStation(lat: number, long: number): Promise<any> {
    let options = {
        url: `https://api.wmata.com/Rail.svc/json/jStations`,
        headers: {
            api_key: wmataApiKey
        },
        json: true
    };
    return request(options)
        .then(response => calculateNearestStation(response.Stations, lat, long));
};