How to fix sequelize connection issue while generating index.js? - javascript

I new in node.js and have some problems with sequelize-cli.
I have sequelize model and while I run the project, i get error in my index.js:
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
TypeError: require(...) is not a function
The project can't find or read this (sequelize, Sequelize.DataTypes).
My project: server.js
const express = require("express");
const productRouter = require("./routers/productRouter");
const discountRouter = require("./routers/discountRouter")
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
// Запрос на таблицу с продуктами
app.use("/shop", productRouter);
// Запрос на таблицу со скидками
app.use("/shop", discountRouter);
app.listen(PORT, () => console.log("Server is working ... "));
productRouter.js
const Router = require("express");
const router = new Router();
const productController = require("../controllers/productControllers");
// Получаем все товары
router.get("/products", async (req, res, next) => {
const resultOfGetAllProducts = await productController.all();
if(resultOfGetAllProducts === Error) {
return res.sendStatus(500).json(Error);
} else {
return res.sendStatus(200).json(resultOfGetAllProducts);
};
});
// Получаем конкретный товар
router.get("/product/:id", async (req, res, next) => {
if(!req.params.id) return res.sendStatus(400).send("Product ID is not specified.");
const id = req.params.id;
const result = null;
const resultOfGetOneProduct = await productController.one(id, result);
if(resultOfGetOneProduct === Error) {
return res.sendStatus(500).json(Error);
} else {
return res.sendStatus(200).json(resultOfGetOneProduct);
};
});
// Добавляем товар
router.post("/product", async (req, res, next) => {
if(!req.body) return res.sendStatus(400).send("Product parameters are not specified.");
const product = {
product_name: req.body.product_name,
price: req.body.price,
product_description: req.body.product_description
};
const result = null;
const resultOfCreateProduct = await productController.create(product, result);
if (resultOfCreateProduct === Error) {
return res.sendStatus(500).json(Error);
} else {
return res.sendStatus(200).send("The product has been created.");
}
});
// Обновляем товар
router.put("/product/:id", async (req, res, next) => {
if(!req.params.id) return res.sendStatus(400).send("Product ID is not specified.");
if(!req.body) return res.sendStatus(400).send("Product parameters are not specified.");
const product = {
product_name: req.body.product_name,
price: req.body.price,
product_description: req.body.product_description
}
const id = {id: req.params.id};
const result = null;
const resultOfUpdateProduct = await productController.update(id, product, result);
if(resultOfUpdateProduct === Error) {
return res.sendStatus(500).json(Error);
} else {
return res.sendStatus(200).send("The product has been updated.");
};
});
// Удаляем товар
router.delete("/product/:id", async (req, res, next) => {
if(!req.params.id) return res.sendStatus(400).send("Product ID is not specified.");
const id = {id: req.params.id};
const result = null;
const resultOfDeleteProduct = await productController.delete(id, result);
if(resultOfDeleteProduct === Error) {
return res.sendStatus(500).json(Error);
} else {
return res.sendStatus(200).send("The product has been deleted.");
}
});
module.exports = router;
productControllers.js
const productModels = require("../models/productModels");
exports.all = async function getAllProducts() {
const result = await productModels.all(function(err, docs) {
if (err) {
console.log(err);
return err;
} else {
return docs;
};
});
return result;
};
exports.one = async function getOneProduct(id, cb) {
const result = await productModels.one(id, function(err, doc) {
if (err) {
console.log(err);
return err;
} else {
return doc;
}
});
cb = result;
return cb;
};
exports.create = async function createProduct(product, cb) {
const confirmationOfCreate = await productModels.create(product, function(err, result) {
if (err) {
console.log(err);
return err;
} else {
return result;
}
});
cb = confirmationOfCreate;
return cb;
};
exports.update = async function updateProduct(id, product, cb) {
const confirmationOfUpdate = await productModels.update(id, product, function(err, result) {
if (err) {
console.log(err);
return err;
} else {
return result;
}
});
cb = confirmationOfUpdate;
return cb;
};
exports.delete = async function deleteProduct(id, cb) {
const confirmationOfDelete = await productModels.delete(id, function(err, result) {
if (err) {
console.log(err);
return err;
} else {
return result;
}
});
cb = confirmationOfDelete;
return cb;
};
productModels.js
const Sequelize = require("sequelize");
const productsModel = require("./products.js");
const db = require("./index.js");
// Получаю с бд все продукты
exports.all = async function getProducts(cb) {
//const products = await db.query('SELECT * FROM products');
const products = await db.findAll({raw: true});
if(products === null) {
return cb(Error, null);
} else {
return cb(null, products);
};
};
// Получаю с бд конкретный продукт
exports.one = async function getOneProduct(id, cb) {
//const getOneQuery = 'SELECT * FROM product where id = $1';
//const getDiscount = 'SELECT * FROM discounts where product_id = $1';
//const curDiscount = await Discount.findOne({where: id});
const product = await db.findAll({where: {id: id}});
const productDiscount = await Discount.findAll({where: {product_id: id}});
const priceWithDiscount = product.price - (product.price * ((productDiscount.discount)/100));
if (product === null) {
return cb(Error, null);
} else if(productDiscount === null) {
return cb(null, product)
} else {
product.price = priceWithDiscount;
const result = product;
return cb(null, result);
};
};
// Создаю в бд продукт
exports.create = async function createProduct(product, cb) {
// const createQuery = 'INSERT INTO product (product_name, price, product_description) values ($1, $2, $3) RETURNING *';
// const arrayQuery = [product.product_name, product.price, product.product_description];
// const newProduct = await db.query(createQuery, arrayQuery);
const newProduct = await db.create(product);
if(newProduct === null) {
return cb(Error, null);
} else {
return cb(null, newProduct);
};
};
// Обновляю в бд конкретный продукт
exports.update = async function updateProduct(id, newData, cb) {
// const updateQuery = 'UPDATE product set product_name = $1, price = $2, product_description = $3 where id = $4 RETURNING *';
// const arrayQuery = [newData.product_name, newData.price, newData.product_description, id];
const product = await db.update(newData, {where: id});
if(product === null) {
return cb(Error, null);
} else {
return cb(null, product);
};
};
// Удаляю в бд конкретный продукт
exports.delete = async function deleteProduct(id, cb) {
//const deleteQuery = 'DELETE FROM product where id = $1';
const product = await db.destroy({where: id});
if(product === null) {
return cb(Error, null);
} else {
return cb(null, product);
};
};
product.js
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class products extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
}
};
products.init({
product_name: DataTypes.STRING,
price: DataTypes.NUMBER,
product_description: DataTypes.STRING
}, {
sequelize,
modelName: 'products',
});
return products;
};
index.js
'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
Also i have migration's and config's files.
What I must to do to issue this errors or another problems?

Move productModels.js to 'repository' directory
because, there is no 'default' export in this file
And, db operation file cannot sit in models folder
I fixed that, and upload to git https://github.com/nkhs/node-sq-stack.git

Related

NodeJs Mongoose - remove one id from array in document

I have an array in my model document. I would like to remove one id in that array. Is this possible?
This is what I tried.
module.exports.RemoveFavourite = async (req, res, next) => {
try {
const userId = req.params.user;
const favouriteId = req.params.event;
const removeFavourite = await User.updateOne(
{ _id: userId },
{ $pull: { favourites: favouriteId } }
);
res.status(200).json(removeFavourite);
} catch {
res.status('404').json('error');
}
};
convert favouriteId string to ObjectId
const mongoose = require("mongoose")
module.exports.RemoveFavourite = async (req, res, next) => {
try {
const userId = req.params.user;
const favouriteId = req.params.event;
const removeFavourite = await User.updateOne(
{ _id: userId },
{ $pull: { favourites: mongoose.Type.ObjectId(favouriteId) } }
);
res.status(200).json(removeFavourite);
} catch {
res.status('404').json('error');
}
};

node.js send notification to specific user in controller

index.js file
var users = [];
let addUser = (userId, socketId) => {
!users.some((user) => user.userId === userId) &&
users.push({ userId, socketId });
};
let removeUser = (socketId) => {
users = users.filter((item) => item.socketId !== socketId);
};
const getUser = (userId) => {
console.log("inside function", users);
return users.find((item) => item.userId === userId);
};
io.on("connection", (socket) => {
socket.on("addUser", async (userId) => {
await addUser(userId, socket.id);
io.emit("getUsers", users);
console.log(users) // print array of users like this
// [{userId:'userId',socketId: 'socket id'}]
});
socket.on("disconnect", () => {
removeUser(socket.id);
io.emit("getUsers", users);
});
});
const socketIoObject = io;
const usersInObject = users;
module.exports.ioObject = { socketIoObject, usersInObject };
controller file
exports.createNotifications = async (req, res) => {
try {
const { userId, title, type = "default", isPublic } = req.body;
if (!title) {
return res.status(401).send("Data is required");
}
const notification = await notificationsModel.create({
userId,
title,
type,
isPublic: userId ? false : true,
});
console.log("socket", socket.ioObject.usersInObject); // return empty
// array [] !!!!
return res.status(200).send("sent");
} catch (err) {
return res.status(400).send(err.message);
}
};
why I can't get the users list in the controller, I got an empty array !!
I need to share the users list in all files to can get the user by function getUser to get the socketId of a specific user to can send a notification to him
Maybe, you import socket in controller file incorrect

How to pass data from Helper Mysql Promises nodejs

i have a problem passing data from folder helper
database.js
const mysql = require('mysql2');
const pool = mysql.createPool({
host: 'localhost',
port:'3306',
user: 'root',
database: '',
password: '',
dateStrings: true
});
module.exports = pool.promise();
helper.js
const Master = require('../models/inspection');
module.exports = {
getLokasi: function (x) {
Master.fetchAll()
.then(([result]) => {
const hasil = result;
return hasil;
})
.catch(err => console.log(err));
}
}
model inspection.js
const db = require('../util/database');
module.exports = class Master {
constructor(si_id) {
this.si_id = si_id;
}
static fetchAll() {
return db.execute('SELECT * FROM mt_analisa_resiko');
}
};
controller
const helpers = require('../../util/helpers');
exports.getInspectionDetail = (req, res, next) => {
const test = helpers.getLokasi();
console.log(test);
}
the problem always return undefined
but when i console.log(hasil) on helper.js it return the data. How do i pass the data from helper so i can used the data on my controller.
You need to return the promise:
module.exports = {
getLokasi: function (x) {
return Master.fetchAll()
.then(([result]) => {
const hasil = result;
return hasil;
})
.catch(err => console.log(err));
}
}
You should be able to access the returned value then:
exports.getInspectionDetail = async (req, res, next) => {
const result = await helpers.getLokasi();
console.log(result);
}

Getting TypeError: FabricUserControllers is not a constructor which can not be catch

I am new to node.js and Javascript.
I have two javascript files "FabricUserController.js" and "UserController.js". So I have create the class in "FabricUserController.js" and export it into "UserController.js".
I am integrate the GetAll fucntion of "FabricUserController.js" to "UserController.js" in GetAllProduce fucntion.
I am trying run the below code however its giving me "TypeError: FabricUserControllers is not a constructor" error which is not handle in try catch{} block
Please see below code
let FabricUserControllers3 = require("./FabricUserController");
GetAllProduce: function (req, res, next) {
try{
let output = {};
var resArray = new Array();
let VZID = req.body.username;
console.log('test', 'GetAllProduce')
console.log('USername', VZID)
MongoClient.connect(config.Database.TEST.connectString, function (err, client) {
if (err) {
let connError = new Error(500, "Error connecting to TEST database", err);
res.status(connError.status).json(connError);
} else {
let query = {};
client.db(config.Database.TEST.dbName).collection("Produce").find(query).toArray(function (err, response) {
console.log(response);
if (err) {
let roleError = new Error(500, "Error getting Produce information", err);
res.status(500).json(roleError);
} else if (response.length > 0) {
//DO someting here
//FabricUserControllers3 = {};
FabricUserControllers3 = new FabricUserControllers();// getting issue here
FabricUserControllers3.GetAll((VZID), (response) => {
console.log("data result", result)
res.status(200).json(response);
client.close();
})
} else {
output.message = "Produce doesn't exist";
res.status(409).json(output);
client.close();
}
});
}
});
}catch(e){
if (e instanceof TypeError){
console.log('error1', e.message);
printError(e,true);
}else{
console.log("error2", e.message);
printError(e, false);
}
}
},
FabricUserController.js
'use strict';
const {
FileSystemWallet,
Gateway
} = require('fabric-network');
const fs = require('fs');
const path = require('path');
var MongoClient = require('mongodb').MongoClient;
var Client = require('node-rest-client').Client;
var client = new Client();
const configPath = path.resolve(__dirname, '..', 'config', 'Config.json');
const configJSON = fs.readFileSync(configPath, 'utf8');
const config1 = JSON.parse(configJSON);
var connection_file = config1.connection_file;
var appAdmin = config1.appAdmin;
var gatewayDiscovery = config1.gatewayDiscovery;
var appAdminSecret = config1.appAdminSecret;
var orgMSPID = config1.orgMSPID;
var caName = config1.caName;
const ccpPath = path.resolve(__dirname, '..', 'config', 'connection.json');
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);
let response = {};
class FabricUserControllers {
constructor() {
console.log("constructer called")
}
async ProduceRegistration(Username, produceid, callback) {
// Create a new file system based wallet for managing identities.
try {
const setAsyncTimeout = (cb, timeout = 0) => new Promise(resolve => {
setTimeout(() => {
cb();
resolve();
}, timeout);
});
let query2 = {}
query2.PRODUCEID = produceid;
// console.log('PRODUCEID',produceid)
var PRODUCE = {};
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
console.log('Username', Username)
// Check to see if we've already enrolled the user.
const userExists = await wallet.exists(Username);
if (!userExists) {
console.log('An identity for the user: ' + Username + ' does not exist in the wallet');
console.log('call the registerUser before retrying');
response.data = null;
response.httpstatus = 400;
response.message = `An identity for the ${Username} does not exist in the wallet`;
return response;
}
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccpPath, {
wallet,
identity: Username,
discovery: {
enabled: false,
asLocalhost: true
}
});
///
MongoClient.connect(config.Database.TEST.connectString, function (err, client) {
if (err) {
// let connError = new Error(500, "Error connecting to TEST database", err);
response.data=null;
response.httpstatus = 500;
response.message = "Error connecting to TEST database :" + err;
// res.status(connError.status).json(connError);
return response;
} else {
client.db(config.Database.TEST.dbName).collection("Produce").find(query2).toArray(function (err, docs) {
if (err) {
response.httpstatus = 500;
response.message = "Error with DB :" + err;
return response;
}
else{
console.log("blockchain_status", docs[0].blockchain_status)
console.log('Role name DB',docs);
console.log('Role name DB1',docs[0]);
if(docs[0].STATUS)
PRODUCE.produceid = docs[0].PRODUCEID;
PRODUCE.produceName = docs[0].PRODUCE;
PRODUCE.farmLocation = docs[0].FARMLOCATION;
PRODUCE.plantingDate = docs[0].PLANTINGDATE;
PRODUCE.harvestDate = docs[0].HARVESTDATE;
PRODUCE.status = docs[0].STATUS;
PRODUCE.produceQuantites = docs[0].VARIETY;
PRODUCE.gapInfo = docs[0].GAP;
PRODUCE.farmerID = docs[0].farmerID;
console.log('Produce', PRODUCE);
const doStuffAsync = async () => {
setAsyncTimeout(async () => {
// Get the network (channel) our contract is deployed to.
const network = await gateway.getNetwork('dfarmchannel');
// Get the contract from the network.
const contract = network.getContract(config1.chaincodeName);
var args = JSON.stringify(PRODUCE)
console.log("type of arg", typeof (args));
// Submit the specified transaction.
// console.log('produceID', args.produceID);
if(args==null || args==''){
console.log('Server not responding please try again');
}else
{
const result = await contract.submitTransaction('ProduceRegistration', args);
var argsJson = JSON.parse(result)
// console.log('result', argsJson)
// console.log('result1', result)
if(argsJson.produceID !="" && argsJson.produceID !=null && argsJson.produceID !="undefined" && argsJson.produceID !=undefined){
// // return false;
response.data = result
response.httpstatus = 200;
response.message = `Transaction has been submitted ansd successfull with Result :${result}`;
return callback(response);
// console.log('result before', response);
// console.log('Transaction has been submitted ansd successfull with Result :' + result);
}else{
console.log('blockchain server not responed')
// return false
response.httpstatus = 500;
response.message = `Please enter produce ID :`;
return response;
}
}
}, 4000);
};
doStuffAsync();
}
client.close();
})
}
})
await gateway.disconnect();
}
catch (error) {
// if(error) throw error;
response.error = error;
response.httpstatus = 500;
response.message = "Failed to enroll admin due to above error";
return response;
}
};
}
module.exports = FabricUserControllers;
#Abhirock, on your main file you have:
let FabricUserControllers3 = require("./FabricUserController");
FabricUserControllers3 = new FabricUserControllers();// getting issue here
You are trying to override FabricUserControllers3 creating a new object FabricUserControllers but you are not importing it. Try next solution to see if it solves your problem:
const FabricUserController = require("./FabricUserController");
const fabricUserControllers3 = new FabricUserController();
Hope it helps :))

KOA2+node+ejs Error: Can't set headers after they are sent

Use kOA2 + node js + ajax to grab the web page data and display the result information on the front page:
query.js
const superagent = require('superagent');
const charset = require('superagent-charset');
const cheerio = require('cheerio');
charset(superagent);
function Rate(from, to, queryNumber) {
this.from = from;
this.to = to;
this.queryNumber = queryNumber;
}
module.exports = Rate;
Rate.query = function query(rate, callback) {
let URL = 'http://qq.ip138.com/hl.asp?from=' + rate.from + '&to=' + rate.to + '&q=' + rate.queryNumber;
superagent.get(URL)
.charset('gbk')
.end((err, sres)=> {
if (err) {
return next(err);
}
var $ = cheerio.load(sres.text);
var queryResult = [];
queryResult[0] = $(".rate td").eq(4).text();
queryResult[1] = $(".rate td").eq(5).text();
callback(null, queryResult);
})
};
index.js
const index = require('koa-router')();
const Rate = require('../models/query');
index.get('/s*', async (ctx, next) => {
let rate = new Rate(ctx.query.from, ctx.query.to, ctx.query.queryNumber);
await Rate.query(rate, (err, queryResult) => {
if (err) {
return next(err);
} else {
return ctx.render('query', {
title: '查询结果',
rate: queryResult[0],
amount: queryResult[1]
});
return next();
}
});
when visit “/s*” page, appear:(Node: 808) UnhandledPromiseRejectionWarning: Unhandled hate rejection (rejection id: 1): Error: Can not set headers after they are sent. Error, and the page can not jump.
Tried a lot of ways, but still do not know where to return in advance.
Is now known, because after the end of ctx, but also to call render to write data. The The But that is not where to change. Pls Help me.
Please update
const index = require('koa-router')();
const Rate = require('../models/query');
index.get('/s*', async (ctx, next) => {
let rate = new Rate(ctx.query.from, ctx.query.to, ctx.query.queryNumber);
await Rate.query(rate, (err, queryResult) => {
if (err) {
return next(err);
} else {
return ctx.render('query', {
title: '查询结果',
rate: queryResult[0],
amount: queryResult[1]
});
return next();
}
});
to
const index = require('koa-router')();
const Rate = require('../models/query');
index.get('/s*', async (ctx, next) => {
let rate = new Rate(ctx.query.from, ctx.query.to, ctx.query.queryNumber);
await Rate.query(rate, (err, queryResult) => {
if (err) {
return next(err);
} else {
return ctx.render('query', {
title: '查询结果',
rate: queryResult[0],
amount: queryResult[1]
});
}
});

Categories

Resources