Best JavaScript code snippet using redwood
HttpConnection.ts
Source:HttpConnection.ts
...125 try {126 if (this.options.skipNegotiation) {127 if (this.options.transport === HttpTransportType.WebSockets) {128 // No need to add a connection ID in this case129 this.transport = this.constructTransport(HttpTransportType.WebSockets);130 // We should just call connect directly in this case.131 // No fallback or negotiate in this case.132 await this.transport!.connect(url, transferFormat);133 } else {134 throw Error("Negotiation can only be skipped when using the WebSocket transport directly.");135 }136 } else {137 let negotiateResponse: INegotiateResponse | null = null;138 let redirects = 0;139 do {140 negotiateResponse = await this.getNegotiationResponse(url);141 // the user tries to stop the connection when it is being started142 if (this.connectionState === ConnectionState.Disconnected) {143 return;144 }145 if (negotiateResponse.error) {146 throw Error(negotiateResponse.error);147 }148 if ((negotiateResponse as any).ProtocolVersion) {149 throw Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");150 }151 if (negotiateResponse.url) {152 url = negotiateResponse.url;153 }154 if (negotiateResponse.accessToken) {155 // Replace the current access token factory with one that uses156 // the returned access token157 const accessToken = negotiateResponse.accessToken;158 this.accessTokenFactory = () => accessToken;159 }160 redirects++;161 }162 while (negotiateResponse.url && redirects < MAX_REDIRECTS);163 if (redirects === MAX_REDIRECTS && negotiateResponse.url) {164 throw Error("Negotiate redirection limit exceeded.");165 }166 await this.createTransport(url, this.options.transport, negotiateResponse, transferFormat);167 }168 if (this.transport instanceof LongPollingTransport) {169 this.features.inherentKeepAlive = true;170 }171 this.transport!.onreceive = this.onreceive;172 this.transport!.onclose = (e) => this.stopConnection(e);173 // only change the state if we were connecting to not overwrite174 // the state if the connection is already marked as Disconnected175 this.changeState(ConnectionState.Connecting, ConnectionState.Connected);176 } catch (e) {177 this.logger.log(LogLevel.Error, "Failed to start the connection: " + e);178 this.connectionState = ConnectionState.Disconnected;179 this.transport = undefined;180 throw e;181 }182 }183 private async getNegotiationResponse(url: string): Promise<INegotiateResponse> {184 let headers;185 if (this.accessTokenFactory) {186 const token = await this.accessTokenFactory();187 if (token) {188 headers = {189 ["Authorization"]: `Bearer ${token}`,190 };191 }192 }193 const negotiateUrl = this.resolveNegotiateUrl(url);194 this.logger.log(LogLevel.Debug, `Sending negotiation request: ${negotiateUrl}.`);195 try {196 const response = await this.httpClient.post(negotiateUrl, {197 content: "",198 headers,199 });200 if (response.statusCode !== 200) {201 throw Error(`Unexpected status code returned from negotiate ${response.statusCode}`);202 }203 return JSON.parse(response.content as string) as INegotiateResponse;204 } catch (e) {205 this.logger.log(LogLevel.Error, "Failed to complete negotiation with the server: " + e);206 throw e;207 }208 }209 private createConnectUrl(url: string, connectionId: string | null | undefined) {210 if (!connectionId) {211 return url;212 }213 return url + (url.indexOf("?") === -1 ? "?" : "&") + `id=${connectionId}`;214 }215 private async createTransport(url: string, requestedTransport: HttpTransportType | ITransport | undefined, negotiateResponse: INegotiateResponse, requestedTransferFormat: TransferFormat): Promise<void> {216 let connectUrl = this.createConnectUrl(url, negotiateResponse.connectionId);217 if (this.isITransport(requestedTransport)) {218 this.logger.log(LogLevel.Debug, "Connection was provided an instance of ITransport, using that directly.");219 this.transport = requestedTransport;220 await this.transport.connect(connectUrl, requestedTransferFormat);221 // only change the state if we were connecting to not overwrite222 // the state if the connection is already marked as Disconnected223 this.changeState(ConnectionState.Connecting, ConnectionState.Connected);224 return;225 }226 const transports = negotiateResponse.availableTransports || [];227 for (const endpoint of transports) {228 this.connectionState = ConnectionState.Connecting;229 const transport = this.resolveTransport(endpoint, requestedTransport, requestedTransferFormat);230 if (typeof transport === "number") {231 this.transport = this.constructTransport(transport);232 if (!negotiateResponse.connectionId) {233 negotiateResponse = await this.getNegotiationResponse(url);234 connectUrl = this.createConnectUrl(url, negotiateResponse.connectionId);235 }236 try {237 await this.transport!.connect(connectUrl, requestedTransferFormat);238 this.changeState(ConnectionState.Connecting, ConnectionState.Connected);239 return;240 } catch (ex) {241 this.logger.log(LogLevel.Error, `Failed to start the transport '${HttpTransportType[transport]}': ${ex}`);242 this.connectionState = ConnectionState.Disconnected;243 negotiateResponse.connectionId = undefined;244 }245 }246 }247 throw new Error("Unable to initialize any of the available transports.");248 }249 private constructTransport(transport: HttpTransportType) {250 switch (transport) {251 case HttpTransportType.WebSockets:252 if (!this.options.WebSocket) {253 throw new Error("'WebSocket' is not supported in your environment.");254 }255 return new WebSocketTransport(this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent || false, this.options.WebSocket);256 case HttpTransportType.ServerSentEvents:257 if (!this.options.EventSource) {258 throw new Error("'EventSource' is not supported in your environment.");259 }260 return new ServerSentEventsTransport(this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent || false, this.options.EventSource);261 case HttpTransportType.LongPolling:262 return new LongPollingTransport(this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent || false);263 default:264 throw new Error(`Unknown transport: ${transport}.`);265 }266 }267 private resolveTransport(endpoint: IAvailableTransport, requestedTransport: HttpTransportType | undefined, requestedTransferFormat: TransferFormat): HttpTransportType | null {268 const transport = HttpTransportType[endpoint.transport];269 if (transport === null || transport === undefined) {270 this.logger.log(LogLevel.Debug, `Skipping transport '${endpoint.transport}' because it is not supported by this client.`);271 } else {272 const transferFormats = endpoint.transferFormats.map((s) => TransferFormat[s]);273 if (transportMatches(requestedTransport, transport)) {274 if (transferFormats.indexOf(requestedTransferFormat) >= 0) {275 if ((transport === HttpTransportType.WebSockets && !this.options.WebSocket) ||276 (transport === HttpTransportType.ServerSentEvents && !this.options.EventSource)) {277 this.logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it is not supported in your environment.'`);278 } else {279 this.logger.log(LogLevel.Debug, `Selecting transport '${HttpTransportType[transport]}'.`);280 return transport;281 }282 } else {283 this.logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it does not support the requested transfer format '${TransferFormat[requestedTransferFormat]}'.`);284 }285 } else {286 this.logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it was disabled by the client.`);287 }288 }289 return null;290 }291 private isITransport(transport: any): transport is ITransport {292 return transport && typeof (transport) === "object" && "connect" in transport;293 }294 private changeState(from: ConnectionState, to: ConnectionState): boolean {295 if (this.connectionState === from) {296 this.connectionState = to;297 return true;298 }299 return false;300 }301 private stopConnection(error?: Error): void {302 this.transport = undefined;303 // If we have a stopError, it takes precedence over the error from the transport304 error = this.stopError || error;305 if (error) {...
transport.js
Source:transport.js
...11} from "../actions/types";12 13import TransportService from '../../service/TransportService'14export const getTransport = (transportData) => (dispatch) => {15 return TransportService.getAllTransport(transportData)16 .then((response) => {17 dispatch({18 type: TRANSPORT_SET_IS_LOADING,19 payload: true20 })21 dispatch({22 type: SET_TRANSPORTS,23 payload: response.data.objects24 })25 dispatch({26 type: TRANSPORT_SET_TOTAL_PAGES,27 payload: response.data.totalPages28 })29 dispatch({30 type: TRANSPORT_SET_TOTAL_ELEMENTS,31 payload: response.data.totalElements32 })33 dispatch({34 type: TRANSPORT_SET_IS_LOADING,35 payload: false36 })37 return Promise.resolve(response.data)38 })39 .catch(error => {40 return Promise.reject(error)41 })42}43export const addTransport = (transportData) => (dispatch) => {44 return TransportService.addTransport(transportData).then(45 response => {46 dispatch({47 type: ADD_TRANSPORT,48 payload: response.data49 })50 return Promise.resolve(response)51 },52 error => {53 return Promise.reject(error)54 }55 )56}57export const updateTransport = (id, patchData) => (dispatch) => {58 return TransportService.updateTransport(id, patchData)59 .then((data) => {60 return Promise.resolve(data)61 })62 .catch(error => {63 return Promise.reject(error)64 })65}66export const deleteTransport = (id) => (dispatch) => {67 return TransportService.deleteTransport(id).then((data) => {68 return Promise.resolve(id)69 })70}71export const setPage = (page) => (dispatch) => {72 dispatch({73 type: TRANSPORT_SET_PAGE,74 payload: page75 })76}77export const setSize = (size) => (dispatch) => {78 dispatch({79 type: TRANSPORT_SET_SIZE,80 payload: size81 })...
iframe-wrap.js
Source:iframe-wrap.js
...3 , IframeTransport = require('../iframe')4 , objectUtils = require('../../utils/object')5 ;6module.exports = function(transport) {7 function IframeWrapTransport(transUrl, baseUrl) {8 IframeTransport.call(this, transport.transportName, transUrl, baseUrl);9 }10 inherits(IframeWrapTransport, IframeTransport);11 IframeWrapTransport.enabled = function(url, info) {12 if (!global.document) {13 return false;14 }15 var iframeInfo = objectUtils.extend({}, info);16 iframeInfo.sameOrigin = true;17 return transport.enabled(iframeInfo) && IframeTransport.enabled();18 };19 IframeWrapTransport.transportName = 'iframe-' + transport.transportName;20 IframeWrapTransport.needBody = true;21 IframeWrapTransport.roundTrips = IframeTransport.roundTrips + transport.roundTrips - 1; // html, javascript (2) + transport - no CORS (1)...
Using AI Code Generation
1const { Transport } = require('@redwoodjs/api')2exports.handler = async (event, context) => {3 const { data, errors } = await Transport.request(`4 query {5 posts {6 }7 }8 if (errors) {9 return {10 body: JSON.stringify(errors),11 }12 }13 return {14 body: JSON.stringify({15 }),16 }17}
Using AI Code Generation
1var redwood = require('redwood');2var transport = redwood.transport;3var myTransport = new transport();4var myConnection = myTransport.createConnection();5var myChannel = myTransport.createChannel();6myConnection.open({host:'localhost', port: 5672});7myChannel.open({connection: myConnection});8myChannel.setConfirmMode();9myChannel.publish('test', {content: 'hello world'});10myChannel.close();11myConnection.close();12var redwood = require('redwood');13var transport = redwood.transport;14var myTransport = new transport();15var myConnection = myTransport.createConnection();16var myChannel = myTransport.createChannel();17myConnection.open({host:'localhost', port: 5672});18myChannel.open({connection: myConnection});19myChannel.setConfirmMode();20myChannel.publish('test', {content: 'hello world'});21myChannel.close();22myConnection.close();23var redwood = require('redwood');24var transport = redwood.transport;25var myTransport = new transport();26var myConnection = myTransport.createConnection();27var myChannel = myTransport.createChannel();28myConnection.open({host:'localhost', port: 5672});29myChannel.open({connection: myConnection});30myChannel.setConfirmMode();31myChannel.publish('test', {content: 'hello world'});32myChannel.close();33myConnection.close();34var redwood = require('redwood');35var transport = redwood.transport;
Using AI Code Generation
1const transport = require('@redwoodjs/api')2exports.handler = transport.http(function (req, res) {3 res.send({4 })5})6exports.handler = transport.graphql(function (req, res) {7 res.send({8 })9})10exports.handler = transport.webSocket(function (req, res) {11 res.send({12 })13})
Using AI Code Generation
1const redwood = require('redwood-client');2const client = new redwood.Client('localhost:50051');3const transport = client.transport('Transport');4const request = {5};6transport.send(request, (err, response) => {7 console.log('Transport response: ' + response.message);8});
Using AI Code Generation
1var redwood = require('redwood');2var transport = require('redwood-transport');3var transport = new Transport({4});5var redwood = new Redwood({6});7redwood.log('test', 'hello world!');8transport.log('test', 'hello world!');9redwood.log('test', 'hello world!');10transport.log('test', 'hello world!');
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!