JavascriptMVC route examples - javascriptmvc

I am staring out with JavascriptMVC, and currently trying to figure out jQuery.route. I know there are other 3rd party plugins that perform routing, but I'm specifically trying to figure out jQuery.route which comes with Javascript MVC.
I'm familiar with Backbone.js and Ember's routing frameworks, but I just don't understand JMVCs. I've tried reading the documentation and looking at the code here, but there are no examples and still can't figure it out.
I'm trying to do something basic such as, if the browser sees a URL like
http://localhost/helloWorld#state1
then some function will be executed. Something similar to how Backbone and Ember work. Can this be done using JavascriptMVC's jQuery.route?

I think deparam should work for the task of figuring out the route for the current page:
var currentRoute = $.route.deparam(window.location.current);
if (currentRoute == "state1") {
// handle route
}

Related

Trying to write to a json file using Node fs.writeFile

I hope I'm saying this correctly. What I'm trying to do is write to a json file using fs.writeFile.
I can get it to work using the command line but what I want to do is call a function maybe a button click to update the json file.
I figure I would need some type of call to the node server which is local port 8080. I was researching and seen somebody mention using .post but still can't wrap my head around how to write the logic.
$(".button").on("click", function(event) {
fs.writeFile("./updateme.json", "{test: 1}", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
});
Using jQuery along with fs? Wow that could be great! Unfortunately that is not as simple as that!
Let me introduce you to server-side VS client-side JavaScript. Well actually there are a lot of resources on the net about that - just google it, or check the answers to this other StackOverflow question. Basically JavaScript can run either on a browser (Chrome, Mozilla...) or as a program (usually a server written in NodeJS), and while the language is (almost) the same, both platforms don't have the same features.
The script that you're showing should run in a browser, because it's using jQuery and interacting with buttons and stuff (aka the DOM). Can you imagine what a mess it would be if that script could interact with the file system? Any page you'll visit will be able to crawl around in your holiday pictures and other personal stuff you keep on your computer. Bad idea! That is why some libraries like fs are not available in the browser.
Similarly, some libraries like jQuery are not available (or simply useless) in the server, because there is no HTML and user interaction, only headless programs running.
So, what can I do to write a JSON file after a user clicks on a button?
You can set up:
A NodeJS server that will write a JSON file
Make jQuery call this server with the data to be written after the user clicks on a button
If you want further guidelines on this, tell me in the comments! I'll be ready to edit my question so as to include instructions on setting up such an environment.

How should I use Swagger with Hapi?

I have a working ordinary Hapi application that I'm planning to migrate to Swagger. I installed swagger-node using the official instructions, and chose Hapi when executing 'swagger project create'. However, I'm now confused because there seem to be several libraries for integrating swagger-node and hapi:
hapi-swagger: the most popular one
hapi-swaggered: somewhat popular
swagger-hapi: unpopular and not that active but used by the official Swagger Node.js library (i.e. swagger-node) as default for Hapi projects
I though swagger-hapi was the "official" approach, until I tried to find information on how do various configurations on Hapi routes (e.g. authorization, scoping, etc.). It seems also that the approaches are fundamentally different, swagger-hapi taking Swagger definition as input and generating the routes automatically, whereas hapi-swagger and hapi-swaggered seem to have similar approach with each other by only generating Swagger API documentation from plain old Hapi route definitions.
Considering the amount of contributors and the number of downloads, hapi-swagger seems to be the way to go, but I'm unsure on how to proceed. Is there an "official" Swagger way to set up Hapi, and if there is, how do I set up authentication (preferably by using hapi-auth-jwt2, or other similar JWT solution) and authorization?
EDIT: I also found swaggerize-hapi, which seems to be maintained by PayPal's open source kraken.js team, which indicates that it might have some kind of corporate backing (always a good thing). swaggerize-hapi seems to be very similar to hapi-swagger, although the latter seems to provide more out-of-the-box functionality (mainly Swagger Editor).
Edit: Point 3. from your question and understanding what swagger-hapi actually does is very important. It does not directly serves the swagger-ui html. It is not intended to, but it is enabling the whole swagger idea (which the other projects in points 1. and 2. are actually a bit reversing). Please see below.
It turns out that when you are using swagger-node and swagger-hapi you do not need all the rest of the packages you mentioned, except for using swagger-ui directly (which is used by all the others anyways - they are wrapping it in their dependencies)
I want to share my understanding so far in this hapi/swagger puzzle, hope that these 8 hours that I spent can help others as well.
Libraries like hapi-swaggered, hapi-swaggered-ui, also hapi-swagger - All of them follow the same approach - that might be described like that:
You document your API while you are defining your routes
They are somewhat sitting aside from the main idea of swagger-node and the boilerplate hello_world project created with swagger-cli, which you mentioned that you use.
While swagger-node and swagger-hapi (NOTE that its different from hapi-swagger) are saying:
You define all your API documentation and routes **in a single centralized place - swagger.yaml**
and then you just focus on writing controller logic. The boilerplate project provided with swagger-cli is already exposing this centralized place swagger.yaml as json thru the /swagger endpoint.
Now, because the swagger-ui project which all the above packages are making use of for showing the UI, is just a bunch of static html - in order to use it, you have two options:
1) to self host this static html from within your app
2) to host it on a separate web app or even load the index.html directly from file system.
In both cases you just need to feed the swagger-ui with your swagger json - which as said above is already exposed by the /swagger endpoint.
The only caveat if you chose option 2) is that you need to enable cors for that end point which happened to be very easy. Just change your default.yaml, to also make use of the cors bagpipe. Please see this thread for how to do this.
As #Kitanotori said above, I also don't see the point of documenting the code programmatically. The idea of just describing everything in one place and making both the code and the documentation engine to understand it, is great.
We have used Inert, Vision, hapi-swagger.
server.ts
import * as Inert from '#hapi/inert';
import * as Vision from '#hapi/vision';
import Swagger from './plugins/swagger';
...
...
// hapi server setup
...
const plugins: any[] = [Inert, Vision, Swagger];
await server.register(plugins);
...
// other setup
./plugins/swagger
import * as HapiSwagger from 'hapi-swagger';
import * as Package from '../../package.json';
const swaggerOptions: HapiSwagger.RegisterOptions = {
info: {
title: 'Some title',
version: Package.version
}
};
export default {
plugin: HapiSwagger,
options: swaggerOptions
};
We are using Inert, Vision and hapi-swagger to build and host swagger documentation.
We load those plugins in exactly this order, do not configure Inert or Vision and only set basic properties like title in the hapi-swagger config.

What is a recommended way to get data into your meteor template from the front-end for a famous surface?

I've been following along with the book Discover Meteor from https://www.discovermeteor.com/ and I have built the tutorial project called 'Microscope'
This uses iron-router and Meteor templating system to render out the front-end. I want to redo this project using famo.us for the front-end but I am unclear on how I to do so.
I am aware of a package called famono. mrt add famono. Using this package I can integrate famo.us and draw surface to the screen in a meteor project. It also allows you to render templates to the screen.
But I am confused on how to redo the project so the router - routes to render a famous surface with the data.
Also I am wondering if the templates will still be reactive.
If someone could provide insight on how to redo the 'Microscope' project to use famo.us on the front-end I would greatly appreciate it!
Thanks
UPDATE (to be more specific)
I have been trying to figure out how to integrate famous with templates and routing, and I have no clue how to do it.
I use iron-router to handle my routing which chooses which template and data to render like so:
Router.map ->
#route 'posts',
path: '/',
data: ->
Posts.findOne()
So this will load up the posts template with Posts.findOne() data.
But I know with famous I can generate surfaces from templates on the front end like so:
background = new Surface
template: Template.post
data: ??? (Posts.findOne()) ???
mainContext.add(background)
Because javascript is what is going to load the final template into the view, what is the recommended way for me to get the data for that template, should I query the database from the front-end by setting up special subscriptions?
Typically I render the data into the page from the router on the server but...
with famous, I just have to load the main template and let famous load the rest of the templates. The only thing left is getting the data for the other templates. What is recommended?
I would start by looking at https://github.com/gadicc/meteor-famous-components/. That package will do all the work for you if you want.
I have never used the Surface template argument but I believe that is a one time load and will not update on data invalidation (data change).
Or u can take a look at working examples )
https://github.com/sayawan?tab=repositories

Proper way to handle errors in ExpressJS 3

I've been struggling for the past hours trying to find a decent tutorial on how to handle errors for a NodeJS + ExpressJS 3 api.
I've read a lot of questions/answers on SO and read the official ExpressJS guide and still cannot figure out the proper way to do such an important thing. Most of the answers I found were relevant in Express 1 or Express 2, but are not anymore and the ExpressJS Guide just describes something out of context, which makes it really hard to understand.
So here's my use case : I want to get informations about a city, using the GET /cities/:slug. If the slug doesn't exist or an error happened (with MongoDB or Mongoose for example), I want to return an error code.
Here's the relevant part of my current code :
if (err || !city) {
res.json({code:500, city:[]});
}
It's a basic example and it's working "well", but I'm pretty sure that's not the right way to do it in NodeJS.
Also, this does not stop my NodeJS instance, but some unexpected errors might. From what I read, this is not a problem in production because apparently restarting the NodeJS instance is cleaner, and third-parties handle it pretty well (read about Cluster, Forever or even Monit).
Would love to have more insights on this problem I've been overlooking for too long.

Testing Node.js app with Zombie

I am writing a node.js app in coffee-script using the express framework. After exploring a couple of options I finally decided to use mocha and zombie.js. However, I am having a hard testing the UI. For example, to implement a successful user authentication I do the following: see the code pasted here my_gist
What I really wanted to do is the following:
call get '/sessions/new', which will call the SessionsController and display the authentication form
then I'll call the browser.visit method, enter the values for the fields and submit the form, which will generate a post method
if the username and password are correct, I'll expect the SessionsController to react accordingly and redirect to the right page.
Unfortunately, whenever I run the tests it complains about Zombie: require is not defined ReferenceError: require is not defined. It turns out it doesn't like the two lines in my /javascripts/app.js
require("coffee-script")
require('./tfs.coffee')
Even when I try to extract any information from the browser after the visit method, I just get undefined values. Apparently none of my assertions is being tested. It just passes the test. Is there anything I am doing wrong? Has anyone testing coffee-script written app in express using Zombie.js faced that problem? what could be the fix?
If /javascripts/app.js is being loaded from the browser, you would want to make sure that RequireJS (or some other browser framework that defines require) is loaded first, or load them in your HTML document:
<script src="coffee-script.js" type="text/javascript"></script>
<script src="tfs.coffee" type="text/coffee"></script>
You might need to wait until the page is fully loaded before extracting values.

Resources