Connect react-native to firebase and mysql - mysql

I'm developing an application using react-native. I can easily connect my react-native application to firebase. My idea is to use firebase authentication, but with data from my MySQL database.
What is the best/correct way to use firebase and mysql?
My idea is use ajax request from react-native to mysql in order to validate the username and password against the data into my MySQL database. Then use the ID returned from this request to create or load a user from firebase. Is it the correct way?
I am sorry if it doe snot make sense. I just start working with react-native and firebase.
Thanks

Well...
For mysql you can use axios plugin. Is the best way to work with mysql database.
Firebase use asynchronous request, if you want work with both the best way is using axios.
First, you get user from your mysql table, correct?
So.. you do something like that :
return axios.get(server_address&param=PARAM_VALUE)
.then(response => {
return(response);
}).catch(function(error) {
alert.error(error.message);
});
Axios aways return a JSON response.
You can use GET or POST method.
So... with the JSON, you can send for firebase your data for load or create user.
like that:
return firebase
.auth()
.signInWithEmailAndPassword(loginEmail,loginPassword)
.then( user => {
return user;
})
.catch(error => {
if ((error.code == 'auth/user-not-found') || (error.code == 'auth/invalid-email')) {
return new Promise((resolve, reject) => {
Alert.alert(
'User not found',
'Create ?',
[{
text: 'No',
onPress:() => resolve(),
style:'cancel'
},{
text:'Yes',
onPress: () =>{
firebase
.auth()
.createUserWithEmailAndPassword(loginEmail,loginPassword)
.then(resolve)
.catch(reject)
}
}],
{cancelable: false}
)
})
}
return Promise.reject(error)
})
For a complete guide to axios :
https://github.com/qiangmao/axios#readme
For a complete guide to firebase:
https://firebase.google.com/docs/auth/?hl=en

Related

How to connect my react native expo project with MySQL? [duplicate]

I'm using React Native. I want to find the data I entered in React Native in the database. For example, in the database of the user name I entered, "select id from table where ('data I entered in react native')". I want to find the table with the user name and pull the user's id.
var name = this.state.username;
"select id from table where (name)"
I want to pull the id of the user name like this.
There is no direct connection between RN and Mysql. Use Node js for this.
Step: 1
npm install express
npm install body-parser
npm install mysql
Step: 2
const connection = mysql.createPool({
host : 'localhost', // Your connection adress (localhost).
user : 'root', // Your database's username.
password : '', // Your database's password.
database : 'my_db' // Your database's name.
});
// Starting our app.
const app = express();
// Creating a GET route that returns data from the 'users' table.
app.get('/users', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'users' table).
connection.query('SELECT * FROM users', function (error, results, fields) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is were the data is.
res.send(results)
});
});
});
// Starting our server.
app.listen(3000, () => {
console.log('Go to http://localhost:3000/users so you can see the data.');
});
Now, how do we get that data on our React Native App?
That's simple, we use the fetch function.
To do that, instead of using 'localhost:3000', you'll have to directly insert your PC's ip adress. If you use 'localhost', you're acessing your smartphone/emulator's localhost. And that's not what we want. Follow this example:
test(){
fetch('http://yourPCip:3000/users')
.then(response => response.json())
.then(users => console.warn(users))
}
You need to have a backend service/API in order to fetch data from database. try using Node, and write a simple backend since its JavaScript. You can execute sql queries on backend, retrive data from mySQL to your node server and then you can fetch data from the backend server to react-native using fetch method. (both your backend API and the device that running react native application should be running on the same network.)

Add information to List in Angular

I'm learning Angular 6 and I have a List shown on my site. Now, i need to give Users of my site the possibility to add entries to that list. There's a form with 4 fields and a submit button, when Submit is clicked, the values should be stored anywhere and all the entries should be shown on the site, permanently, not just in the active session.
How can i achieve this? Do i need to include some sort of database? Or is it possible to append the new dataset to a JSON file?
Thank you in advance
EDIT: This is a training project and will only be available through the Intranet of the Company i work at, so security concerns about missing Captchas or similar things are not a factor
If you are going to use this project for long time and if number of entries is higher and you have alot of users, then you should use some data base. And if there is limited number of users and you need this app temporary then using json file is also good. Using json file will save you from database logics etc if you are not familiar with them
To SAVE some data anywhere you HAVE TO use some kind of database.
Angular is JavaScript framework. It helps to write applications. But it does nothing with server side (except, of course, CLI and other stuff which NodeJS people likes to do).
JSON is not the only way to communicate between browser and the server. But in Angular it's easiest way.
You'll need something on the server (I suppose PHP script) which will receives data from your Angular app and will send back some feedback. In the case with PHP you'd learn how to receive JSON POST ($_POST and $_REQUEST will not work)
What I advise you in terms "how to learn Angular" is go to this step-by-step tutorial https://angular.io/tutorial
Run it twice or three times and you'll understand how works Promises, Observables, communications, templates, services and all other stuff.
It is possible to append the data to the new dataset to the JSON file create a service to read that JSON file using that service so to give you the basics of reading that JSON file
Config.service.ts
#Injectable()
export class ConfigService {
private static _config: any = {}
constructor(private _http: Http) { }
load() {
return new Promise((resolve, reject) => {
this._http.get('../assets/' + 'data.json')
.map(res => res.json())
.subscribe((data) => {
console.log("inside http get of the new service");
console.log(data);
ConfigService._config = data;
resolve(true);
},
(error: any) => {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
});
});
}
// Gets a value of specified property in the configuration file
get(key: any) {
console.log("tell me the base :" + ConfigService._config['BASE_URL']);
return ConfigService._config[key];
}
}
export function ConfigFactory(config: ConfigService) {
return () => config.load();
}
export function init() {
return {
provide: APP_INITIALIZER,
useFactory: ConfigFactory,
deps: [ConfigService],
multi: true
}
}
const ConfigModule = {
init: init
}
export { ConfigModule };
add these lines in your main module
app.module.ts
import { CommonModule } from '#angular/common';
import { ConfigModule, ConfigService } from './config-service';
providers:[
ConfigService,
ConfigModule.init(),
]
Then, you can inject this service on any component or service that wants the data
Also, you have to add an assets folder under your app folder and place the data.json there.

Building a SaaS product with Node + Express + Sequelize + (Mysql or Postgres)

We are planning to build a SaaS based product, so mainly after a lot of search, we found there are three database approach for designing a SaaS product.
Separate database for each tenant
Separate schemas for each tenant
Shared schema and one databases for all tenants(But will query using tenant_id)
So we are planning to get into option 2,
So initially we use Mysql, but we did not found how to get multiple schemas in mysql, we are using Sequelize as ORM.
After a lot of googling, we found many Multi tenant based product is using postgresql for the powerful schema approach, So we tried this library:
https://github.com/westmark/sequelize-multi-tenant-enhancer
We tried this library for multiple schema based approach, but the data are
not showing according to the tenant, Also i opened a issue in github,
So if you have any idea, or any post which help me to build a SaaS product, Help me
NOTE: My Stack: Node + Express + Angular + Mysql or Postgres
My Question is How to use multiple schemas in postgres?
Finally i decided to use option 2, and i moved to Postgresql instead of mysql, because Postgresql has schema based approach!
Now my final code:
const postgresDB = new Sequelize('postgres://localhost:5432/test_enduser');
postgresDB.authenticate().then((err) => {
if (err) {
console.log('There is connection in ERROR.');
} else {
console.log('Postgres Connection has been established successfully');
}
});
postgresDB.define('inventory', {
name: Sequelize.STRING,
});
const createSchema = () => {
Business.findAll({
raw: true,
}).then((data) => {
data.forEach((client) => {
postgresDB.createSchema(client.code).then(() => {
Object.keys(postgresDB.models).forEach((currentItem) => {
postgresDB.models[currentItem].schema(client.code).sync();
});
// new schema is created
console.log('Postgres schema created');
}).catch((err) => {
console.log(err.message);
});
});
});
};
createSchema();
// apis
exports.getAllBusiness = (req, res) => {
postgresDB.models.inventory.schema(req.user.code).findAll()
.then((results) => {
res.send(results);
});
};
exports.postBusiness = (req, res) => {
const user = {
name: req.body.name,
};
postgresDB.models.inventory.schema(req.user.code).create(user)
.then(data => res.status(200).send(data))
.catch(Sequelize.ValidationError, err => res.status(422).send(err.errors[0].message))
.catch(err => res.status(400).send(err.message));
};
I am setting my postgres connection
Simply for test i am creating a table called "inventory"
In my application a online came and he signup, while signup i am storing there Business Code into my Business table(The Business table coming from separate DB, which is a super main app DB), so i am finding the business code and looping and make dynamic schemas in postgres
Now see my api, I am doing CRUD based on req.user.code(from login session),and i am finally matching showing datas according to particular schemas,
So finally i have clean separate schemas for each client
Thanks!

Angular 4: Recreive data from MySQL to array

I have been learning Angular and I made simple app which use database request and print all information from MySQL. In my service I made this method
getCharacters(){
return this.http.get('http://localhost/something/controller/characters')
.map(
(response: Response) => {
return response.json();
}
);
}
In characters-list component I used subscribe()
this.charactersService.getCharacters().subscribe(
(characters) => {
this.characters = characters;
}
);
It works of course but it's not practical. I want to use one array to a few components so I would retrieve data from MySQL one time and use this array in all components I want to.
How to do that?

Server not returning JSON from Express to React (proxy)

I'm attempting to make an application that has a React frontend (running on port 8080) and an Express-Node.js backend (on port 3000). I'd like for my client to use fetch to request data from my server. So far, what I've read online indicates that I need to add a proxy entry to my package.json with the value of http://localhost:3000. I've done this, my server receives the request correctly, but its response is not what I expect (a JSON object). What am I doing wrong?
//Server
app.get('/search', function(req, res) {
...
//console.log(section) <-- Is the correct value
res.json(section);
})
...
app.listen(3000)
//Client
handleTouchTap() {
fetch('/search?crn=10001').then(function(response) { //<-- Hard-coded for testing
return response; //<-- Does not contain the value of "section" from server
}).then(function(data) {
console.log(data); //<-- Likewise, does not contain the value
});
}
//From package.json
...
"proxy": "http://localhost:3000",
...
You need to pull the json out of your response:
fetch('/search?crn=10001')
.then(response => response.json())
.then(section => console.log(section));