How to use formattedHeaders method in wpt

Best JavaScript code snippet using wpt

ApiBuilder.js

Source:ApiBuilder.js Github

copy

Full Screen

1import React, { useState, useEffect } from "react";2import PropTypes from "prop-types";3import { connect } from "react-redux";4import { withRouter } from "react-router";5import {6 Grid, Form, Dropdown, Input, Menu, Button, List, Icon, Checkbox,7 Divider, Label, Popup,8} from "semantic-ui-react";9import AceEditor from "react-ace";10import uuid from "uuid/v4";11import _ from "lodash";12import { toast } from "react-toastify";13import "ace-builds/src-min-noconflict/mode-json";14import "ace-builds/src-min-noconflict/mode-javascript";15import "ace-builds/src-min-noconflict/theme-tomorrow";16import ApiPagination from "./ApiPagination";17import {18 runRequest as runRequestAction,19} from "../../../actions/dataset";20import { changeTutorial as changeTutorialAction } from "../../../actions/tutorial";21import { primaryTransparent } from "../../../config/colors";22const methods = [{23 key: 1,24 text: "GET",25 value: "GET",26}, {27 key: 2,28 text: "POST",29 value: "POST",30}, {31 key: 3,32 text: "PUT",33 value: "PUT",34}, {35 key: 4,36 text: "DELETE",37 value: "DELETE",38}, {39 key: 5,40 text: "OPTIONS",41 value: "OPTIONS",42}];43/*44 The API Data Request builder45*/46function ApiBuilder(props) {47 const [apiRequest, setApiRequest] = useState({48 method: "GET",49 route: "",50 useGlobalHeaders: true,51 formattedHeaders: [{52 id: uuid(),53 key: "",54 value: "",55 }]56 });57 const [result, setResult] = useState("");58 const [activeMenu, setActiveMenu] = useState("headers");59 const [requestSuccess, setRequestSuccess] = useState(false);60 const [requestLoading, setRequestLoading] = useState(false);61 const [requestError, setRequestError] = useState(false);62 const [useCache, setUseCache] = useState(false);63 const {64 dataRequest, match, onChangeRequest, runRequest, dataset,65 connection, onSave, requests, changeTutorial, chart,66 } = props;67 // on init effect68 useEffect(() => {69 if (dataRequest) {70 // format the headers into key: value -> value: value format71 const formattedApiRequest = dataRequest;72 const formattedHeaders = [];73 if (dataRequest.headers) {74 Object.keys(dataRequest.headers).forEach((key) => {75 formattedHeaders.push({76 id: uuid(),77 key,78 value: dataRequest.headers[key],79 });80 });81 }82 if (!formattedApiRequest.method) formattedApiRequest.method = "GET";83 formattedApiRequest.formattedHeaders = formattedHeaders;84 setApiRequest(formattedApiRequest);85 // get the request data if it exists86 const requestBody = _.find(requests, { options: { id: dataset.id } });87 if (requestBody) {88 setResult(JSON.stringify(requestBody.data, null, 2));89 }90 setTimeout(() => {91 changeTutorial("apibuilder");92 }, 1000);93 }94 setUseCache(!!window.localStorage.getItem("_cb_use_cache"));95 }, []);96 useEffect(() => {97 const newApiRequest = apiRequest;98 // automate the pagination template here (to a possible extent)99 if (connection && apiRequest && !apiRequest.template) {100 if (connection.host.indexOf("api.stripe.com") > -1) {101 apiRequest.template = "stripe";102 }103 }104 onChangeRequest(newApiRequest);105 }, [apiRequest, connection]);106 const _addHeader = () => {107 const { formattedHeaders } = apiRequest;108 formattedHeaders.push({109 id: uuid(),110 key: "",111 value: "",112 });113 setApiRequest({ ...apiRequest, formattedHeaders });114 };115 const _removeHeader = (id) => {116 let { formattedHeaders } = apiRequest;117 if (formattedHeaders.length === 1) formattedHeaders = [];118 let found;119 for (let i = 0; i < formattedHeaders.length; i++) {120 if (formattedHeaders[i].id === id) {121 found = i;122 break;123 }124 }125 if (found) formattedHeaders.splice(found, 1);126 setApiRequest({ ...apiRequest, formattedHeaders });127 };128 const _onChangeHeader = (id, value) => {129 const { formattedHeaders } = apiRequest;130 for (let i = 0; i < formattedHeaders.length; i++) {131 if (formattedHeaders[i].id === id) {132 formattedHeaders[i].key = value;133 break;134 }135 }136 setApiRequest({ ...apiRequest, formattedHeaders });137 };138 const _onChangeHeaderValue = (id, value) => {139 const { formattedHeaders } = apiRequest;140 for (let i = 0; i < formattedHeaders.length; i++) {141 if (formattedHeaders[i].id === id) {142 formattedHeaders[i].value = value;143 break;144 }145 }146 setApiRequest({ ...apiRequest, formattedHeaders });147 };148 const _changeMethod = (value) => {149 if (value === "GET" || value === "OPTIONS") {150 setApiRequest({ ...apiRequest, method: value });151 setActiveMenu("headers");152 } else {153 setApiRequest({ ...apiRequest, method: value });154 }155 };156 const _onToggleGlobal = () => {157 setApiRequest({158 ...apiRequest, useGlobalHeaders: !apiRequest.useGlobalHeaders,159 });160 };161 const _onChangeBody = (value) => {162 setApiRequest({ ...apiRequest, body: value });163 };164 const _onChangeRoute = (value) => {165 setApiRequest({ ...apiRequest, route: value });166 };167 const _onPaginationChanged = (type, value) => {168 let newValue = value;169 if (type === "itemsLimit" && value && value !== "0") {170 newValue = Math.abs(parseInt(value, 10));171 }172 setApiRequest({ ...apiRequest, [type]: newValue });173 };174 const _onTest = () => {175 const { formattedHeaders } = apiRequest;176 let newHeaders = {};177 for (let i = 0; i < formattedHeaders.length; i++) {178 if (formattedHeaders[i].key && formattedHeaders[i].value) {179 newHeaders = { ...newHeaders, [formattedHeaders[i].key]: formattedHeaders[i].value };180 }181 }182 const finalApiRequest = { dataRequest: apiRequest };183 finalApiRequest.dataRequest.headers = newHeaders;184 setRequestLoading(true);185 setRequestSuccess(false);186 setRequestError(false);187 onSave().then(() => {188 runRequest(match.params.projectId, match.params.chartId, dataset.id, useCache)189 .then((result) => {190 setRequestLoading(false);191 setRequestSuccess(result.status);192 setResult(JSON.stringify(result.data, null, 2));193 })194 .catch((error) => {195 setRequestLoading(false);196 setRequestError(error);197 toast.error("The request failed. Please check your request 🕵️‍♂️");198 setResult(JSON.stringify(error, null, 2));199 });200 });201 };202 const _onChangeUseCache = () => {203 if (window.localStorage.getItem("_cb_use_cache")) {204 window.localStorage.removeItem("_cb_use_cache");205 setUseCache(false);206 } else {207 window.localStorage.setItem("_cb_use_cache", true);208 setUseCache(true);209 }210 };211 return (212 <div style={styles.container}>213 <Grid columns={2} stackable centered>214 <Grid.Column width={10}>215 <Form>216 <Form.Field className="apibuilder-route-tut">217 <Input218 label={connection.host}219 placeholder="/route?key=value"220 focus221 value={apiRequest.route || ""}222 onChange={(e, data) => _onChangeRoute(data.value)}223 />224 </Form.Field>225 <Form.Field>226 {"Available variables: "}227 <Popup228 trigger={(229 <Label basic as="a" onClick={() => chart.startDate && _onChangeRoute(`${apiRequest.route}{{start_date}}`)}>230 {"{{start_date}}"}231 </Label>232 )}233 content={chart.startDate || "Set this value in chart date settings first"}234 position="bottom center"235 />236 <Popup237 trigger={(238 <Label basic as="a" onClick={() => chart.endDate && _onChangeRoute(`${apiRequest.route}{{end_date}}`)}>239 {"{{end_date}}"}240 </Label>241 )}242 content={chart.endDate || "Set this value in chart date settings first"}243 position="bottom center"244 />245 </Form.Field>246 </Form>247 <Menu pointing secondary className="apibuilder-menu-tut">248 <Menu.Item249 name="Headers"250 active={activeMenu === "headers"}251 onClick={() => setActiveMenu("headers")}252 />253 <Menu.Item254 name="Body"255 disabled={apiRequest.method === "GET" || apiRequest.method === "OPTIONS"}256 active={activeMenu === "body"}257 onClick={() => setActiveMenu("body")}258 />259 <Menu.Item260 name="Pagination"261 active={activeMenu === "pagination"}262 onClick={() => setActiveMenu("pagination")}263 />264 <div style={{ position: "absolute", right: 15 }}>265 {requestSuccess && (266 <>267 <Label color="green" style={{ marginBottom: 10 }}>268 {`${requestSuccess.statusCode} ${requestSuccess.statusText}`}269 </Label>270 </>271 )}272 {requestError && (273 <Label color="red" style={{ marginBottom: 10 }}>274 {`${requestError.statusCode} ${requestError.statusText}`}275 </Label>276 )}277 </div>278 </Menu>279 {activeMenu === "headers" && (280 <div className="apibuilder-headers-tut">281 {connection.options && connection.options.length > 0 && (282 <div>283 <Checkbox284 label="Include connection headers"285 checked={!!apiRequest.useGlobalHeaders}286 onChange={_onToggleGlobal}287 />288 {apiRequest.useGlobalHeaders && (289 <List>290 {connection.options.map((header) => {291 return (292 <List.Item key={header}>293 <List.Content>294 <Form>295 <Form.Group widths={2}>296 <Form.Field width={7}>297 <Input value={Object.keys(header)[0]} />298 </Form.Field>299 <Form.Field width={7}>300 <Input value={header[Object.keys(header)[0]]} />301 </Form.Field>302 </Form.Group>303 </Form>304 </List.Content>305 </List.Item>306 );307 })}308 </List>309 )}310 <Divider />311 </div>312 )}313 <List>314 {apiRequest.formattedHeaders && apiRequest.formattedHeaders.map((header) => {315 return (316 <List.Item key={header.id}>317 <List.Content>318 <Form>319 <Form.Group widths={3}>320 <Form.Field width={7}>321 <Input322 placeholder="Header"323 value={header.key}324 onChange={(e, data) => {325 _onChangeHeader(header.id, data.value);326 }}327 />328 </Form.Field>329 <Form.Field width={7}>330 <Input331 placeholder="Value"332 value={header.value}333 onChange={(e, data) => {334 _onChangeHeaderValue(header.id, data.value);335 }}336 />337 </Form.Field>338 <Form.Field width={1}>339 <Button340 icon341 onClick={() => _removeHeader(header.id)}342 >343 <Icon name="close" />344 </Button>345 </Form.Field>346 </Form.Group>347 </Form>348 </List.Content>349 </List.Item>350 );351 })}352 </List>353 <Button354 icon355 labelPosition="right"356 size="small"357 onClick={_addHeader}358 >359 <Icon name="plus" />360 Add header361 </Button>362 </div>363 )}364 {activeMenu === "body" && (365 <div>366 <AceEditor367 mode="json"368 theme="tomorrow"369 height="400px"370 width="none"371 value={apiRequest.body || ""}372 onChange={(value) => {373 _onChangeBody(value);374 }}375 name="queryEditor"376 editorProps={{ $blockScrolling: true }}377 />378 </div>379 )}380 {activeMenu === "pagination" && (381 <ApiPagination382 items={apiRequest.items}383 itemsLimit={apiRequest.itemsLimit}384 offset={apiRequest.offset}385 paginationField={apiRequest.paginationField}386 pagination={apiRequest.pagination}387 onPaginationChanged={_onPaginationChanged}388 apiRoute={apiRequest.route || ""}389 template={apiRequest.template}390 result={result && JSON.parse(result)}391 />392 )}393 </Grid.Column>394 <Grid.Column width={6}>395 <Form style={{ paddingBottom: 10 }}>396 <Form.Group widths={2}>397 <Form.Field className="apibuilder-type-tut">398 <Dropdown399 fluid400 text={apiRequest.method}401 options={methods}402 selection403 onChange={(e, data) => _changeMethod(data.value)}404 />405 </Form.Field>406 <Form.Field className="apibuilder-request-tut">407 <Button408 primary409 icon410 labelPosition="right"411 loading={requestLoading}412 onClick={_onTest}413 fluid414 >415 <Icon name="play" />416 Run the request417 </Button>418 </Form.Field>419 </Form.Group>420 <Form.Field>421 <Checkbox422 label="Use cache"423 checked={!!useCache}424 onChange={_onChangeUseCache}425 />426 {" "}427 <Popup428 trigger={<Icon name="question circle outline" style={{ color: primaryTransparent(0.7) }} />}429 inverted430 >431 <>432 <p>{"If checked, Chartbrew will use cached data instead of making requests to your data source."}</p>433 <p>{"The cache gets automatically invalidated when you change the configuration of the request."}</p>434 </>435 </Popup>436 </Form.Field>437 </Form>438 <AceEditor439 mode="json"440 theme="tomorrow"441 height="400px"442 width="none"443 value={result || ""}444 onChange={() => setResult(result)}445 name="resultEditor"446 readOnly447 editorProps={{ $blockScrolling: false }}448 className="apibuilder-result-tut"449 />450 <p>451 <Icon name="exclamation circle" />452 <small>{"This is a preview and it might not show all data in order to keep things fast in the UI."}</small>453 </p>454 </Grid.Column>455 </Grid>456 </div>457 );458}459const styles = {460 container: {461 flex: 1,462 },463};464ApiBuilder.defaultProps = {465 dataRequest: null,466};467ApiBuilder.propTypes = {468 dataset: PropTypes.object.isRequired,469 connection: PropTypes.object.isRequired,470 match: PropTypes.object.isRequired,471 onChangeRequest: PropTypes.func.isRequired,472 runRequest: PropTypes.func.isRequired,473 onSave: PropTypes.func.isRequired,474 requests: PropTypes.array.isRequired,475 dataRequest: PropTypes.object,476 changeTutorial: PropTypes.func.isRequired,477 chart: PropTypes.object.isRequired,478};479const mapStateToProps = (state) => {480 return {481 requests: state.dataset.requests,482 };483};484const mapDispatchToProps = (dispatch) => {485 return {486 runRequest: (projectId, chartId, datasetId, getCache) => {487 return dispatch(runRequestAction(projectId, chartId, datasetId, getCache));488 },489 changeTutorial: (tutorial) => dispatch(changeTutorialAction(tutorial)),490 };491};...

Full Screen

Full Screen

email.js

Source:email.js Github

copy

Full Screen

1'use strict';2module.exports.formatHeaders = function formatHeaders(headers) {3 if (!headers) {4 return [];5 }6 var formattedHeaders = [];7 Object.keys(headers).forEach(function(header) {8 if (headers[header] instanceof Array) {9 headers[header].forEach(function(value) {10 formattedHeaders.push([header, value]);11 });12 } else {13 formattedHeaders.push([header, headers[header]]);14 }15 });16 return formattedHeaders;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt-api');2var wptClient = new wpt(process.env.WPT_API_KEY);3wptClient.formattedHeaders(url, function(err, data) {4 if (err) {5 console.log(err);6 } else {7 console.log(data);8 }9});10### formattedResults(url, callback)11* callback: function(err, data)12var wpt = require('wpt-api');13var wptClient = new wpt(process.env.WPT_API_KEY);14wptClient.formattedResults(url, function(err, data) {15 if (err) {16 console.log(err);17 } else {18 console.log(data);19 }20});21### getLocations(callback)22* callback: function(err, data)23var wpt = require('wpt-api');24var wptClient = new wpt(process.env.WPT_API_KEY);25wptClient.getLocations(function(err, data) {26 if (err) {27 console.log(err);28 } else {29 console.log(data);30 }31});32### getTestStatus(url, callback)33* callback: function(err, data)34var wpt = require('wpt-api');35var wptClient = new wpt(process.env.WPT_API_KEY);36wptClient.getTestStatus(url, function(err, data) {37 if (err) {38 console.log(err);39 } else {40 console.log(data);41 }42});43### getTestResults(url, callback)44* callback: function(err, data)

Full Screen

Using AI Code Generation

copy

Full Screen

1const wpt = require('wpt-api');2const wptApi = new wpt(process.env.WPT_API_KEY);3const options = {4 videoParams: {5 videoParams: {6 }7 }8};9 .test(options)10 .then(data => {11 console.log('data', data);12 console.log('headers', data.headers);13 console.log('formatted headers', wptApi.formattedHeaders(data.headers));14 })15 .catch(err => {16 console.error(err);17 });18Please read [CONTRIBUTING.md](

Full Screen

Using AI Code Generation

copy

Full Screen

1const wpt = require('wpt-api');2const wptClient = new wpt('API_KEY');3 if (err) {4 console.log(err);5 } else {6 console.log(data);7 }8});9#### new WPT(apiKey, options)

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful