Movatterモバイル変換


[0]ホーム

URL:


Index (R) »AWS »Request
Weannounced the upcoming end-of-support for AWS SDK for JavaScript v2.
We recommend that you migrate toAWS SDK for JavaScript v3. For dates, additional details, and information on how to migrate, please refer to the linked announcement.

Class: AWS.Request

Inherits:
Object
  • Object
  • AWS.Request
show all
Defined in:
lib/request.js

Overview

Asynchronous Requests

All requests made through the SDK are asynchronous and use acallback interface. Each service method that kicks off a requestreturns anAWS.Request object that you can use to registercallbacks.

For example, the following service method returns the requestobject as "request", which can be used to register callbacks:

// request is an AWS.Request objectvar request = ec2.describeInstances();// register callbacks on request to retrieve response datarequest.on('success', function(response) {  console.log(response.data);});

When a request is ready to be sent, thesend() method shouldbe called:

request.send();

Since registered callbacks may or may not be idempotent, requests should onlybe sent once. To perform the same operation multiple times, you will need tocreate multiple request objects, each with its own registered callbacks.

Removing Default Listeners for Events

Request objects are built with default listeners for the various events,depending on the service type. In some cases, you may want to removesome built-in listeners to customize behaviour. Doing this requiresaccess to the built-in listener functions, which are exposed throughtheAWS.EventListeners.Core namespace. For instance, you maywant to customize the HTTP handler used when sending a request. In thiscase, you can remove the built-in listener associated with the 'send'event, theAWS.EventListeners.Core.SEND listener and add your own.

Multiple Callbacks and Chaining

You can register multiple callbacks on any request object. Thecallbacks can be registered for different events, or all for thesame event. In addition, you can chain callback registration, forexample:

request.  on('success', function(response) {    console.log("Success!");  }).  on('error', function(error, response) {    console.log("Error!");  }).  on('complete', function(response) {    console.log("Always!");  }).  send();

The above example will print either "Success! Always!", or "Error! Always!",depending on whether the request succeeded or not.

See Also:

Constructor Summarycollapse

Request Building Eventscollapse

Request Sending Eventscollapse

Data Parsing Eventscollapse

Completion Eventscollapse

HTTP Eventscollapse

HTTP Propertiescollapse

Operation Propertiescollapse

Sending a Requestcollapse

Constructor Details

newAWS.Request(service, operation, params) ⇒void

Creates a request for an operation on a given service witha set of input parameters.

Parameters:

  • service(AWS.Service)

    the service to perform the operation on

  • operation(String)

    the operation to perform on the service

  • params(Object)

    parameters to send to the operation.See the operation's documentation for the format of theparameters.

Event Details

'validate'function (request)

Triggered when a request is being validated. Listenersshould throw an error if the request should not be sent.

Examples:

Ensuring that a certain parameter is set before sending a request

var req = s3.putObject(params);req.on('validate', function() {  if (!req.params.Body.match(/^Hello\s/)) {    throw new Error('Body must start with "Hello "');  }});req.send(function(err, data) { ... });

Parameters:

  • request(Request)

    the request object being sent

See Also:

'build'function (request)

Triggered when the request payload is being built. Listenersshould fill the necessary information to send the requestover HTTP.

Examples:

Add a custom HTTP header to a request

var req = s3.putObject(params);req.on('build', function() {  req.httpRequest.headers['Custom-Header'] = 'value';});req.send(function(err, data) { ... });

Parameters:

  • request(Request)

    the request object being sent

'sign'function (request)

Triggered when the request is being signed. Listeners shouldadd the correct authentication headers and/or adjust the body,depending on the authentication mechanism being used.

Parameters:

  • request(Request)

    the request object being sent

'send'function (response)

Triggered when the request is ready to be sent. Listenersshould call the underlying transport layer to initiatethe sending of the request.

Context (this):

  • (Request)

    the request object that was sent

Parameters:

  • response(Response)

    the response object

See Also:

'retry'function (response)

Triggered when a request failed and might need to be retried or redirected.If the response is retryable, the listener should set theresponse.error.retryable property totrue, and optionally setresponse.error.retryDelay to the millisecond delay for the next attempt.In the case of a redirect,response.error.redirect should be set totrue withretryDelay set to an optional delay on the next request.

If a listener decides that a request should not be retried,it should set bothretryable andredirect to false.

Note that a retryable error will be retried at mostConfig.maxRetries times (based on the service object's config).Similarly, a request that is redirected will only redirect at mostConfig.maxRedirects times.

Context (this):

  • (Request)

    the request object that was sent

Examples:

Adding a custom retry for a 404 response

request.on('retry', function(response) {  // this resource is not yet available, wait 10 seconds to get it again  if (response.httpResponse.statusCode === 404 && response.error) {    response.error.retryable = true;   // retry this error    response.error.retryDelay = 10000; // wait 10 seconds  }});

Parameters:

  • response(Response)

    the response object

'extractError'function (response)

Triggered on all non-2xx requests so that listeners can extracterror details from the response body. Listeners to this eventshould set theresponse.error property.

Context (this):

  • (Request)

    the request object that was sent

Parameters:

  • response(Response)

    the response object

'extractData'function (response)

Triggered in successful requests to allow listeners tode-serialize the response body intoresponse.data.

Context (this):

  • (Request)

    the request object that was sent

Parameters:

  • response(Response)

    the response object

'success'function (response)

Triggered when the request completed successfully.response.data will contain the response data andresponse.error will be null.

Context (this):

  • (Request)

    the request object that was sent

Parameters:

  • response(Response)

    the response object

'error'function (error, response)

Triggered when an error occurs at any point during therequest.response.error will contain details about the errorthat occurred.response.data will be null.

Context (this):

  • (Request)

    the request object that was sent

Parameters:

  • error(Error)

    the error object containing details aboutthe error that occurred.

  • response(Response)

    the response object

'complete'function (response)

Triggered whenever a request cycle completes.response.errorshould be checked, since the request may have failed.

Context (this):

  • (Request)

    the request object that was sent

Parameters:

  • response(Response)

    the response object

'httpHeaders'function (statusCode, headers, response, statusMessage)

Triggered when headers are sent by the remote server

Context (this):

  • (Request)

    the request object that was sent

Parameters:

  • statusCode(Integer)

    the HTTP response code

  • headers(map<String,String>)

    the response headers

  • statusMessage(String)

    A status message corresponding to the HTTPresponse code

  • response(Response)

    the response object

'httpData'function (chunk, response)

Triggered when data is sent by the remote server

Context (this):

  • (Request)

    the request object that was sent

Parameters:

  • chunk(Buffer)

    the buffer data containing the next data chunkfrom the server

  • response(Response)

    the response object

See Also:

'httpUploadProgress'function (progress, response)

Note:

This event will not be emitted in Node.js 0.8.x.

Triggered when the HTTP request has uploaded more data

Context (this):

  • (Request)

    the request object that was sent

Parameters:

  • progress(map)

    An object containing theloaded andtotal bytesof the request.

  • response(Response)

    the response object

'httpDownloadProgress'function (progress, response)

Note:

This event will not be emitted in Node.js 0.8.x.

Triggered when the HTTP request has downloaded more data

Context (this):

  • (Request)

    the request object that was sent

Parameters:

  • progress(map)

    An object containing theloaded andtotal bytesof the request.

  • response(Response)

    the response object

'httpError'function (error, response)

Triggered when the HTTP request failed

Context (this):

  • (Request)

    the request object that was sent

Parameters:

  • error(Error)

    the error object that was thrown

  • response(Response)

    the response object

'httpDone'function (response)

Triggered when the server is finished sending data

Context (this):

  • (Request)

    the request object that was sent

Parameters:

  • response(Response)

    the response object

Property Details

httpRequestAWS.HttpRequest(readonly)

Returns the raw HTTP request objectcontaining request headers and body informationsent by the service.

Returns:

  • (AWS.HttpRequest)

    the raw HTTP request objectcontaining request headers and body informationsent by the service.

startTimeDate(readonly)

Returns the time that the request started.

Returns:

  • (Date)

    the time that the request started

Method Details

abort() ⇒AWS.Request

Note:

This feature is not supported in the browser environment of the SDK.

Aborts a request, emitting the error and complete events.

Examples:

Aborting a request after sending

var params = {  Bucket: 'bucket', Key: 'key',  Body: Buffer.alloc(1024 * 1024 * 5) // 5MB payload};var request = s3.putObject(params);request.send(function (err, data) {  if (err) console.log("Error:", err.code, err.message);  else console.log(data);});// abort request in 1 secondsetTimeout(request.abort.bind(request), 1000);// prints "Error: RequestAbortedError Request aborted by user"

Returns:

  • (AWS.Request)

    the same request object, for chaining.

Since:

  • v1.4.0

createReadStream() ⇒Stream

Note:

The data read from a readable stream contains onlythe raw HTTP body contents.

Note:

This feature is not supported in the browser environment of the SDK.

Sends the request and converts the request object into a readable streamthat can be read from or piped into a writable stream.

Examples:

Manually reading from a stream

request.createReadStream().on('data', function(data) {  console.log("Got data:", data.toString());});

Piping a request body into a file

var out = fs.createWriteStream('/path/to/outfile.jpg');s3.service.getObject(params).createReadStream().pipe(out);

Returns:

  • (Stream)

    the readable stream object that can be pipedor read from (by registering 'data' event listeners).

eachItem(callback) ⇒void

This function is part of anexperimental API. You can use this function, but it may be removed or be changed in the future.

Enumerates over individual items of a request, paging the responses ifnecessary.

Since:

  • v1.4.0

eachPage(callback) ⇒void

Note:

This operation can generate multiple requests to a service.

Iterates over each page of results given a pageable request, callingthe provided callback with each page of data. After all pages have beenretrieved, the callback is called withnull data.

Examples:

Iterating over multiple pages of objects in an S3 bucket

var pages = 1;s3.listObjects().eachPage(function(err, data) {  if (err) return;  console.log("Page", pages++);  console.log(data);});

Iterating over multiple pages with an asynchronous callback

s3.listObjects(params).eachPage(function(err, data, done) {  doSomethingAsyncAndOrExpensive(function() {    // The next page of results isn't fetched until done is called    done();  });});

Callback (callback):

  • function(err, data, [doneCallback]) { ... }

    Called with each page of resulting data from the request. If theoptionaldoneCallback is provided in the function, it must be calledwhen the callback is complete.

    Parameters:

    • err(Error)

      an error object, if an error occurred.

    • data(Object)

      a single page of response data. If there is nomore data, this object will benull.

    • doneCallback(Function)

      an optional done callback. If thisargument is defined in the function declaration, it should be calledwhen the next page is ready to be retrieved. This is useful forcontrolling serial pagination across asynchronous operations.

    Returns:

    • (Boolean)

      if the callback returnsfalse, pagination willstop.

See Also:

Since:

  • v1.4.0

isPageable() ⇒Boolean

Returns whether the operation can return multiple pages ofresponse data.

Returns:

  • (Boolean)

    whether the operation can return multiple pages ofresponse data.

See Also:

  • AWS.Response.eachPage

Since:

  • v1.4.0

promise() ⇒Promise

Sends the request and returns a 'thenable' promise.

Two callbacks can be provided to thethen method on the returned promise.The first callback will be called if the promise is fulfilled, and the secondcallback will be called if the promise is rejected.

Examples:

Sending a request using promises.

var request = s3.putObject({Bucket: 'bucket', Key: 'key'});var result = request.promise();result.then(function(data) { ... }, function(error) { ... });

Callbacks:

  • function(data) { ... }

    Called if the promise is fulfilled.

    Parameters:

    • data(Object)

      the de-serialized data returned from the request.

  • function(error) { ... }

    Called if the promise is rejected.

    Parameters:

    • error(Error)

      the error object returned from the request.

Returns:

  • (Promise)

    A promise that represents the state of the request.

send(callback = null) ⇒void

Sends the request object.

Examples:

Sending a request with a callback

request = s3.putObject({Bucket: 'bucket', Key: 'key'});request.send(function(err, data) { console.log(err, data); });

Sending a request with no callback (using event handlers)

request = s3.putObject({Bucket: 'bucket', Key: 'key'});request.on('complete', function(response) { ... }); // register a callbackrequest.send();

Callback (callback):

  • function(err, data) { ... }

    If a callback is supplied, it is called when a response is returnedfrom the service.

    Context (this):

    Parameters:

    • err(Error)

      the error object returned from the request.Set tonull if the request is successful.

    • data(Object)

      the de-serialized data returned fromthe request. Set tonull if a request error occurs.

Generated on Wed Nov 6 18:52:05 2024 byyard 0.9.36 (ruby-2.5.1).

[8]ページ先頭

©2009-2025 Movatter.jp