Is it possible to run Node.js commands alongside three.js - node.js

I am attempting to run node.js commands within my three.js project. Something as simple as declaring SQLite3 and initializing my database doesn't seem to be working. Ultimately I want to run UPDATE, INSERT, DELETE commands throughout game play as the user picks up items. Since node.js and three.js are both JavaScript packages, I assumed they would fit well together. There doesn't seem to be much information about this, so what I want to know is it possible to combine the two or am I wasting my time?
var sqlite3 = require('sqlite3').verbose();
var fs = require('fs');
var db = new sqlite3.Database('shopDB.db');

As discussed, you can't use node.js in the browser. If you want your browser app to talk to a database, you can expose a REST API around your database. This means exposing some HTTP endpoints to access your data.
For example, you might POST some JSON object describing some data from your browser-based app to http://someurl/some_path and your web server would be listening for a POST to the /some_path url, at which point it would read the POST data and insert a new entry into your database.
You could use jQuery's ajax() function to make requests to the API.
This blog post runs through an example REST API built around a sqlite database.

Related

Creating an Express API from MongoDB server automatically

I have a pretty large MongoDB server running on my local machine, I know how to create an API using Express & Node.js and know how to use routes, etc. But I only know how to add new data to a route using the POST method. My database has tens of thousands of entries in different collections and so it would be impossible to add them all manually.
I wanted to know if there was a way to quickly convert my entire mongodb local database into an API with Express so I can access it client-side from my React.js application.

External API Calls server or client side?

I'm currently working on an analytics webapp with a react frontend and node (express) backend.
Describing the functionality in a nutshell:
A user will be able to login on the website, search for a YouTube username and then the YouTube API is called, the data will be stored in a mysql db via my express API and also the data will be used to calucalte some statistics which afterwards are displayed in a dashboard.
Now I was wondering if I should:
Call the YouTube API from the frontend, i.e. inside my react code, do the calculations display them and and then store it in the DB via my express API.
Or, from the react app call an endpoint in my express API that will then call the YouTube API, store the data in the DB and then pass on the data to my react app.
Are there any best practices or up-/downsides to either approach?
When answering questions like these, it's important to remember that the client-side is different for each and every user that visits your website, their internet speed, their GPU & CPU power, etc., but the server is most commonly held in a stable container and much more powerful than a client.
The proper way would be the following:
1. Obtain a search query from a client
Meaning you should get the user's search query from an input, or any other form of control (text area, checkbox, etc.), this way client is doing the least business logic, as it should. The client should always focus more on UI / UX rather than business logic.
2. Send query to the server
Let the server use the query you've just obtained from client, call the youtube api from the server (either explicitly using Axios, or find a node.js youtube library), and do all the necessary calculation on the backend
3. Send processed data to the client
Let client receive the data in the form which is ready for use (iterations, mappings, etc.) - again separating concerns, server - business logic, client - UI / UX
Now to be fair, the example you have will most commonly be done all on the client-side, since it is not as computationally heavy as other enterprise examples, but this is a good rule to follow for big projects, and no one would really complain if you did it this way, since it would be the proper way.

the process between a frontend, backend and cloud database

I'm having a hard time finding information on simple straight forward process. I keep getting forwarded things like the "google cloud engine" and such.
I am attempting to start a new project to expand my knowledge. Previously, I developed a localhost web app which included; working frontend with react, express backend (REST api) and mongo database. I understood the concepts effectively of rest calls, state management and authentications and such.
The new setup is flutter, nodeJS (express), and firebase.
Looking at quick tutorials I have a simple flutter app working with a http post for a user sign up. Makes sense.
Normally in nodeJS, I'd have a route it hits e.g. router.post('/users', function (req, res, next) ... and then I'd have a model scheme to and if everything is correct it would post.
Exploring the relationship with firebase and nodeJS I'm slightly overwhelmed on how this works. I thought it would be something simple as an authentication key (which, btw I have sorted out with firebase-admin) and then proceed on my merry way with my models and routes/services.
Are the models defined within firebase, and my node just confirms the requests and talks through the firebase API? I haven't been able to locate any simple resources for this.
Since you didn't say which product within Firebase you're using (Firebase is a suite of products, not just one thing), I'm going to assume you mean Realtime Database or Cloud Firestore. They are both schemaless NoSQL databases -- they don't impose any structure on the data you put into them. There's no model, there's no validation. That's all stuff you have to do on your own, if you want. Or not, if you want flexibility.

How to fetch from nodejs-api-starter into react-starter-kit

I am trying out React-Starter-Kit for the first time and loving all the cutting edge features baked in (apollo/graphql-client in particular). A crucial part of any app for me is the database, and for that my understanding is the same author provides nodejs-api-starter which sets up a REST interface for accessing Postgres at localhost:5000 and has a graphql webui at localhost:5000/graphl.
That is about as far as I have been able to understand of the setup so far. I have changed the frontend code a little bit so a new Component "Counter" is loaded on the home page. I need to be able to make a new counter, fetch the latest counter, and increment decrement the counter. Write now the component just outputs the 'value' retrieved from the server at 5000.
I do not think I am accessing the 5000 server correctly, do I put the port in this url line somehow?
You can pull the repo down from : https://github.com/Falieson/react-starter-kit-crud-counter-demo
This is my first time setting up a nodejs api server, I am used to using MeteorJS which has pub/sub to MongoDB baked in. I am looking forward to the separation the RSK strategy (which seems more industry standard?) provides.
I've just done setting up the full site with Database from React-Stater-Kit, I'm also a newbie so I understand your frustration.
About this question, you don't need the NodeJS-API-Starter, it has enhanced function ( such as Redis cache ) and it's not suited for newbies. You should look deeper into the RSK, it already has the DB. If you ran the boilerplate and played around, change is you'll see file database.sqlite in your folder, it's the database. Here are the things you should learn:
Use SequelizeJS to connect the NodeJS server with database. Your database can be MySQL/MariaDB, PostgreSQL or SQLite. The connection is easy and there's tool to auto-generate Models from your database
How to create GraphQL's Types and Queries. If your queries need to search through the database, import Sequelize's models and use its functions.
Test your API via GraphQLi
Note: if you want to use MongoDB or other NoSQL, try Mongoose instead of Sequelize.

How to build a website on Node.js?

I've just started diving into Node.js after several years of PHP programming and I would like to build a Node.js app for my next project, but I have no clue how to do it.
Are there any resources for a Node.js jumpstart?
Thanks in advance!
You should think of Node.js as some kind of Apache + PHP, meaning that you can program your website and your webserver with Node.
Node has some important differences with your basic PHP, it's evented, asynchronous, non-blocking. You have to learn how to deal with callbacks, don't block the event loop and other things.
What you should do is try to learn the basic stuff with Node at the beginning, here are some great resources: https://stackoverflow.com/tags/node.js/info (my favorite has been nodetuts.com and the excellent book by it's author, Hands on Node).
After you've learned the basics, you can find Express really useful as a web framework and Socket.IO if your app is focused on real-time.
I think you're searching for a node.js jump start to build some meaningful web page with node. Take a look at express, which is a node web framework. They offer a nice but short tutorial (under guide).
You need to run Node.js on a web server. Basically, you need a VPS or Dedicated Server over which you have full control. [PHP runs through the standard web server, Apache. Node.js is the webserver.]
Or you find a Node.js host that'll do it for you.
Node.js is essentially your webserver that would replace Apache so the only hosting that you would find to run Nodejs is a dedicated server or a cloud instance in which you would have to install and run nodejs on. The machine that you run node.js on needs to have a domain name pointed to it or the only way you can access the server is by its IP address which is this case your localhost.
Another option is to use something like Knockout.js (http://knockoutjs.com/), and have the page make JSONP calls to the Node.js server. It's really easy to use Node to send JSON to the client, since it's JavaScript on the server. Using a framework on the client makes it really easy to create a dynamic page based on that JSON data.
The disadvantage is there is no graceful degredation for older browsers. The advantage is a potentially blazing fast website with great AJAX built-in right from the start.
Here is some sample code for using Node to generate a JSONP response:
function writeJsonpResponse(res, jsonpcallback, obj) {
var serialized = JSON.stringify(obj);
res.writeHead(200, {'Content-Type': 'application/javascript'});
res.write(jsonpcallback + '(' + serialized + ');');
res.end();
}
Read the README.
Setup environment.
take a look at package.json (or npm init to create one)
install dependencies (npm install / axios, nodemon, express, mysql, react, babel)
add scripts to start server & webpack if needed
Get acquainted with file structure.
separation of concerns - public/dist, server, db, client
think about the flow of data
Ensure basic HTML structure.
check that bundle.js file / everything it needs is loaded in
need a div id to render react with (like app or root)
Spin up Express server.
Start server and webpack is separate terminals.
check for console.log that server is listening!
Write routes (get and post requests) on your server.
check that get & post requests are working w/ Postman!
Create mySQL database (db/index.js).
Design & import schema (how to structure data tables).
make sure you’re in the db folder when importing yr schema girl!
Connect db to server.
check for console.log that connection is successful!
Write insert/retrieve db query functions.
don’t forget to module.exports those queries to the server!
will call query functions in routes/get & post requests in server
Set up basic React structure.
index.js’s only task is to render your app component to the div id app
need a stateful App component to render all other components
remember to import & export default everything!
Design the rest of your components, decide whether or not they will be functional (stateless) or class components (stateful).
draw it out!
what props (data & functions) do you need to pass down?
Write those components.
Work through one data flow that executes through all the pieces. Get your input handler to send the client side POST request (using axios) to the server route, which will execute your API call (if there is one) and then insert that data to the database.
remember to handle your errors!
Handle events / conditional rendering.
1. user event gives input (onChange e.target.value)
2. write a handleChange f(x) to update state to that new input
3. input is submitted (onClick)
3. write a handleSubmit f(x) that takes in the updated state and makes an axios POST request w/ that { input } to the appropriate server route
remember to bind method functions appropriately!
Call query functions in routes/get & post requests.
Check that data from the client is being stored in the database.
describe those tables my friend!
Do an AJAX get request (use axios or fetch) on client side to api endpoint.
Store the incoming data in setState
May want to do a GET request in componentDidMount to always render appropriate info for client
Yay! You successfully set up your server, database, and client, passed data between them, potentially manipulated the data, stored that data, and displayed the appropriate data to the client!
Tackle those user stories!

Resources