ServiceStack: Are "GET" results cached by default? - servicestack

I am running into issue that my second GET request after POST does not get executed at all but returns results prior to POST. I cannot see the request being issued in fiddler at all. If I restart the application then it returns the correct results. I do not have any caching set up. Routes are configured like this:
container.RegisterAutoWired<ComplianceService>().ReusedWithin(ReuseScope.Request);
Routes.Add<CertificateDefinitionList>("/certificates","GET");
Routes.Add<CertificateDefinition>("/certificates/{CertificateDefinitionId}", "GET");
Routes.Add<CertificateDefinitionSave>("/certificates","POST");

There is no implicit Caching in ServiceStack. If you want to Cache responses you need to explicitly request it as seen on the Caching wiki:
public object Get(CachedOrders request)
{
var cacheKey = "unique_key_for_this_request";
return RequestContext.ToOptimizedResultUsingCache(base.Cache,cacheKey, () =>
{
//Delegate is executed if item doesn't exist in cache
//Any response DTO returned here will be cached automatically
});
}

This is probably caused by your proxy which caches results locally. Caching is enabled on http get by default. Specify http caching in your http headers.

Related

nginx can return the cache without invoke the node code?

I have nodejs application and /foo/123 endpoint that access to database to return the data.
router.get('/foo/123', (req, res) => {
const data = getData();
res.json({ data });
});
I want to cache this url for 30 minutes. everyone who invoke the url will get the results from the cache.
I know I can do it with redis to store the data and return the results.
I also know I can set 304 header.
I was thinking to solve it with nginx. using nginx cache to return the data from the url.
My question is does nginx support cache in this way? I mean nginx will stop the request and return the results form the cache without invoking the node code
The user can make a request from the browser (ajax) and can do the request using curl command.

How can I invalidate Google Cloud CDN cache from my express server?

Is there a way to invalidate / clear cached content on Cloud CDN from my express server?
For example, if I'm generating server rendered content to make it readily available and I update a specific route from my website, like editing a blogPost, for example. I need to do the following:
export const editBlogPostHandler = (req,res,next) => {
// 1. UPDATE BLOGPOST WITH SLUG some-blogpost-slug ON DB
// 2. INVALIDATE /some-blogpost-slug ROUTE ON CLOUD CDN CACHE
// THIS IS NECESSARY FOR NEW REQUESTS TO GET FRESH DATA RATHER THAN A STALE DATA RESPONSE
};
How can I do that from my express server?
From Cloud CDN - Invalidating Cached Content:
You can invalidate cached content from Cloud CDN through these methods:
Using the console:
Using gcloud SDK:
There is an API endpoint for that :
https://cloud.google.com/compute/docs/reference/rest/v1/urlMaps/invalidateCache
POST https://compute.googleapis.com/compute/v1/projects/{project}/global/urlMaps/{resourceId}/invalidateCache
As a complement to Alexandre accepted answer, here are more details on how to use this endpoint:
POST https://compute.googleapis.com/compute/v1/projects/{project}/global/urlMaps/{resourceId}/invalidateCache
In order to get the resourceId, you can call the endpoint mentioned here in order to get a list of urlMaps resources and their associated ids.
GET https://compute.googleapis.com/compute/v1/projects/{project}/global/urlMaps
Once you've got the resourceId, you also need to specify the path of the file/folder that you wish to invalidate in the request body (wildcard paths also work):
{ "path": "/folder/file.mp4" }
In the response body, you will find the id of the compute operation - If you want to check this operation progress, you can query it using the Compute Operation Global Get method.
In addition and in order to avoid running the same request several times, it is advised to give a unique requestId parameter under the form of a UUID (as specified in RFC 4122)

Postman Requests Receive a HTTP 401 Status Code

I am working on creating a Node.js REST API, using the Express module, that redirects HTTP GET and PUT requests to another server. However, when running test queries in Postman, I always get HTTP 401 Unauthorized responses. Yet, when I try the same on query on the Chrome browser I get a successful response (HTTP 302). I read through some documentation on the HTTP request/response cycle and authorization. The server I am redirecting to uses HTTP Basic authentication. In my code I am redirecting the API call to my application server using the res.redirect(server) method. In my Postman request I am setting the username/password in Authorization tab for my request. I know this is gets encoded using base64, but I am guessing this isn't being passed on the redirect when done through Postman.
The following code snippets show what I've created thus far.
This is the Express route I created for GET requests
app.get('/companyrecords/:name', function(req, res) {
var credentials = Buffer.from("username:password").toString('base64');
console.log(req);
var requestURL = helperFunctions.createURL(req);
res.redirect(requestURL);
});
I define a function called createURL inside a file called helperFunctions. The purpose of this function is set up the URL to which requests will be directed to. Here is the code for that function.
module.exports.createURL = function (requestURL) {
var pathname = requestURL._parsedUrl.pathname;
var tablename = pathname.split("/")[1];
var filter = `?&filter=name=\'${requestURL.params.hostname}\'`;
var fullPath = BASE_URL + tablename.concat('/') + filter;
console.log(fullPath);
return fullPath;
}
Where BASE_URL is a constant defined in the following form:
http://hostname:port/path/to/resource/
Is this something I need to change in my code to support redirects through Postman or is there a setting in Postman that I need to change so that my queries can execute successfully.
Unfortunately you can't tell Postman not to do what was arguably the correct thing.
Effectively clients should be removing authorisation headers on a redirect. This is to prevent a man-in-the-middle from sticking a 302 in and collecting all your usernames and passwords on their own server. However, as you've noticed, a lot of clients do not behave perfectly (and have since maintained this behaviour for legacy reasons).
As discussed here however you do have some options:
Allow a secondary way of authorising using a query string: res.redirect(302, 'http://appServer:5001/?auth=auth') however this is not great because query strings are often logged without redacting
Act as a proxy and pipe the authenticated request yourself: http.request(authedRequest).on('response', (response) => response.pipe(res))
Respond with a 200 and the link for your client to then follow.

How to prevent RequestLogsFeature from skipping a request after a Gateway call is made during request handling

If a request handler uses the build-in IServiceGateway the request called by the gateway will be logged, not the original request.
e.g.
public object Post(DoSomething request)
{
/* handle request */
Gateway.Send(new DoSomethingElse());
//Request.Items[Keywords.HasLogged] == true at this point
return result;
}
The RequestLogsFeature will log the DoSomethingElse request, set Request.Items[Keywords.HasLogged] = true and not log the DoSomething request.
Is there a way to prevent Gateway from setting the Keywords.HasLogged flag to true? Thanks!
This issue has already been resolved where ServiceStack won't log or flag In Process Requests. So if you upgrade to the latest v5.4 on NuGet you should no longer have this issue.

NodeJS HTTP - Removing a header from request to be proxied

I have a NodeJS proxy service which obfuscates some data and forwards the request to another service. Due to some details surrounding how we, and the servcie we're proxying to handle authentication, we need to remove a certain header from the incoming request before we proxy it.
I saw some documentation about request such as: "This object is created internally and returned from http.request(). It represents an in-progress request whose header has already been queued. The header is still mutable using the setHeader(name, value), getHeader(name), removeHeader(name) API."
But then the same documentation says the headers are read-only. I also saw some documentation that showed those methods (removeHeader, etc) being available, and others that don't list it.
Can someone tell me if there's a way to remove a header from the request object itself before copying the headers over? If not is there an easy way to copy over all the headers except the one I want to leave out?
Came here looking for a solution, but for node-http-proxy. You can do it by listening to proxyReq event on the proxy and then calling removeHeader on the proxy request object, like so
myProxy.on("proxyReq", function(proxyReq, req, _, options) {
proxyReq.removeHeader("x-my-header");
});

Resources