How should I respond with different status codes to a GET request in Spray? - spray

For POST and PUT requests I use the following syntax:
put {
entity(as[CaseClass]) { entity =>
returnsOption(entity).map(result => complete{(Created, result)})
.getOrElse(complete{(NotFound, "I couldn't find the parent resource you're modifying")})
}
}
Now for GET requests I'm trying to do the same, but I can't get it to work analogously to my PUT solution. What is a good way to do this with GET requests?
Update:
I've got this working with the following hack:
(get & parameters('ignored.?)) {
//TODO find a way to do this without ignored parameters
(ingored:Option[String]) => {
returnsOption().map(result => complete(result))
.getOrElse(complete{(NotFound, "")})
}
}
I'd expect something similar to be possible with () => or ctx => , but that doesn't fly, because it gives trouble with marshalling:
... could not find implicit value for evidence parameter of type spray.httpx.marshalling.Marshaller[(spray.http.StatusCodes.ClientError, String)]
}).getOrElse(ctx.complete{(NotFound, "")})
^
Could it be that this somehow relates to the fact that I'm using spray-json?

Use HttpResponse like this for example
complete{
HttpResponse(StatusCodes.OK, HttpBody(ContentType(`text/html`), "test test: " + System.currentTimeMillis.toString))
}
Update: I've been using Spray for a while now. Turned out there is better way:
complete {
StatusCodes.BandwidthLimitExceeded -> MyCustomObject("blah blah")
}

This code should work:
get {
ctx =>
ctx.complete(returnsOption())
}
If don't use ctx => at the start, your code might only be executed at route build time.
Here you can find some explanations: Understanding the DSL Structure

Related

Receiving The 'task' event has not been registered in the plugins file. You must register it before using cy.task()

I don't know how to use the task and for which purpose, I have one project and I have got this project for solving errors. and I am getting this error. Any help or suggestions are welcome.
I have this code in my plugins/index.js file.
module.exports = (on, config) => {
on("task", { "setUserId": (val) => { return (userId = val); }});
};
And in my test i have implement like this.
cy.task('setUserId', randomEmail);
I got this below error.

Why does my FactoryBot definition not see my lambda definition (Ruby,Rspec)

I am attempting to define a lambda in a FactoryBot like so...
contact_methods = %w[Phone Email Snail\ Mail Carrier\ Pigeon]
factory :my_object do
transient do
remove_used_value = -> (x,y) { x.reject { |a| a == y }.sample }
end
first_contact_option { contact_methods.sample }
second_contact_option { remove_used_value.call(contact_methods,first_contact_option) }
end
However, when I run FactoryBot.create(:my_object) I get the error undefined method remove_used_value for #<FactoryBot::SyntaxRunner:0x00007fb2ac238960>
I define this as a lambda because there are several other fields that need this same functionality in the Bot. The strange thing is that this was working just fine yesterday, except the logic in the lambda wasn't returning the expected result. After reworking the logic and testing the lambda in the CLI I figured out logic that works, but all of the sudden it's not recognizing the lambda is there.
Is there something wrong with my definition? Also, is there a more preferred way of doing something like this either way?
Most probably replacing this assignment
remove_used_value = -> (x,y) { x.reject { |a| a == y }.sample }
with the proper dynamic attribute defined via a block
remove_used_value { -> (x,y) { x.reject { |a| a == y }.sample } }
will fix the issue.
(To be honest, I would avoid such kind of randomization of the object properties that I don't control in full - this often leads to either flaky specs that fail all of a sudden or, even worse, subtle bugs in the app logic that were not caught by the specs; but I understand that it might be a good solution for the particular use case)

Silverstripe 3: removeByName not working

Good morning,
I've been trying to use the removeByName method and it doesn't work.
I'm basically trying to hide a field in my DataObject within the forms that's generated by ModelAdmin, which manages the object.
See sample code below:
///DataObject snippet...
class MyObject extends DataObject{
public static $db = array(
'Title' => 'Varchar',
'Desc' => 'Text',
'Template' => 'HTMLText',
);
//#Override
public function getCMSField(){
$fields = parent::getCMSField();
$fields->removeByName('Template'); /// DOESN'T WORK!!!
return $fields;
}
}//class
Note: I'm not getting any errors. I'm just still seeing the field on the forms (Add and Edit) as usual.
Any help appreciated, thanks.
Okay, I found the issue.
I was just going over the API again for the millionth time, and recognized that I've named the function wrong. See correction below:
///Correction, forgot to add the 's' at the end of both the function and the parent call.
public function getCMSFields(){
$fields = parent::getCMSFields();
}
I can understand an error not being generated in Apache logs for the function because it's legit. But as for the parent call, it should of generated an error since the method don't exists. (Theory: Perhaps, since the function was never actually being called, the parent call wasn't being executed and thus no errors [run-time error]).

Change Grails REST format /controller/<id>/<action>

I messed around with this a bit yesterday and failed miserably. I want to convert:
"/$controller/$action?/$id?"
To
#in psudo
"/$controller/$id?/$action?"
#ideal regex
"\/(\w+)(\/\d+)?(\/\w+)?"
The most obvious way failed "/$controller/$action?/$id?"
I can write the regex's to do it, but I am having trouble finding a way to using true regexs (I found RegexUrlMapping but could not find out how to use it), and also can't find documentation on how to assign a group to a variable.
My question is 2 parts:
How to I define a URL Resource with a true regex.
How to I bind a "group" to a variable. In other words if I define a regex, how do I bind it to a variable like $controller, $id, $action
I would also like to be able to support the .json notation /user/id.json
Other things I have tried, which I thought would work:
"/$controller$id?$action?"{
constraints {
controller(matches:/\w+/)
id(matches:/\/\d+/)
action(matches:/\/\w+/)
}
}
also tried:
"/$controller/$id?/$action?"{
constraints {
controller(matches:/\w+/)
id(matches:/\d+/)
action(matches:/\w+/)
}
}
The grails way to deal with this is to set
grails.mime.file.extensions = true
in Config.groovy. This will cause Grails to strip off the file extension before applying the URL mappings, but make it available for use by withFormat
def someAction() {
withFormat {
json {
render ([message:"hello"] as JSON)
}
xml {
render(contentType:'text/xml') {
//...
}
}
}
For this you'd just need a URL mapping of "$controller/$id?/$action?"
I'm not aware of any way to use regular expressions in the way you want in the URL mappings, but you could get a forward mapping working using the fact that you can specify closures for parameter values that get evaluated at runtime with access to the other params:
"$controller/$a?/$b?" {
action = { params.b ?: params.a }
id = { params.b ? params.a : null }
}
which says "if b is set then use that as the action and a as the id, otherwise use a as the action and set id to null". But this wouldn't give you a nice reverse mapping, i.e. createLink(controller:'foo', action:'bar', id:1) wouldn't generate anything sensible, you'd have to use createLink(controller:'foo', params:[a:1, b:'bar'])
Edit
A third possibility you could try is to combine the
"/$controller/$id/$action"{
constraints {
controller(matches:/\w+/)
id(matches:/\d+/)
action(matches:/\w+/)
}
}
mapping with a complementary
"/$controller/$action?"{
constraints {
controller(matches:/\w+/)
action(matches:/(?!\d+$)\w+/)
}
}
using negative lookahead to ensure the two mappings are disjoint.

Query Orchard CMS from IShapeFactoryEvents

I am trying to insert shapes into my layout from my module once it has been enabled. I figured IShapeFactoryEvents would be perfect for this, but querying the CMS from here gives me a "TransactionScope nested incorrectly exception" if this occurs during a POST. Wondering if anyone had any words of wisdom for me again? See my code snippet below.
public void Created(ShapeCreatedContext context)
{
if (context.ShapeType == "Layout")
{
if (!AdminFilter.IsApplied(_services.WorkContext.HttpContext.Request.RequestContext))
{
var route = RouteTable.Routes.GetRouteData(_services.WorkContext.HttpContext);
object location;
if (route.Values.TryGetValue("location", out location))
{
var region = _services.ContentManager.Query("Region")
.Join<RoutePartRecord>()
.Where(x => x.Slug == (string)location)
.Slice(1).FirstOrDefault();
context.Shape.Header.Add(context.New.CurrentRegion(Title: region.As<RoutePart>().Title), "10");
}
context.Shape.Navigation.Add(context.New.RegionSelector(Regions: _services.ContentManager.Query(VersionOptions.Published, "Region").List()), "11");
}
}
}
Once again, thanks in advance. You guys are awesome.
See the blog post I did on this very topic here: http://chrisbower.com/2011/02/15/orchard-shape-wizardry/
From the blog post:
"One thing I need to note, and this took me an entire day to discover, is that you can't just inject your data service into your IShapeTableProvider implementation. If you do, it'll try to use a transaction out of scope and that will cause you all kinds of problems. After tearing my hair out for hours on end, I finally discovered what the Orchard team is doing inside of the CoreShapes class: The trick to resolve a service dependency within the function itself by using a property that loads the service per-request."
Try using your service like this instead:
private IOrchardServices Services
{
get
{
return _workContextAccessor.GetContext(_httpContextAccessor.Current()).Resolve<IOrchardServices>();
}
}

Resources