Chrome DevTools protocol: how to configure a RequestPattern to capture all requests except those sent from the service server - chrome-devtools-protocol

I need to handle all request except those sent from the service server.
At present, I do it using such a way: capture all requests and into handler filter service requests.
await client.Fetch.enable({
patterns: [
{ requestStage: 'Request' },
{ requestStage: 'Response' }
], // handle all requests and responses.
});
client.Fetch.on('requestPaused', async (event: RequestPausedEvent) => {
if (isServiceRoute(event.request.url))
await continueRequestOrResponse(client, event);
...
// Handle the necessary events
});
Question: Can I do this at client.Fetch.enable() stage? E.g setup the the patterns filter so, it passes all requests (*) and rejects the service routes (started from https://service-domain-1.company.com and https://service-domain-2.company.com).

Related

Adding CORS support to AWS API Gateway endpoints

Reading the documentation: https://docs.aws.amazon.com/cdk/api/v1/docs/aws-apigateway-readme.html
It's not clear to me that specifying CORS on an endpoint means that it only applies to that level, or all the sub-resources as well?
F.e.,
let's say I add a method at resource path - /products and
declare const productsResource: apigateway.Resource;
productsResource.addCorsPreflight({
allowOrigins: [ 'https://amazon.com' ],
allowMethods: [ 'GET', 'PUT' ]
Does that apply to /products/{productdId} as well?
});
Or do I need a separate addCorsPreflight() call for that sub-resource?
It depends on how that sub resource is defined.
If it is an actual Resource, i believe the answer is yes - you do need to define it for all other defined resources. Doing this for any given resource that is NOT a proxy connection will enable the OPTIONS method on your resource.
However if its a Proxy end point (which as a product ID i would expect) linked to a lambda it has to handle the Cors Preflight response itself.
Youd have to, for instance, (NOT working code, you need to define how to know if this is a preflight or not based on the incoming event from Api Gateway that triggers the lambda)
exports.handler = async (event) => {
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin": "https://www.example.com",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET"
},
body: JSON.stringify('Hello from Lambda!'),
};
if preflight:
return response;
};
Find more information here: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html

Service workers "sync" operation is working while its offline?

I have a PWA project where I send the data to server. During this process, if the user is offline then the data is stored in indexedDb and a sync tag is registered. So, then when the user comes online that data can sent to the server.
But In my case the sync event gets executed immediately when the we register a sync event tag, which means the data is tried to be sent to server while its offline, which is not going to work.
I think the sync event supposed to fire while its online only, what could be issue here ?
The service worker's sync event works accordingly when I tried to enable and disable the offline option of chrome devtools, and also works correctly in my android phone.
This is how I register my sync tag
function onFailure() {
var form = document.querySelector("form");
//Register the sync on post form error
if ('serviceWorker' in navigator && 'SyncManager' in window) {
navigator.serviceWorker.ready
.then(function (sw) {
var post = {
datetime1: form.datetime1.value,
datetime: form.datetime.value,
name: form.name.value,
image: form.url.value,
message: form.comment.value
};
writeData('sync-comments', post)
.then(function () {
return sw.sync.register('sync-new-comment');
})
.then(function () {
console.log("[Sync tag registered]");
})
.catch(function (err) {
console.log(err);
});
});
}
}
And this is how the sync event is called
self.addEventListener('sync', function (event) {
console.log("[Service worker] Sync new comment", event);
if (event.tag === 'sync-new-comment') {
event.waitUntil(
readAllData('sync-comments')
.then(function (data) {
setTimeout(() => {
data.forEach(async (dt) => {
const url = "/api/post_data/post_new_comment";
const parameters = {
method: 'POST',
headers: {
'Content-Type': "application/json",
'Accept': 'application/json'
},
body: JSON.stringify({
datetime: dt.datetime,
name: dt.name,
url: dt.image,
comment: dt.message,
datetime1: dt.datetime1,
})
};
fetch(url, parameters)
.then((res) => {
return res.json();
})
.then(response => {
if (response && response.datetimeid) deleteItemFromData('sync-comments', response.datetimeid);
}).catch((error) => {
console.log('[error post message]', error.message);
})
})
}, 5000);
})
);
}
});
you mention
The service worker's sync event works accordingly when I tried to enable and disable the offline option of chrome devtools, and also works correctly in my android phone.
So I'm not sure which case is the one failing.
You are right that the sync will be triggered when the browser thinks the user is online, if the browser detects that the user is online at the time of the sync registration it will trigger the sync:
In true extensible web style, this is a low level feature that gives you the freedom to do what you need. You ask for an event to be fired when the user has connectivity, which is immediate if the user already has connectivity. Then, you listen for that event and do whatever you need to do.
Also, from the workbox documentation
Browsers that support the BackgroundSync API will automatically replay failed requests on your behalf at an interval managed by the browser, likely using exponential backoff between replay attempts.

socket.io-client Jest testing inconsistent results

I am writing some end-to-end test cases to test socket connections in my app. I expect receiving socket events after specific rest API requests. For instance, after hitting: /api/v1/[createTag], I expect receiving createTag event to be captured by socket.io-client. The issue is that, it is very inconsistently passing, and sometimes failing, with good rest API requests. The reason to fail is that done() event inside socket.on('createTag' ... is never called, so it gets timeout. On browser, currently all the API endpoints and sockets seem to be working fine. Is there a specific configuration that I might be missing in order to test socket.io-client within Node.js environment and Jest?
Below is my test cases, and thanks a lot in advance:
describe('Socket integration tests: ', () => {
beforeAll(async done => {
await apiInit();
const result = await requests.userSignIn(TEST_MAIL, TEST_PASSWORD);
TEST_USER = result.user;
SESSION = result.user.session;
console.log('Test user authenticated succesfully.');
done();
});
beforeEach(done => {
socket = io(config.socket_host, { forceNew: true })
socket.on('connect', () => {
console.log('Socket connection succesful.');
socket.emit('session', { data: SESSION }, (r) => {
console.log('Socket session successful.');
done();
});
});
})
test('Receiving createTag socket event?', async(done) => {
console.log('API request on createTag');
const response = await Requester.post(...);
console.log('API response on createTag', response);
socket.on('createTag', result => {
console.log('createTag socket event succesful.');
createdTagXid = result.data.xid;
done();
})
});
afterEach(done => {
if(socket.connected) {
console.log('disconnecting.');
socket.disconnect();
} else {
console.log('no connection to break');
}
done();
})
}
Basically, setting event handles after async API calls seems to be the issue. So I should have first set the socket.on( ... and then call rest API.

RabbitMQ Publish to Exchange Confirmation

I would like to return a retrieve a confirmation that the message was successfully published to the exchange before closing the AMQP connection. At the moment, I am using a timeout function to allow for the message to be published before closing the connection. This is not the right way. Can someone please help to retrieve a confirmation so I can close the connection based on a successful publish?
The code I am using is below:
function toExchange(msg)
{
amqp.connect('amqp://localhost:5672', function(err, conn) //local connection
{
conn.createChannel(function(err, ch)
{
var exchange = 'MessageExchange';
ch.assertExchange(exchange, 'fanout', {durable: true});
ch.publish(exchange, '', new Buffer(msg));
console.log("Sent to Exchange: %s", msg);
});
setTimeout(function() { conn.close(); }, 5000);
});
}
You can use a RabbitMQ extension called "Publisher confirms". Here is more information: https://www.rabbitmq.com/confirms.html#publisher-confirms.
You are not notified when the message is published to the exchange, but when it is published and routed to all queues: https://www.rabbitmq.com/confirms.html#when-publishes-are-confirmed
In your case using amqplib in nodeJS you can use this snippet of code: https://www.squaremobius.net/amqp.node/channel_api.html#confirmchannel
It uses the callback #waitForConfirms(function(err) {...}) that triggers when all published messages have been confirmed.

How to stub some requests and call real service for others using stubby4j

I am using stubby4j to stub some service endpoints. I am currently stubbing the ones that are very heavy and not so complex to mock but I would like to call the real service for the rest of the endpoints.
Something like this:
/heavy-call-1 => stub service
/heavy-call-2 => stub service
/lightweight-call-1 => real service
/lightweight-call-2 => real service
Is there a way I can achieve this with this tool or should I consider using a different one?
You can actually make stubby call the real service and record the response for the first time, so the next requests will use this recorded response.
The way you can do this is by specifying an URL in the body of the stubbed response in your yaml file like this:
- request:
url: /1.1/direct_messages.json
query:
since_id: 240136858829479935
count: 1
response:
headers:
content-type: application/json
body: https://api.twitter.com/1.1/direct_messages.json?since_id=240136858829479935&count=1
You can find some more information in the stubby github docs: https://stubby4j.com/#key-features and https://stubby4j.com/docs/http_endpoint_configuration_howto.html#record-and-replay
Hope this helps!
Are you using webpack? If so, you can match different domains. For example:
const config = merge(common, {
devtool: 'inline-source-map',
mode: 'development',
devServer: {
historyApiFallback: true,
port: 3000,
hot: true,
proxy: [
{ path: '/heavy-all-1 ', target: 'http://localhost:8882' }, //stubby
],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development'),
}),
],
});
And the URLs that don't have the prefix described won't be stubbed.