Using babel traverse to to get comments in AST - babeljs

How do I traverse comments with babelTraverse?
babelTraverse(nodes, {
CommentBlock: (path) => {
console.log(path)
},
CommentLine: (path) => {
console.log(path)
}
})
Error: You gave us a visitor for the node type CommentBlock but it's not a valid type

The CommentBlock and CommentLine are not part of the program.body in the ast returned by the babel parser. These comment types live outside of the program body. I am assuming that is why we get the Type error when we add CommentLine and CommentBlock.
The comments for a node can be accessed, using traverse, as follows:
traverse(ast, {
ClassDeclaration(path) {
console.log(path.node.leadingComments);
console.log(path.node.trailingComments);
},
});

Seems like you can't traverse that way but you can access comments with:
nodes.comments

Related

Rescript Record: Key as Array

In Rescript, one can define a Record in this format:
type record1 = {
a : String
}
but NOT:
type record2 = {
[a] : String
}
I am looking to write a record that compiles to JS like:
{
[Op.or]: [12,13]
}
The use case above comes from Sequelize, and the reference is here.
My current solution:
%raw(`{[Op.or]:[12,13]}`)
It's not entirely clear how you intend to interface with the Op construct, whether you can bind to it or not, but here's an example that does, and along with Js.Dict.t effectively produces the same output:
module Op = {
#val external or: string = "Op.or"
}
Js.Dict.fromList(list{
(Op.or, [12, 23])
})
It does not directly compile to the JS you want, however, which might be a problem if you rely on something that actually parses the source code. But short of that, I believe this should do what you ask for.

Writing nested path parameters in FeathersJS

How to generate multi level path parameters in feathers js like below :
api.com/category/catergoryId/subCatergory/subCatergoryId
The following is taken from this Feathers FAQ entry:
Normally we find that they actually aren't needed and that it is much better to keep your routes as flat as possible. For example something like users/:userId/posts is - although nice to read for humans - actually not as easy to parse and process as the equivalent /posts?userId=<userid> that is already supported by Feathers out of the box. Additionaly, this will also work much better when using Feathers through websocket connections which do not have a concept of routes at all.
However, nested routes for services can still be created by registering an existing service on the nested route and mapping the route parameter to a query parameter like this:
app.use('/posts', postService);
app.use('/users', userService);
// re-export the posts service on the /users/:userId/posts route
app.use('/users/:userId/posts', app.service('posts'));
// A hook that updates `data` with the route parameter
function mapUserIdToData(hook) {
if(hook.data && hook.params.userId) {
hook.data.userId = hook.params.userId;
}
}
// For the new route, map the `:userId` route parameter to the query in a hook
app.service('users/:userId/posts').hooks({
before: {
find(hook) {
hook.params.query.userId = hook.params.userId;
},
create: mapUserIdToData,
update: mapUserIdToData,
patch: mapUserIdToData
}
})
Now going to /users/123/posts will call postService.find({ query: { userId: 123 } }) and return all posts for that user.

How do I use findOrCreateEach in waterline/sailsjs?

I been looking around on the sails site and was lead to the waterline page. I am curious to how I can use the findOrCreateEach method. Specifically, number of arguments, what it will return, and how it will benefit me using it? I been searching, around and going to have to dive into the source code. I figure I ask here while I look.
Method without bluebird promises
Model.findOrCreateEach(/* What Goes Here */).exec(/* What Returns Here */);
With bluebird promises
Model.findOrCreateEach(/* What Goes Here */).then(/* What Returns Here */);
findOrCreateEach is deprecated; that's why it's not in the documentation. The best way to replicate the functionality is by using .findOrCreate() in an asynchronous loop, for example with async.map:
// Example: find or create users with certain names
var names = ["scott", "mike", "cody"];
async.map(names, function(name, cb) {
// If there is a user with the specified name, return it,
// otherwise create one
User.findOrCreate({name: name}, {name: name}).exec(cb);
},
function done(err, users) {
if (err) { <handle error and return> }
<users now contains User instances with the specified names>
});

Can I use CSS selectors in Tritium for moving/copying elements?

I am trying to copy an element to a given CSS selector in Tritium.
The Tritum Spec lists the signature for copy_to as:
copy_to(Text %xpath)
http://tritium.io/simple-mobile/1.0.224#Node.copy_to(Text%20%25xpath)
I am trying to do:
copy_to( CSS_SELECTOR )
For e.g:
copy_to("#header")
I cant seem to get this to work.
Here is the Tritium Tester URL: http://tester.tritium.io/4193cf46a239b4ff440cf1b4c36fb703cd22a5a4
Unfortunately, that won't work because of the way CSS selectors work in Tritium.
According to the spec, CSS selectors are converted into XPath local searches, which means they are scoped.
html() {
$("/html") {
$$("#header > img") {
add_class("logo")
}
$$("#content") {
$("./div[#id='courses']"){
$$("a") {
attribute("href", "http://console.moovweb.com/learn/training/getting_started/generate")
}
copy_to(css('#header'), "before")
}
}
}
}
In your example, your copy_to function is in the scope of $("./div[#id='courses']"), so it won't find the div#header in there.
You'll have to use an XPath selector like this: copy_to("/html/body/div[#id='header']","before")
See here: http://tester.tritium.io/5f0ae313a4f43038ee4adeb49b81236bfbc5f097

Entity Framework and Nested Lambda Expressions

I've just started using Lambda expressions, and really like the shortcut. I also like the fact that I have scope within the lambda of the encompassing method. One thing I am having trouble with is nesting lambdas. Here is what I am trying to do:
public void DoSomeWork()
{
MyContext context = new MyDomainContext();
context.GetDocumentTypeCount(ci.CustomerId, io =>
{
if (io.HasError)
{
// Handle error
}
// Do some work here
// ...
// make DB call to get data
EntityQuery<AppliedGlobalFilter> query =
from a in context.GetAppliedGlobalFiltersQuery()
where a.CustomerId == ci.CustomerId && a.FilterId == 1
select a;
context.Load<AppliedGlobalFilter>(query, lo =>
{
if (lo.HasError)
{
}
**// Do more work in this nested lambda.
// Get compile time error here**
}
}, null);
}, null);
}
The second lambda is where I get the following compile time error:
Cannot convert Lambda expression to type 'System.ServiceModel.DomainService.Client.LoadBehavior' because it is not a delegate type
The compiler is choosing the wrong overload for the Load method even though I am using the same override I did in the previous Lambda.
Is this because I am trying to nest? Or do I have something else wrong?
Thanks,
-Scott
Found the problem as described in my comment above. I'll head back to work now - red face and all....
I realize this is not the answer you want, but I suggest caution about lengthy and/or nested lambdas. They work, but they often make code harder to read / maintain by other developers. I try to limit my lambdas in length to three statements, with no nesting.