Using meteor's simple:rest package in publications with arguments - javascript

I a meteor app, using the simple:rest package to access publications works very nicely!
However, I didn't manage yet to GET a publication that requires an argument.
The docs say nothing about publications with arguments.
When I call the GET URL without argument http://localhost:3000/publications/export/, I get an error message (as I check for the argument in my publication)
When I call get URL with attached argument: http://localhost:3000/publications/export/12345/ the main app gets loaded instead (well, with some broken links to images)
When I add an url option to the publication
Meteor.publish("export", function exportPublication(id) {...}, {
url: "export/:0",
})
it doesn't help, I still get the main app.
The example at https://github.com/stubailo/meteor-rest/blob/master/packages/rest/rest-tests.js suggests that using the URL option seems to be the correct way to define a route for a publication with arguments.
What am I missing?

I haven't used this package myself, but I think you need to add the parameter to the publish function, like this:
Meteor.publish("export", function exportPublication(id) {...}, {
url: "export/:0",
})
and you can access id in the code that retrieves the data. If you are treating it as a number, you may need to parse it: parseInt(id, 10)
Also I would use postman or curl to access the URL (it sounds like you are using the browser)

Oh, when I publish the url as export/:0, then it is mapped to http://localhost:3000/export/123 - but not to http://localhost:3000/publications/export/123. I thought the "publications" would be added automatically.

Related

Fetch node issue

This code is using to bring BNB price, I want to push the price into an array. I tried Fetch in HTML page, and it worked perfect.
Node doesn't have fetch as the browser's JavaScript does.
You can try to use the Node's http module directly or use some package like axios.
UPDATE:
However, regarding your particular case - it seems you don't have do make requests manually. You're using node-binance-api package that does requests under the hood. So just remove the code that invokes fetch at all.
ANOTHER UPDATE:
So finally to add a price to the array you can rewrite your function fetchCoinPrice like this:
function fetchCoinPrice() {
binance.prices(function(error, ticker) {
console.log("Price of BNB: ", ticker.BNBBTC);
array.push(ticker.BNBBTC);
});
}

How to create a Shared Query Folder using the vso-node-api (VSTS)?

In the VSTS Rest API, there's a piece of documentation showing me how to create a folder. Specifically, I would like to create a folder within the Shared Queries folder. It seems like I can do this with the REST API.
I would like to do the same thing with the VSTS Node API (vso-node-api). The closest analogous function I can seem to find would be WorkItemTrackingApi.createQuery. Is this the correct function to use?
When I try to use this function, I'm getting an error:
Failed request: (405)
That seems strange, since a "Method Not Allowed" error doesn't seem like the right error here. In other words, I'm not the person deciding what method (GET/POST/...etc) to use, I'm just calling the VSTS Node API's function which should be using the correct HTTP Request Method.
I think the error code would/should be different if something about my request is wrong (like providing bad parameters/data).
But, I would not be surprised if VSTS didn't like the data I provided with the request. I wrote the following test function:
async function createQueryFolder (QueryHeirarchyItem, projectId, query) {
let result = await (WorkItemTrackingApi.createQuery(QueryHeirarchyItem, projectId, query))
return result
}
I set some variables and called the function:
let projectID = properties.project // A previously set project ID that works in other API calls
let QueryHeirarchyItem = {
isFolder: true,
name: 'Test Shared Query Folder 1'
}
try {
let result = await createQueryFolder(QueryHeirarchyFunction, projectID, '')
Notice that I provided a blank string for the query - I have no idea what to provide there when all I want to create is a folder.
So, I think a lot of things could be wrong with my approach here, but also if my request parameters are wrong maybe I should be getting a 400 error? 405 leads me to believe that the VSTS Node API is making a REST call that the underlying VSTS REST API doesn't understand.
For the third parameter of the createQueryFolder, you should specify the folder path where you want to create the new folder.
Such as if you want to create a folder Test Shared Query Folder 1 under Shared Queries, you should specify parameters for createQueryFolder as:
let result = await createQueryFolder(QueryHeirarchyFunction, projectID, 'Shared Queries')

Understanding anonymous functions in Express js

I am new to express and am trying to wrap my head around callbacks in RESTful actions. In my PUT request below, I'm confused about the following line that I have bolded below. Why is response.pageInfo.book being set to the second parameter in the anonymous function (result)? that seems kind of arbitrary.
Also, what is the best way to inspect some of these parameters (req, res, result, etc)? When I console.log it, doesn't show up in my terminal or in my browser console.
exports.BookEdit = function(request, response) {
var id = request.params.id;
Model.BookModel.findOne({
_id: id
}, function(error, result) {
if (error) {
console.log("error");
response.redirect('/books?error=true&message=There was an error finding a book with this id');
} else {
response.pageInfo.title = "Edit Book";
**response.pageInfo.book = result;**
response.render('books/BookEdit', response.pageInfo)
}
})
}
The findOne function takes a query ({_id : id}) and a callback as arguments. The callback gets called after findOne has finished querying the database. This callback pattern is very common in nodejs. Typically the callback will have 2 arguments
the first one error is only set if there was an error.
the second one usually contains the value being returned. In this case you are finding one book in the database.
The line you have bolded is where the book object is assigned to a variable which will be sent back to be rendered in the browser. It is basically some javascript object.
Your second request, to debug this stuff, here is what you can do:
In you code type the word debugger;
e.g.
var id = request.params.id;
debugger;
Next, instead of running your program like this:
node myprogram.js
... run with debug flag, i.e.
node debug myprogram.js
It will pause at the beginning and you can continue by pressing c then Enter
Next it will stop at that debugger line above. Type repl and then Enter and you'll be able to inspect objects and variables by typing their names.
This works very well and requires no installation. However, you can also take a more visual approach and install a debugger such as node-inspector which does the same thing but in a web browser. If you use a good IDE (e.g. webstorm) you can also debug node.js pretty easily.
In the above, the document that is the result of the findOne() query is being added to the pageInfo key of the response and is then being rendered in a template. The first parameter is a potential error that must be checked and the remainder contain data. It's the standard node idiom that an asynchronous call returns to a callback where you do your work.
The writer of the code has also decided to decorate the response object with an extra attribute. This is often done when a request passes through a number of middleware functions and you might want to build up the response incrementally (for example having a middleware function that adds information about the current user to the pageInfo key).
Look and see what else is on response.pageInfo. Information was probably put there by previous middleware (especially since the function above expects the pageInfo key to exist). Just do a console.log(response.pageInfo) and look on your server log or standard out.

What is the REST style for getSomethingByAnother() method

I have a Node.js REST API service and I have a resouce - Link for example.
To get all links I use GET /links
To submit new link I use POST /links
To get one link by linkid I use GET /links:id
Each link have an array of Tags and I need a REST style URI to get the links by tag value. What will be REST style URI in this case ?
For getting the links of a certain tag you can define the following route:
/tags/:tagID/links
And for getting tags of a certain link:
/links/:linkID/tags
I think it should be:
GET /links/:id/tags
that should return all the tags related to the link with id ":id"
If you like to work with your tags as a separated thing you could do it like this:
GET /tags ==> retrieve all tags.
GET /tags/:id ==> retrieve tag with id..
GET /tags/links/:id
Also resftull is not strict, and some times, the resource, or action that you need to execute does not fit in that schema, and you can create a custom method:
GET /tags/get-for-link-id/:id => retrieve tags related to a link
That example is pointless, but consider that you are having a complicated route with so much params eg:
GET /tags?q=return&state=active&sort=date if this request is repeated so much times, for your api customer it would be pleasant to have a custom alias like GET /tags/activeByDate
It depends. TYou can do something like /blah:{tagId}/ (which is perfectly valid URI as well). Or you can do /links/?tagID={id} and so on. I don't prefer the already mentioned hierarchical URI /tags/{id}/links, I think a flat URI is much better. If the relationship has attributes as well, then you can use /tag-link-relationships/{relationshipId} or /tag-link-relationships/tag:{tagId}/ or /tag-link-relationships/?tag={tagId} etc...
From client perspective the URI structure does not matter, because the client follows the hyperlinks the service responds with (aka. uniform interface / HATEOAS constraint).
off: Almost every day we got this question, at least try to search next time.

How do I post a tweet using javascript, twitter api and node.js?

Ok...I'm new to this >.<
I have my npm from github.com (node-twitterbot...whose dependency is twit)
I've looked at the twitter api..
What I'm trying to do is add an action which is post a tweet.
I can't seem to find out how to define the string for the actionName (which might be...)
var tweet = ("https://api.twitter.com/1.1/statuses/update.json");
and the actionFunction. Then I need to put it all together to post. Also, I have my instructions written below, however I'm not sure how to apply them. My actionName could be "tweet"? I have no idea how to define my actionFunction either...Can someone explain this? I NEED TO KNOW WHAT TO PUT WHERE. I have the twitterbot.js file open and ready to edit along with with all my oauth keys...access and consumer stuff. Please help anyway you can. I can paste my twitterbot.js file if that helps. Below are the instructions on the npm site reads:
Actions
In order to get your node-twitterbot to actually do something, you need to define actions. It is done through the addAction() method. It takes 2 parameters:
actionName: a string value for the name of an action
actionFunction: a function to be called when a given action is scheduled. (See below for method signature)
So our addAction method might look like this:
Bot.addAction("tweet", function(twitter, action, tweet) {
Bot.tweet("I'm posting a tweet!");
});
The twitter variable passed into the function is the Twit object associated with a given node-twitterbot, and can be managed directly. The same Twit object is available as [TwitterBot].twitter as well.
The action variable passed into the function is the TwitterBotAction created by addAction.
And the tweet object is the tweet passed into the action (if there was one)
TwitterBotActions
addAction() returns a TwitterBotAction object.
var tweetAction = Bot.addAction("tweet", function(twitter, action, tweet) {
Bot.tweet("I'm posting a tweet!");
});
But you will rarely need to directly hold onto the tweetAction directly. You can always get a reference to the action by calling
Bot.actionWithName("tweet");
Which will return the TwitterBotAction object, or null if the name is invalid (or the action already removed)
Again, I'm trying to put all of this together so i can post a tweet using the javascript in node.js Thank you for your time and consideration.

Categories

Resources