Create an API directly from a data source - mysql

I need to create my own REST API.
I just saw strongloop and loopback and I thought it will be perfect for my project.
In fact, I was able to get mysql connected using strongloop. However, I had to create something called a "model" and I did it. But, it was like creating a new model from scratch and use it for persisting on the Datasource.
Instead, what I was looking for, is to get a REST API directly from my model on the DB.
I mean taking the models from each table on the DB and then set them up as web services.
Is that possible?
I am newbie on these technologies, although I think it is an interesting question.
Thanks

I'm not sure of a Node tool to do what you're asking, but in other languages / databases you have some choices!
The only one I'm really familiar with is postgrest.
postgrest: You import your data into a Postgres database (similar to MySQL), and it generates a REST API on top of your tables instantly. Bam. Done. I've used this and it was amazingly awesome. You can also deploy it directly on Heroku.

StrongLoop actually has a "discovery" tool for just this purpose! Read up on that page, but here's the basic code to do it. Just drop this code in a file inside /server/boot/ (the docs are wrong on that, it must be in the directory I mention). Of course, you'll need to tailor it for your use case:
var loopback = require('loopback');
var ds = loopback.createDataSource('mysql', {
"host": "yourhost",
"port": 1234,
"database": "foobar",
"username": "someuser",
"password": "somepass"
});
// Discover and build models from a given table
ds.discoverAndBuildModels('PERSON', {visited: {}, associations: true},
function (err, models) {
// Now we have a list of models keyed by the model name
// You only need the rest of this if wanted to inspect what came in...
// For example, you could find the first record from the table
// and verify info or something.
models.Person.findOne({}, function (err, person) {
if(err) {
// handle this if need be...
console.error(err);
return;
}
// Some code using `person`
});
});
Good luck!

I was supposing "discovery tool" was to find out pattern, cluster or whatever else thing into the data. But following
the recomendation of #jakarella I went with more depth.
It was even easier than that, because you can do everything via StrongLoop Arc (GUI). I always prefer cli
but to have a general look of it, sometimes is better to start with the GUI if you don't have too much idea about the subject.
Anyway,
first of all you would need to connect your datasource before (installing previously the driver).
After that, through StrongLoop Arc you can do "discover the models" choosing your tables (taking care of run Arc and restarting every time
you get a new model) and that's it, you get an API over your Datasource
(for testing go to the explorer).
I described before generally the main tasks but if anyone needs more detail pls let me know. Hope this helps to anyone else who is looking to do
something similar
thanks guys for the interest.

Related

How do I use Nodejs for backend using SQL workbench?

I am a beginner and this is my first full-stack web development project and I have completed the front-end part and created the related tables using MySQL... and now I want to link the tables to front-end using nodejs. How do I proceed further?? Is it proper to use workbench in the first place for a full-stack project?? Please guide me.
SQL Workbench is just an IDE for mySQL so thats fine for building out your DB, setting permissions etc.
Your question is not one that is simple to answer, simply because the steps in creating, setting up a full web app is not that simple to explain..
There are few things you will need to do to hook this up
Ensure you have a mySQL middleware installed
Ensure you have the routes created
Use a templating engine like EJS
Once you have the basic flow working ( meaning you can hit your page and it returns the correct page ) you will want to then hook into the DB before sending the response object back to the browser. A typical flow would be, on your 'get' response, you would perform the mysql 'select'
This should be promis based but will depend on the actual package you install, I don't use mysql but a postgres command is something like
query.pool("SELECT is, name, des from table where id = '10' ").then(results => {
//put in your response code here to send back to the page
}).catch( e => {console.error(e)})
The response code portion is where you would send things back to the page, in an ejs template would then be able to access the response and display the data.
I know, this is a bit light on full explanations and that is because the proper response would be huge!
Judging by the question I would guess you are a bit new to node / DB etc ( sorry if you are not ) I think what may be very helpful is to watch a few youtube videos on setting up Node and EJS ( or any templating engine for that matter )
That should give you the basic understanding and setup of the project.

How to subscribe and listen to channels with feathers client?

Please point me on the right path. I use angular for the client and I get my data with:
private getOrders(query: {}) {
return from(this._feathers.service('orders').find({ query }));
}
this works great and I get an observable in return.
But I don't know how to get the messages on the client side.
For instance, the app template in channels.ts mentions something like this:
app.service('messages').publish(() => {
return [
app.channel(`userIds/${data.createdBy}`),
app.channel(`emails/${data.recipientEmail}`)
];
});
Well, how can I get the data from the client for emails/${data.recipientEmail}?
What is the syntax?
Things are actually pretty straight forward!
My confusion was that I had experience with socket.io and I created a channel per each service I had back then.
In feathers, the channels are a means of sending the data. So every service can post to any channel and it all depends to which channel you subscribe to!
On the client side I had the confusion of how I can access that data thinking that I need a 'custom' channel name and method. This actually does not matter as the clients are subscribed to different channels and in the end data does come from a service and method in that service!
I hope this makes sense and clears up confusion for people that are like me. :)
This article clears things up: https://blog.feathersjs.com/feathersjs-channel-subscriptions-647c771ca6c8

How to create JSON tree and nested nodes in Firebase using AngularFire2

There is no proper documentation for AngularFire2 v5, so I don't know where am i supposed to learn from, but here it's only for Firestore. I don't use firestore, I use Firebase Realtime Database. https://github.com/angular/angularfire2/tree/master/docs
However, I'm pretty new to it, and I'm looking how can I store data in a collection, that would look something like this:
nepal-project-cffb1:
users:
userid:
email: "lajmis#mail.com"
score: 1
My function now looks like this:
this._db.list("users/" + "id").set({
email: this.user,
score: this.score
})
but it doesn't work, I get Expected 2 arguments, but got 1. error. There are a bunch of syntaxes, like .ref .list and i don't know which one to use.
There is an entire section of the AngularFire guide dedicated to RTDB, so I'm confused by the statement that there is no real documentation. Typically you would use valueChanges() to create a list observer as described here for reading, and set() is covered here.
So as that doc illustrates, you need to pass the key of the record to be modified, and also the data to be changed when you call it.
this._db.list("users").set("id", {...});
But if you aren't monitoring the collection, you can also just use db.object directly:
this._db.object("users/id").set({...});
One aspect that may not be immediately intuitive with AngularFire is that it's mainly an adapter pattern intended to take away some of the boilerplate of ferrying data between your Angular model and your Firebase servers.
If you aren't syncing data (downloading a local copy) then there's no reason to use AngularFire here. You can simply call the Firebase SDK directly and avoid the overhead of subscribing to remote endpoints:
firebase.database().ref("users/id").set({...});

MediaWiki Extension to register new user

I made OnBeforeinitialize hook. I need place there code which register new user if user doesn't exists in database.
Which MediaWiki class and functions should be used?
If you need to create users, chances are you are doing something wrong. Users should be created on login/signup (use a PrimaryAuthenticationProvider to tell the system to create them), or when they are authenticated based on request data (use a SessionProvider). There is also User::newSystemUser but it's only meant for scripts.
Even if I don't know, what you really want to do, where the data for the user should came from, and why you want to do this in the BeforeInitialize hook (so, in fact, any useful information to really know and understand what you want to achieve is missing, therefore, you'll get an answer to your concrete question without any guarantee, that it works like you expected in your use case). However, to create a new user, you can use the createNew function of the User class. You should check, if the user is already present in the database.
EDIT:
An usage example:
$user = User::createNew( 'Testuser', [ 'email' => 'email_from#external_source.com' ] );

node js + mysql push notification

I am working on project where I want to give notification like facebook. i.e. when someone comments on others profile or like any link on others profile. I want to use nodejs for real time push notification.
These data of comments, likes are stored in the mysql database in "Notification table" via ajax request or by posting the form to php.I found many tutorials of nodejs on net for the real time push notifications but unfortunately they talk about keeping watch on file and emits the notification when file is updated.
does anybody knows how to keep watch on the mysql table, so whenever, any data is inserted in the table, it emits the notification. I am not getting any way what kind of code I should write in nodejs.
Please let me know if more explanation is needed.
Thanks in advance.
You can use node.js with a mysql library to poll your database for new notifications, which I think is what you're trying to do. I've never done that specific task personally, but I know it's achievable.
In terms of what kind of code you need to write, try looking up "Node Middleware Tutorials" with perhaps some variations that include MySQL in the search query and you'll find at least an idea of what you should be looking for.
If I can I will update this answer with more specific code samples to get you moving in the right direction.
You can use nowjs and add on the after save (if you are using an mysql active record) to notify the client with this package.
On the server
var httpServer = require('http').createServer(function(req, response){ /* Serve your static files */ })
httpServer.listen(8080);
var nowjs = require("now");
var everyone = nowjs.initialize(httpServer);
everyone.now.logStuff = function(msg){
console.log(msg);
}
On the client
<script type="text/javascript" src="http://localhost:8080/nowjs/now.js"></script>
<script type="text/javascript">
now.ready(function(){
// "Hello World!" will print on server
now.logStuff("Hello World!");
});
</script>
For more information take a look at the examples