Sorry for a nooby question. I'd ask it anyway!
I am playing around with AdonisJs. I understand it is a MVC framework. But I want to write REST APIs using the said framework. I could not find much help on the internet.
I have two questions:
Does the framework support writing REST APIs?
If yes to 1. then what could be the best starting point?
1. I've created 3 API projects with AdonisJS and think it's ideal for quick setup. It has many functions already included from start, supports database migrations and is pretty well documented in general.
You can create routes easily with JSON responses:
http://adonisjs.com/docs/3.2/response
Route.get('/', function * (request, response) {
const users = yield User.all()
response.json(users)
})
Or add them to a controller, and even fairly easily add route authentication with token protection (all documented):
Route.post('my_api/v1/authenticate', 'ApiController.authenticate')
Route.group('api', function () {
Route.get('users', 'ApiController.getUsers')
}).prefix('my_api/v1').middleware('auth:api')
2. Take a look at the official tutorial, you can probably finish it in about half an hour. http://adonisjs.com/docs/3.2/overview#_simplest_example
Start with defining some routes and try out echoing simple variables with JSON and just in regular views.
Move the test logic to Controllers
Read a bit more about the database migrations and add some simple models.
Don't forget the Commands and Factory, as you can easily define test data commands there. This will save you a lot of time in the long run.
Just keep in mind that you need to have a server with Node.JS installed to run the system on production (personally I'm keeping it running using a tool like Node Forever JS.
In order to create just a RESTful api you can use
npm i -g #adonisjs/cli
# Create a new Adonis app
adonis new project-name --api-only
Related
How can I create PR on Github using their API? Let's imagine I have package.json file as a string and I want to make changes to this file. So I parse it, make changes to it and then what exactly I need to do to make it look like I made those changes locally after checking out the new branch, making changes, commiting them to new branch and the pushing them to remote? I see that they have POST API endpoint to create a commit and POST API endpoint to create a PR, but I don't see where I put the file I changed.
Using something like GitJS could be a solution.
This library is a simple wrapper around the git command line.
Instead of using the Github API you could just work the git commands programatically with a library like this.
That way you don't have to work with the much more complicated API and have the benefit of supporting other source control sites too.
Looking at their example we can see it's incredibly easy to commit and push a file using javascript:
require('simple-git')()
.add('./*')
.commit("first commit!")
.addRemote('origin', 'some-repo-url')
.push(['-u', 'origin', 'master'], () => console.log('done'));
Make sure you refer to the usage documentation before trying that example to ensure you configure everything correctly.
Alternatively, you can use the package Octokit to more easily interface with the Github API.
When adding, committing and pushing a file via the API you must first start by creating a tree. Then you use that tree as part of the commit request, update the references and finally push the commit.
You can find a working example on this Github issue.
I have a few tiny node apps doing some basic stuff like checking things and filling my DB (triggered by CRON). In my Nuxt app I will need to use part of what is insinde these Node apps. What is the best way to organise it, do I keep them separated or do I fuse them with my Nuxt app ? Do I copy what I need from these node apps and adapt it in Nuxt, do I use the serverside middlewares to add those node apps inside my Nuxt project or do I create my Nuxt app with express and I use /server/index.js to add my node apps there in some way ?
Let's take an example. You have a node app that check very hour some data and fill a DB. In the Nuxt app you have a page showing the content of the DB but you want first to be sure that nothing new has to be added in the DB since the last hour. The code I would have to run in th every Nuxt page is the same code as the Node app (check and fill the DB). It looks a bit stupid (and hard to maintain and update) to have twice the same code at two places. But I 'm not sure how would I have this node app running every hour in my Nuxt app. Any advice would be greatly appreciated
Here is a control flow that may help your thinking about designing this CRON microservice. There are many ways to do this, and this may not be the best approach, but I think it will work for your use case.
Have a services directory in your server (can also be called middleware).
Include a cron.js file that contains the logic for the task runner.
Within cron.js, issue a scheduled response from node to Vue, such as a JSON keyword like res.JSON({message: 'checkNewData'}). This will be something called a "server sent event". A server sent event is simply an event that happens autonomously on a defined schedule within node environment.
In Vue, at the root level App.vue, use the created() hook to register an event listener that will listen for the server sent "checkNewData" JSON object. When this event listener hears the JSON response, it should trigger Vue to check the appropriate component, package up any new data, and send it down to the DB in a post or put http call, depending on whether you're adding new data, or replacing the old with the new.
This configuration would give you a closed-loop system for automatic updates. The next challenge would be making this operation client-specific, but that is something to worry about once you got this working. Again, others may have a different approach to this, but this is how I would handle the flow.
I am new to UI framework development. Currently my requirement is to work with anuglarjs and nodejs. I know there are few more like me who want to know the exact use..
I am confused as where i need to use nodejs in my application. I tried to find a simple live demo example(plunker/jsfiddle) which used angularjs and nodejs but i couldn't find one.
Currently i have written a small module using angularjs, which hits the java controller class and saves/get the data and display the data on the webpage. Here i'm no where using nodejs. I tried to search in web to understand the use of nodejs with angularjs.
Any input's would be very helpful.
Below is the sample javascript code i implemented using angularjs.
myDataCOntroller.js
//some code here
$scope.submitFormData = function(myForm){
if(myForm.$valid)
{
MyDataService.saveOrGetData($scope.myReport).then(
function(response) {
$scope.myReport = response;
},
function(errResponse){
console.error('Errorr');
});
}else{
console.log("invalid form data!!");
}
}
myDataService.js
app.factory('myService',function($http,$q,$location){
var MY_SERVICE_URI = $location.protocol()+'://'+$location.host()+':'+$location.port();
var _repServiceFactory={};
_repServiceFactory.saveOrGetData = function(myData){
var deferred = $q.defer();
var url = appURL+'/saveOrGetData.form';
$http.post(url,JSON.stringify(myData))
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while fetching data');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
PS: I know that Angularjs is client side, Nodejs is server side, both are using Javascript programming language.
What i want to know is, what is the use of nodejs and where is it used in real time??
If you are writing an AngularJS front end web application, you may never have to use NodeJS.
If you need tooling (build scripts to compile Sass, linters, etc) in your development or deployment process you can use NodeJS task runners like Gulp, Grunt or Webpack.
If you need to build a back end API, that stores and retrieves information, you can use Express or the whole MEAN stack.
* * * Also worth noting-- you mention hitting a Java class. If you are already using Java for the backend, then you probably won't be using any NodeJS for that purpose. If you were just shortening JavaScript to "Java", please note they are separate and distinct languages. * * *
Web dev has 4 primary parts:
Back-End: Node.Js (which will replace or work with your Java server)
Front-End: Angular.js (or React/Polymer/Vue/etc.)
Database: MongoDB (noSQL), mySql/Postgres (sql)
Routing/Server/Middleware: Express.js
For you to create an app that is realtime, you can use websockets, especially Socket.io (which works really well with and is built for Node.js)
WebSockets are essentially bi-directional (low latency) event-based tunnels where data can be passed from client-to-server, and server-to-client without the need to make an AJAX (tcp) request per message.
This paired with a strong data-binding architecture (API -> Angular Binding) allows for customizable single page views, where the same data can be used to create a view, and update the back-end modal when the data gets updated.
The best way I can think to explain my question is with an example:
Say I have a small single page app with server side rendering. On the client side new page requests resolve using XHR, but on the server I'd like to just run the server-side resolvers directly.
The components of the front end call a getter on a data object eg: Data.page.get() which either polls the server or returns a locally stored value. So I want webpack to pack the relevant client code. But I want to point to a different Data object on the server that calls whatever logic the server uses to resolve the XHR request, be it a db call or a filesystem call or whatever.
At the moment I've got var Data = require(./data) getting the server logic. Is there a way to tell webpack 'Hey, don't use ./data here use ./data-client instead? Or am I going about this backwards somehow?
This seems like a pretty simple concept but I'm still pretty new to javascript and programming in general and I'm a little stumped as to the best way to do it.
Or should I be processing the node script with webpack too like described here: can webpack output separate script and module files for browser and node?
I'm currently using webpack 1, but happy to solve the problem using webpack 2 instead.
It turned out to be fairly simple.
Webpack resolves modules with an extension priority:
1) .webpack.js
2) .web.js
3) .js
So in my case require('./data') will resolve todata.jswith node, and so long as I have adata.web.js` it will resolve to that in webpack.
At least to my understanding.
I m actually developping a REST API using Node.js and Express 4.0 and I wanted to clarify something.
The service is actually working, but in a single javascript file, and I m looking for a good way to cut it into multiples parts.
I was thinking about MVC, but with the actual route system, what is the controller ? Is it the declaration function of the route ?
How can I separate the different route into multiple files ? (like user_routes, billing_routes) etc... I know how to export module etc... but having app = express() in multiple file seems to not work (different instanciation)
And where to start to the listen the part ?
These are beginner questions, but please, but explicit :-)
Thanks for advance
You can check out some these examples:
mvc: https://github.com/visionmedia/express/tree/master/examples/mvc and
route-separation: https://github.com/visionmedia/express/tree/master/examples/route-separation
Also here there are 2 good posts on SO about the subject:
https://stackoverflow.com/a/13611448/2846161
ExpressJS How to structure an application?