AWS sdk does'nt do xhr request in service workers.
sk16 opened this issue · 5 comments
Hi,
AWS SDK uses XML HttpRequest , which is not supported in service worker env.
Modified the code of aws-sdk.js, replaced XmlHttpRequest api with fetch api . Here is modified one :
AWS.XHRClient = AWS.util.inherit({
handleRequest: function handleRequest(httpRequest, httpOptions, callback, errCallback) {
var self = this;
var endpoint = httpRequest.endpoint;
var emitter = new EventEmitter();
var href = endpoint.protocol + '//' + endpoint.hostname;
if (endpoint.port !== 80 && endpoint.port !== 443) {
href += ':' + endpoint.port;
}
href += httpRequest.path;
callback(emitter);
var headers = new Headers();
AWS.util.each(httpRequest.headers, function (key, value) {
if (key !== 'Content-Length' && key !== 'User-Agent' && key !== 'Host') {
headers.set(key, value);
}
});
var credentials = 'omit';
if (httpOptions.xhrWithCredentials) {
credentials = 'include';
}
var request = new Request(href, {
method: httpRequest.method,
headers: headers,
body : httpRequest.body,
credentials: credentials
});
fetch(request).then(function(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}).then(function(response) {
emitter.statusCode = response.status;
emitter.headers = self.parseHeaders(response.headers);
emitter.emit('headers', emitter.statusCode, emitter.headers);
response.text().then(function(res){
console.log(res);
self.finishRequest(res, emitter);
}).catch(function(err){
console.log(err);
});
}).catch(function(err) {
errCallback(AWS.util.error(new Error('Network Failure'), {
code: 'NetworkingError'
}));
});
return emitter;
},
parseHeaders: function parseHeaders(rawHeaders) {
var headers = {};
rawHeaders.forEach(function(val,key){
headers[key] = val;
});
return headers;
},
finishRequest: function finishRequest(res, emitter) {
var buffer;
try {
buffer = new AWS.util.Buffer(res);
} catch (e) {}
if (buffer) emitter.emit('data', buffer);
emitter.emit('end');
}
});
Hi @sk16
Thank you very much for bringing this up. Currently, we don't have story on how to support SDK in service worker, but we are open to any PR if you'd like to contribute to our code base. I will close this issue and you can open a PR for better tracking it.
It would be nice if you submit the test code along with the PR. You can run npm install
then npm run test
to test locally.
@AllanFly120 Can you tell me how to build aws-sdk for node/browser/service worker env. I have created a file service_worker.js under path lib/http , but not able to build for service worker env.
sk16, your code works with cloudflare workers. I overwrite xhr.js AWS.XHRClient part with your code, but I had to remove credentials property in request object.
before this, it won't work with cloudflare workers because of xmlhttp
@zzzxtreme , you can use aws appSync : https://aws.amazon.com/appsync/ , if it fulfill its requirements, it also support service workers and similar env.