The following coffeeScript is running properly without the references to setUpdateInterval.
class Notifications
constructor: ->
#notifications = $("[data-behavior='notifications']")
#setup() if #notifications.length > 0
setUpdateInterval()
setup: ->
$.ajax(
url: "/notifications.json"
dataType: "JSON"
method: "GET"
success: #handleSuccess
)
handleSuccess: (data) =>
items = $.map data, (notification) ->
"<li class='active'><a href='#{notification.url}'>#{notification.actor} #{notification.notifiable.type}</a></li>"
$("[data-behavior='unread-count']").text(items.length)
$("[data-behavior='notification-items']").html(items)
setUpdateInterval: (notifications) ->
callback = #setup.bind(this)
setInterval( callback, 15000 )
jQuery ->
new Notifications
What is incorrect with the additional line and bloc inserted?
Based on comment, the following functions.
constructor: ->
#notifications = $("[data-behavior='notifications']")
#setUpdateInterval()
#setup() if #notifications.length > 0
setup: ->
$.ajax(
url: "/notifications.json"
dataType: "JSON"
method: "GET"
success: #handleSuccess
)
setUpdateInterval: (notifications) ->
callback = #setup.bind(this)
setInterval( callback, 15000 )
Related
I'm following this guide, with Zipkin.
I have 3 microservices involed, A -> B -> C, I'm propagating headers from A to B and from B to C.
But in the Zipkin dashboard I only see entries for A -> B and B -> C, not A -> B -> C.
Those are the headers:
[
"x-request-id",
"x-b3-traceid",
"x-b3-spanid",
"x-b3-parentspanid",
"x-b3-sampled",
"x-b3-flags",
"x-ot-span-context"
]
I can see that in B x-b3-parentspanid is null and I guess that's wrong, but the other are working I think...how is it possible?
EDIT:
added code snippets to show headers propagation
A -> B propagation:
app.post("/job", (req, res) => postJob(req.body, req.headers).then((response) => res.send(response)))
...
const postJob = (job, headers) => rp({
method: "POST",
uri: `${API_ENDPOINT}/api/job`,
json: true,
body: job,
headers: Object.keys(headers).filter((key) => TRACING_HEADERS.includes(key)).map((key) => headers[key])
})
B -> C propagation:
#PostMapping("/api/job")
#ResponseBody
fun publish(
#RequestBody job: Job,
#RequestHeader("x-request-id") xreq: String?,
#RequestHeader("x-b3-traceid") xtraceid: String?,
#RequestHeader("x-b3-spanid") xspanid: String?,
#RequestHeader("x-b3-parentspanid") xparentspanid: String?,
#RequestHeader("x-b3-sampled") xsampled: String?,
#RequestHeader("x-b3-flags") xflags: String?,
#RequestHeader("x-ot-span-context") xotspan: String?
): JobResponse = jobsService.publishJob(
job, mapOf(
"x-request-id" to xreq,
"x-b3-traceid" to xtraceid,
"x-b3-spanid" to xspanid,
"x-b3-parentspanid" to xparentspanid,
"x-b3-sampled" to xsampled,
"x-b3-flags" to xflags,
"x-ot-span-context" to xotspan
)
)
...
fun publishJob(job: Job, headers: Map<String, String?>): JobResponse {
val enabled = restTemplate.exchange(
"${gatekeeperConfiguration.endpoint}/",
HttpMethod.GET,
HttpEntity(headers),
EnabledResponse::class.java
).body
if (!enabled!!.isEnabled) // TODO we intentionally want this to crash if body is null
return JobResponse(JobRequestStatus.REJECTED)
return if (this.queue.publish(job)) JobResponse(JobRequestStatus.OK)
else throw RuntimeException("I don't know what to do, yet")
}
Object.keys(headers).filter((key) => TRACING_HEADERS.includes(key)).map((key) => headers[key]) returns an array.
What you want is:
Object.keys(headers)
.filter(key => TRACING_HEADERS.includes(key))
.reduce((obj, key) => {
obj[key] = headers[key];
return obj;
}, {})
I'm pretty sure this isn't an istio / distributed tracing issue ;-)
b3-propagation of x-b3-parentspanid (https://github.com/openzipkin/b3-propagation) can be configured in your application.yml by adding:
opentracing:
jaeger:
enable-b3-propagation: true
I have been working around lately with the Twitter typeahead jQuery plugin. It is mostly working, but it gives me 'Undefined' as the search result.
Here is my folder.js.coffee:
$(document).ready ->
console.log("searchhhhh");
haunt = undefined
repos = undefined
repos = new Bloodhound(
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value')
queryTokenizer: Bloodhound.tokenizers.whitespace
limit: 10
prefetch:
url: '/auto_search.json',
filter: (list) ->
$.map list.results, (auto) ->
{ value: auto }
)
repos.initialize()
$('#auto_search').typeahead null,
name: 'repos'
displayKey: 'value'
source: repos.ttAdapter()
return
This worked.
$(document).ready ->
console.log("searchhhhh");
haunt = undefined
repos = undefined
repos = new Bloodhound(
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name')
queryTokenizer: Bloodhound.tokenizers.whitespace
limit: 10
prefetch:
url: '/auto_search.json',
filter: (list) ->
$.map list.results, (auto) ->
{ value: auto }
)
repos.initialize()
$('#auto_search').typeahead null,
name: 'repos'
displayKey: 'name'
source: repos.ttAdapter()
return
Is there a way to chain Promises together in Coffeescript. For example, consider the following javascript code,
return $.getJSON('/api/post.json')
.then(function(response) {
// do something
})
.then(function(response) {
// do something
})
.then(null, function(err) {
// do something
});
Each of the then's is optional, and the final then needs to be returned by the function.
Currently I am writing this in coffeescript as,
promise = $.getJSON('/api/post.json')
promise = promise.then (response) ->
// do something
promise = promise.then (response) ->
// do something
promise = promise.then null, (err) ->
// do something
return promise
Is there a better way to do this? Thanks.
Ezekiel shows the right way, but it doesn't need the parentheses around the functions. Just do:
$.getJSON '/api/post.json' # As of CoffeeScript 1.7, you don't need the parentheses here either.
.then (response) ->
# do something
response # if you would not return anything, promise would be fulfilled with undefined
.then (response) ->
# do something
undefined # necessary to prevent empty function body
.then null, (err) ->
# handle error
I think it's surprisingly clean.
The one thing that's relatively messy is when you need to add onRejected and onFulfilled handlers at the same time.
Note: Last time I checked, this did not work in CoffeeScript Redux, but this was a few months ago.
Note 2: You need at least one line of actual code (i.e. not just a comment) in each function body for this to work. Typically, you will, so it's not a big issue.
This is my personal favorite way to write promises, with a little bit extra indentation
doSomething = () -> new RSVP.Promise (resolve, reject) ->
if 1 is 1
resolve 'Success'
else
reject 'Error'
doSomething()
.then (res) ->
console.log 'Step 1 Success Handler'
, (err) ->
console.log 'Step 1 Error Handler'
.then (res) ->
console.log 'Step 2 Success Handler'
.then (res) ->
console.log 'Step 3 Success Handler'
, (err) ->
console.log 'Step 3 Error Handler'
Which compiles to:
var doSomething;
doSomething = function() {
return new RSVP.Promise(function(resolve, reject) {
if (1 === 1) {
return resolve('Success');
} else {
return reject('Error');
}
});
};
doSomething().then(function(res) {
return console.log('Step 1 Success Handler');
}, function(err) {
return console.log('Step 1 Error Handler');
}).then(function(res) {
return console.log('Step 2 Success Handler');
}).then(function(res) {
return console.log('Step 3 Success Handler');
}, function(err) {
return console.log('Step 3 Error Handler');
});
There are some instances where this works really well too:
step1Success = (res) -> console.log 'Step 1 Success Handler'
step1Error = (err) -> console.log 'Step 1 Error Handler'
step2Success = (res) -> console.log 'Step 2 Success Handler'
step3Success = (res) -> console.log 'Step 3 Success Handler'
step3Error = (err) -> console.log 'Step 3 Error Handler'
doSomething()
.then(step1Success, step1Error)
.then(step2Success)
.then(step3Success, step3Error)
Tested on coffee-script v1.6.3
This is probably the best you'll do:
$.getJSON('/api/post.json')
.then( (response) ->
# do something
).then( (response) ->
# do something
).then null, (err) ->
# do something
Note the parentheses surrounding the then() arguments. Nothing earth shattering but hopefully this helps.
The response is 415 (Unsupported Media Type) .
Client Side Code:
$.ajax({
url: "/book",
//contentType: 'application/json',
data: {action: "hello", method: "json"},
dataType: "json",
type: "POST",
complete: function(a, b) {
console.log(a);
console.log(b);
}
});
Server Side Code:
content_types_provided(Req, State) ->
{[
{<<"application/json">>, handle_to_all}
], Req, State}.
handle_to_all(Req, State) ->
Body = <<"{\"rest\": \"Hello World!\"}">>,
{Body, Req, State}.
If I update the type from "POST" to "GET" from client side, everything is okay.
Anything I missed?
content_types_provided method of cowboy accepts only GET and HEAD
Go through the following link and change the code accordingly
https://ninenines.eu/docs/en/cowboy/1.0/manual/cowboy_rest/
You can use cowboy_rest, implement the content_types_accepted/2 callback method like so:
content_types_accepted(Req, State) ->
case cowboy_req:method(Req) of
{<<"POST">>, _ } ->
Accepted = {[{<<"application/json">>, put_json}], Req, State};
{<<"PUT">>, _ } ->
Accepted = {[{<<"application/json">>, post_json}], Req, State}
end,
Accepted.
I think this way you can have separate handlers for different HTTP Verbs/Methods. This gives you cleaner code too :)
And the various handlers:
%% handle http put requests
put_file(Req, State) ->
{true, Req, State}.
%% handle http post requests
post_json(Req, State) ->
{true, Req, State}.
I can't seem to get the POST parameters to come through from an AJAX javascript POST. The error is:
#6angl7689 - Internal server error, for request [POST /myRoute] ->
play.core.ActionInvoker$$anonfun$receive$1$$anon$1: Execution exception [[NoSuchElementException: None.get]]
Route:
POST /myRoute controllers.Application.testPost
Controller code:
def myForm = Form(
tuple(
"valOne" -> text,
"valTwo" -> text))
def testPost() = Action { implicit request =>
val (valOne, valTwo) = myForm.bindFromRequest.get // Errors here
println("valOne: " + valOne)
println("valTwo: " + valTwo)
Ok
}
CoffeeScript client-side:
params =
valOne: 'valOne'
valTwo: 'valTwo'
$.ajax
type: 'POST'
url: '/myRoute'
data: params
Update your client code,
$.ajax(
type: 'POST'
url: '/myRoute'
data: {valOne: 'valOne', valTwo: 'valTwo'}
);
This should work