PATCH request ignored due to use of an 'auto-add' method in main controller - sinatra

In writing a Sinatra app, I added a function to my config.ru file to automatically use additional controllers, while also running my main Application Controller (last line of code below). All tests passed up until the PATCH edit request, which was not even being recognized in the controller (I tried prying within the request).
See config.ru code below; why would PATCH (and I assume DELETE) not be recognized when using the method below to auto-add controllers? When I added "use SongsController...ect" that is shown at the bottom of my code below, my app worked like a charm. Thanks in advance.
require './config/environment'
if ActiveRecord::Migrator.needs_migration?
raise 'Migrations are pending. Run `rake db:migrate` to resolve the issue.'
end
# auto-add controllers
Dir[File.join(File.dirname(__FILE__), "app/controllers", "*.rb")].collect {|file| File.basename(file).split(".")[0] }.reject {|file| file == "application_controller" }.each do |file|
string_class_name = file.split('_').collect { |w| w.capitalize }.join
class_name = Object.const_get(string_class_name)
use class_name
end
use Rack::MethodOverride
use SongsController
use ArtistsController
use GenresController
run ApplicationController

If your requests are coming from a browser then they will in reality be POST requests, not PATCH or DELETE (as GET and POST are the only methods browsers use). In order to use other HTTP verbs Sinatra relies on the Rack::MethodOverride middleware which converts the request to the correct type if there is a hidden _method parameter.
You have this middleware in your config, but it is after your code to find and add your other controllers. This means that when a request arrives it will not have been modified to be the appropriate type when those controllers see it, and so they will treat it as a POST and not PATCH and ignore it.
The fix is simply to move the line use Rack::MethodOverride to before the code to auto-add your other controllers, so requests are modified before your controllers see them.

Related

Expecting arguments in Mojolicious routes

I have two routes in Mojolicious app as follows:
my $route = $r->any('/api')->to('API#');
$route->get('/get_data')->to('#process_forms');
$route->get('/get_data/?file=:file&name=:name')->to('#submit_forms');
if I go to /api/get_data I get redirected to process_forms function. I want the app to take me to submit_forms function if I pass additional arguments to that same route. for example, url /api/get_data/?file=myfile&name=myname should call submit_forms function, but that's not the case here.
In both scenarios, process_forms is called.
What option Mojolicious routing provides to help me with this?
Mojo's router connects URL and HTTP request methods to controllers. The GET and POST parameters are not used in routing. This makes sense, because a URL is typically supposed to target a resource by itself.
You have a path /get_data you need to send that to one controller. From there you want it sounds like you want to do is to go to another controller if you have GET parameters (passed in the URL). You can do this, but it's not normally what you want.
Just putting a conditional in a controller,
What you normally want when handling get parameters is simply to put them inside a block in the controller, IE,
my $query = $c->req->query_params
my $file = $query->param('foo');
my $name = $query->param('name');
if ( defined $file && defined $name) {
# we have file and name
}
else {
# or we do not
}
Redispatch
But you can always redispatch to a different controller (manually)
MyApp::Controller::submit_forms($self);
Or, through Mojo,
$self->routes->continue("#submit_forms")
As a last idea, you can also make it that the route doesn't match if the post variables aren't there. But, I've never needed to do this.

How to extend res.json in sailsjs

I need to extend res.json so that the response goes out as text with a csrf token eg
&&&CSRF&&&{foo:bar}
Sails seems to use a different csrf methodology, but I need to do it this way to match the preexisting client side codebase.
Ideally I need to be able to create a new function:
return res.jsonWithCsrf({
foo: bar
});
Internally this would call res.json but would wrap the csfr token around the response.
I gather that I need to write a hook but am unsure how to do it.
You can create custom responses by placing your file in the api/responses directory.
You can see the files that are already there, modify them if you want, or create your own.
If you were to create jsonWithCsrf.js in that folder, then you can access it in the manner you describe above.
res.jsonWithCsrf()
http://sailsjs.org/#!/documentation/concepts/Custom-Responses

Grails - RESTful Web service responds with 404 when controller is defined

I defined a domain model class with a few properties and marked it as a RESTful resource using #Resource following the official Grails guide on Web services. Now, when testing the application (using Ruby's RestClient) I can see that things are working fine. However, after defining an associated Controller that overrides save method (for creating new resource), I've been getting 404 even on just simple GET requests. I defined some test objects using BootStrap so GET should be working.
My controller code looks like this:
class ModelController {
#Transactional
def save(Model model) {
def status = 201
if (model.validate()) {
model.save(flush: true, failOnError: true)
} else {
status = 422
}
render status:status
}
}
Do I still need to do something with the UrlMappings.groovy or is there something wrong with my controller code (all my unit tests for it are passing though)?
Update
I have created a sample project to demonstrate what's happening. Please check my bookstore-demo repository on GitHub. In the repository, I've defined 2 tags, rest-working, and rest-not-working. The first one marks the point where things are still working, and second one, as the name suggests, marks where I've created a controller that causes 404 response. This is pretty much what I've done with my actual project so far, and I'm getting the the same error.
The code looks OK, if you are getting a 404 then it sounds like its not even hitting this Controller. I would open developer console and try capture what URL it is hitting - URL being sent is potentially incorrect. If I am experimenting I tend to put println "1" println "2" and so on between my logics to see where the code is going or did it return it at all meaning it didn't even get there. so maybe if you doubt your code try this tactic between your if statements see which numbers get hit.
Also there is not a lot to go on to try give anything of more useful as feedback, but I would also check out the allowedMethods of this Controller if any defined...
unsure how it is being posted by if you have ..
static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
try changing it to
static allowedMethods = [update: "POST", delete: "POST"]
unsure if this is still supported:
static allowedMethods = [save:['POST','GET'],update: "POST", delete: "POST"]
For all the methods refer to:
http://grails.org/doc/latest/ref/Controllers/allowedMethods.html

Creating a REST service in Sitecore

I'm trying to build a REST service in a Sitecore root. My application start looks like this:
void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = System.Web.Http.RouteParameter.Optional });
}
And my URL looks like this:
http://{mydomain}/api/books
I have the correct controller and all that.
But Sitecore keeps redirecting me to the 404 page. I've added the path to the IgnoreUrlPrefixes node in the web.config, but to no avail. If I had to guess, I'd think that Sitecore's handler is redirecting before my code gets the chance to execute, but I really don't know.
Does anybody have any idea what might be wrong?
Your assessment is correct. You need a processor in the httpRequestBegin pipeline to abort Sitecore's processing. See the SystemWebRoutingResolver in this answer:
Sitecore and ASP.net MVC
It's also described in this article:
http://www.sitecore.net/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2010/10/Sitecore-MVC-Crash-Course.aspx
But I'll include the code here as well. :)
public class SystemWebRoutingResolver : Sitecore.Pipelines.HttpRequest.HttpRequestProcessor
{
public override void Process(Sitecore.Pipelines.HttpRequest.HttpRequestArgs args)
{
RouteData routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(args.Context));
if (routeData != null)
{
args.AbortPipeline();
}
}
}
Then in your httpRequestBegin configuration:
<processor type="My.SystemWebRoutingResolver, My.Classes" />
You might want to have a look at Sitecore Web Api
It's pretty much the same you are building.
Another option, which I've used to good effect, is to use the content tree, the "star" item, and a sublayout/layout combination dedicated to this purpose:
[siteroot]/API/*/*/*/*/*/*/*/*/*
The above path allows you to have anywhere between 1 and 9 segments - if you need more than that, you probably need to rethink your process, IMO. This also retains all of the Sitecore context. Sitecore, when unable to find an item in a folder, attempts to look for the catch-all star item and if present, it renders that item instead of returning a 404.
There are a few ways to go about doing the restful methods and the sublayout (or sublayouts if you want to segregate them by depth to simplify parsing).
You can choose to follow the general "standard" and use GET, PUT, and POST calls to interact with these items, but then you can't use Sitecore Caching without custom backend caching code). Alternately, you can split your API into three different trees:
[siteroot]/API/GET/*/*/*/*/*/*/*/*/*
[siteroot]/API/PUT/*/*/*/*/*/*/*/*/*
[siteroot]/API/POST/*/*/*/*/*/*/*/*/*
This allows caching the GET requests (since GET requests should only retrieve data, not update it). Be sure to use the proper caching scheme, essentially this should cache based on every permutation of the data, user, etc., if you intend to use this in any of those contexts.
If you are going to create multiple sublayouts, I recommend creating a base class that handles general methods for GET, PUT, and POST, and then use those classes as the base for your sublayouts.
In your sublayouts, you simply get the Request object, get the path (and query if you're using queries), split it, and perform your switch case logic just as you would with standard routing. For PUT, use Response.ReadBinary(). For POST use the Request.Form object to get all of the form elements and iterate through them to process the information provided (it may be easiest to put all of your form data into a single JSON object, encapsulated as a string (so .NET sees it as a string and therefore one single property) and then you only have one element in the post to deserialize depending on the POST path the user specified.
Complicated? Yes. Works? Yes. Recommended? Well... if you're in a shared environment (multiple sites) and you don't want this processing happening for EVERY site in the pipeline processor, then this solution works. If you have access to using MVC with Sitecore or have no issues altering the pipeline processor, then that is likely more efficient.
One benefit to the content based method is that the context lifecycle is exactly the same as a standard Sitecore page (logins, etc.), so you've got all the same controls as any other item would provide at that point in the lifecycle. The negative to this is that you have to deal with the entire page lifecycle load before it gets to your code... the pipeline processor can skip a lot of Sitecore's process and just get the data you need directly, making it faster.
you need to have a Pipeline initializer for Routing:
It will be like :
public class Initializer
{
public void Process(PipelineArgs args)
{
RouteCollection route = RouteTable.Routes;
route.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{id}",
new { id = RouteParameter.Optional });
}
}
On config file you will have :
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<initialize>
<processor type="_YourNameSpace.Initializer,_YourAssembly" />
</initialize>
</pipelines>
</sitecore>
</configuration>
Happy coding

Perl Dancer after hook

Is there a way in Dancer to execute a code after every request?
I tried with an after hook but it seems that it doesn't execute after a file request...
There is a hook called 'after_file_render' which is executed a decent number of times after each request but I am not sure what is its purpose. Is it always called after every request?
The after_file_render hook is run after each successful request for a static file (e.g., a CSS file or an image), while the after hook runs after an action is performed by a route handler.
If you want to run the same code for both after and after_file_render, you can put it in a subroutine and assign it to the two hooks using a reference, e.g.:
sub foo {
...
}
hook after_file_render => \&foo;
hook after => \&foo;