mvc pattern in hapi.js - javascript

i'm trying to orgnize the a hapi folder i added the database also the route but i cant seem to find a way to add the controller , so how i can make it so i can use controller instead of adding all the code in the router
thank you so much
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: ""
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
module.exports = con
Routes
"use strict";
const Path = require("path");
module.exports = [
{
method: 'GET',
path: '/',
handler: (request, h) => {
return 'Hello World!';
}
}
];
main.js
'use strict';
const Hapi = require('#hapi/hapi');
const Routes = require("./lib/routes");
const db = require('./config/db')
const init = async () => {
const server = Hapi.server({
port: 3000,
host: 'localhost'
});
server.route(Routes);
await server.start();
console.log('Server running on %s', server.info.uri);
};
db.connect
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();

Related

Node.JS JavaScript PeerJS ReferenceError: navigator is not defined

I'm trying to build a simple peer to peer image sharing demo app using Node.JS and PeerJS.
But when I try to run the app, I get an error ReferenceError: navigator is not defined.
This is a node.js backend app so I don't get why PeerJS is requesting to identify the navigator.
Could you please help me spot the problem?
Thanks in advance!
app.js
const express = require('express');
const fs = require('fs');
const { resolve } = require('path');
const Peer = require('peerjs');
const app = express();
const port = 9500;
const sender = new Peer('sender', {
host: 'localhost',
port: port,
path: '/'
});
const receiver = new Peer('receiver', {
host: 'localhost',
port: port,
path: '/'
});
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.get('/send', (req, res) => {
...
...
let image = readDataset();
const conn = sender.connect('receiver');
conn.on('open',()=> {
conn.send({
photo: image,
});
res.status(200).send("Image sent.");
});
});
app.get('/receive', (req, res) => {
receiver.on('connection', conn => {
conn.on('data', data => {
...
...
res.status(200).send("Image received and saved.");
});
});
});
// set the app to listen on the port
app.listen(port, () => {
console.log(`Server running on port: ${port}`);
});

How to split and export the mysql code into other file and can be use anywhere in Reactjs

I'm new in Reactjs. Its been 2 months since I learned Reactjs. I have a question. How to split the mysql code that i created into 2 file and can be call it anywhere. Here i attached the mysql code.
const express = require('express');
const app = express();
const mysql = require('mysql');
const cors = require('cors');
const { response } = require('express');
app.use(cors());
app.use(express.json()); //convert from json
// configure database
const db = mysql.createConnection({
user: 'root',
host: 'localhost',
password: '',
database: 'testdb',
});
// declare function
function getQuery(db, sqlQuery, res) {
db.query(sqlQuery, (err, result) => {
if (err) {
res.send(err.sqlMessage);
} else {
res.send(result);
}
});
}
function setQuery(db, sqlQuery, par, res) {
db.query(sqlQuery, par, (err, result) => {
if (err) {
res.send(err);
} else {
res.send(result);
}
});
}
// configure server port number
const listener = app.listen(process.env.PORT || 3333, () => {
console.log('App is listening on port ' + listener.address().port)
})
// call function
app.get("/users", (req, res) => {
getQuery(db, displayTableQuery, res)
});
app.post("/", (req, res) => {
const RegisterUserQuery = "INSERT INTO users set ?";
const par = req.body;
setQuery(db, RegisterUserQuery, par, res)
});
The code i want to be in other file:
// call function
app.get("/users", (req, res) => {
getQuery(db, displayTableQuery, res)
});
app.post("/", (req, res) => {
const RegisterUserQuery = "INSERT INTO users set ?";
const par = req.body;
setQuery(db, RegisterUserQuery, par, res)
});
How to make the code above in other file so that i can make it globally use for other person in the project. Thank you so much for your time. Hope you guys can help me :(
Create other file, example mysqlDatabase.js. And write in that file :
// configure database
const db = mysql.createConnection({
user: 'root',
host: 'localhost',
password: '',
database: 'testdb',
});
module.exports = db
Then to access in other file, use require and write function without db as argument :
const db = require('./mysqlDatabase.js')
// declare function
function getQuery(sqlQuery, res) {
db.query(sqlQuery, (err, result) => {
if (err) {
res.send(err.sqlMessage);
} else {
res.send(result);
}
});
}
function setQuery(sqlQuery, par, res) {
db.query(sqlQuery, par, (err, result) => {
if (err) {
res.send(err);
} else {
res.send(result);
}
});
}

Reusing postgresql pool in other node javascript files

I am creating nodejs backend app with postgresql database. What I want is when once I create connection to database in my db.js file, that I can reuse it in other files to execute queries.
This is my db.js file
const pool = new Pool({
user: 'us',
host: 'localhost',
database: 'db',
password: 'pass',
port: 5432,
})
pool.on('connect', () => {
console.log('connected to the Database');
});
module.exports = () => { return pool; }
And this is how I tried to use it in index.js file
const db = require('./db.js')
app.get('/', (request, response) => {
db().query('SELECT * FROM country'), (error, results) => {
if (error) {
response.send(error)
}
console.log(results)
response.status(201).send(results)
}
})
There aren't any errors, and when I go to this specific page, it's keep loading. Nothing in console also.
But, if I write a function in my db.js file and do something like pool.query(...), export it, and in my index.js I write app.get('/', exportedFunction), everything is working fine.
Is there any way not to write all my (like 50) queries in just one (db.js) file, because I want to organise my project a little bit?
To streamline your project structure entirely, if you're starting from scratch maybe try this :
index.js
const express = require('express');
const app = express();
const PORT = 8080;
const bodyparser = require('body-parser');
const baseRouter = require('../your-router');
app.use(bodyparser.json());
app.use(express.json());
app.use('/', baseRouter);
app.listen(PORT, function () {
console.log('Server is running on PORT:', PORT);
});
your-router.js
const Router = require('express');
const router = Router();
const getCountries = require('../handlers/get');
router.get('/check-live', (req, res) => res.sendStatus(200));
// route for getCountries
router.get('/countries', getCountries);
src/handler/get.js
const YourService = require('./service/your-service');
function getCountries(request, response) {
const yourService = new YourService();
yourService.getCountries(request)
.then((res) => { response.send(res); })
.catch((error) => { response.status(400).send({ message: error.message }) })
}
module.exports = getCountries;
src/service/your-service.js
const connectionPool = require('../util/dbConnect');
class yourService {
getCountries(req) {
return new Promise(((resolve, reject) => {
connectionPool.connect((err, db) => {
if (err) reject(err);
let query = format('SELECT * FROM country'); // get inputs from req
db.query(query, (err, result) => {
if (err) reject(err);
resolve(result);
})
});
}));
}
}
module.exports = yourService;
dbConnect.js
const pgCon = require('pg')
const PGUSER = 'USER'
const PGDATABASE = 'localhost'
let config = {
user: PGUSER,
database: PGDATABASE,
max: 10,
idleTimeoutMillis: 30000
}
let connectionPool = new pgCon.Pool(config);
module.exports = connectionPool;
Please consider this as a basic example, refactor your code to use callbacks/async awaits (in the above example you can just use callbacks not needed to convert into promise), if needed - you can have DB-layer calls from the service layer in order to extract DB methods from the service layer.

What is causing MySQL Database to refuse connection?

I am trying to use MySQL for a local database in my Electron app to store settings and user data but am getting the following error:
Error: connect ECONNREFUSED 127.0.0.1:3306
I can't seem to figure out what is causing this and think I have it properly set up. Here is the code for my setup:
// main.js (Electron's main file)
const path = require('path');
require(path.resolve(`${__dirname}/assets/server/server`));
// server.js
const express = require('express');
const apiRouter = require('./routes/index');
const app = express();
app.use(express.json());
app.use('/api', apiRouter);
app.listen('3000', error => {
if (error) {
return console.error(error);
}
console.log('Server started on Port: 3000');
});
// routes - index.js
const express = require('express');
const db = require('../db/index');
const router = express.Router();
router.get('/', async (request, response, next) => {
try {
response.json(await db.all());
} catch (error) {
console.error(error);
response.sendStatus(500);
}
});
module.exports = router;
// db - index.js
const mysql = require('mysql');
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: null,
database: 'storage',
connectionLimit: 10,
port: 3306
});
function all () {
return new Promise((resolve, reject) => {
pool.query('SELECT * FROM Products', (error, results) => {
if (error) {
return reject(error);
}
resolve(results);
});
}).catch((error) => {
console.error(error);
});
}
module.exports = { all };

Unable to Connect to MSSQL from NODEJS with SSL

I am trying to connect to Sql Server Database using Node.js
Below is the code :
var express = require('express');
var sql = require('mssql');
var app = express();
app.get('/', function (req, res) {
var config = {
server: 'server',
database: 'database',
user: 'user',
password: 'password',
options: {
encrypt: true,
trustServerCertificate:false
}
};
sql.connect(config, function (err) {
if (err) console.log(err);
var request = new sql.Request();
console.log("preparing request");
request.query("some query").then(function (recordSet) {
if (err) console.log(err);
res.send(recordset);
});
});
});
app.listen(8080);
I get the log: "preparing request". After that nothing happens. There isn't any error log either.
In Java I connect to my DB using following URL:
jdbc:jtds:sqlserver://servername;SSL=request

Categories

Resources