Import sequelize model in vuejs - vue.js

I'm building a CRUD app using electron + vuejs + sequelize, i have used sequelize init and configured the .sequelizerc as below
const path = require('path');
module.exports = {
'config': path.resolve('src/renderer/database/config', 'config.json'),
'models-path': path.resolve('src/renderer/database', 'models'),
'seeders-path': path.resolve('src/renderer/database', 'seeders'),
'migrations-path': path.resolve('src/renderer/database', 'migrations')
}
Now i'm trying to populate a table with data from the database, I've tried to import the models in many ways, always leading to errors.
Error: Uncaught TypeError: Path must be a string. Received undefined
Component:
var models = require('./../../database/models'); // LINE WITH ERROR
export default {
name: "user-index",
data: function() {
return {
users: []
};
},
created: function() {
models.Users.findAll().then(users => {
//
});
},
components: {},
methods: {}
};
Thanks.
EDIT:
I found the problem, it is in the models/index.js:
'use strict';
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(__filename);
var env = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/../config/config.json')[env];
var db = {};
if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
var 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 => {
var model = sequelize['import'](path.join(__dirname, file)); // THIS LINE
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;

I fixed by changing path.join to path.resolve and changing this:
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
to
for (var modelName in db) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
}
in models/index.js file.

Related

using Multer to add array

I am using multer to add an array of images to my product document, I am getting the right name into the uploads folder, but undefind as a name in postman.
This is the code I tried:
router.put(
"/gallery-images/:id",
uploadOptions.array("images", 10),
async (req, res) => {
if (!mongoose.isValidObjectId(req.params.id)) {
res.status(400).send("Invalid product ID");
} //product ID validation
const files = req.files;
let imagesPaths = [];
const basePath = `${req.protocol}://${req.get("host")}/public/upload/`;
if (files) {
files.map((file) => {
imagesPaths.push(`${basePath}${file.fileName}`);
console.log("uhu", file);
});
}
let product = await Product.findByIdAndUpdate(
req.params.id,
{
images: imagesPaths,
},
{ new: true }
);
if (!product) return res.status(500).send("The product cannot be updated");
res.send(product);
}
);
It worked with this change:
const basePath = `${req.protocol}://${req.get("host")}/public/upload/`;
if (files) {
// files.map((file) => {
// imagesPaths.push(`${basePath}${file.fileName}`);
// });
imagesPaths = files.map((file) => {
const fileName = file.filename;
return `${basePath}${fileName}`;
});
}

Jest global variables with require modules

I'm working on some test for a very small vanilla js library, so I have this module
var otherModule = require('../module/mymodule');
var postscribe = require('postscribe');
var exports = module.exports = {};
var API_URL = URL;
exports.myFunction = function (arg1, arg2, arg3) {
if (arg1 && arg2) {
var myUrl = getApiUrl(arg1, arg2, arg3);
callSomeURL(myUrl);
}
}
function getApiUrl(arg1, arg2, arg3) {
var param1 = otherModule.getParams(arg1);
var param2 = otherModule.getOtherParams(arg1);
return `${API_URL}/v1/pixels/${arg1}/${arg2}${param1}${param2}`;
}
...
then I have otherModule module with my functions
var GLOBAL_VALUE = MY_VALUE;
var otherModule = {};
otherModule.getParams = function (arg1) {
return arg1 ? `&value=${arg1}` : '';
}
otherModule.getOtherParams = function (arg1) {
return GLOBAL_VALUE + arg1
}
module.exports = otherModule;
And my webpack configs
const { DefinePlugin } = require('webpack');
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
const devConfig = require('./src/config/dev');
module.exports = () => {
var envConfig = devConfig;
return merge(common, {
mode: 'development',
devtool: 'inline-source-map',
plugins: [
new DefinePlugin({
__DEV__: true,
URL: JSON.stringify(envConfig.URL),
MY_VALUE: JSON.stringify(envConfig.VALUE)
})
]
})
}
my common is:
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
entry: './src/index.js',
plugins: [
new CleanWebpackPlugin()
],
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
};
And my jest.config
const config = require('./src/config/dev');
module.exports = {
globals: {
"MY_VALUE": config.VALUE,
"URL" : config.URL
}
}
my problem appears when I try to test exports.myFunction via rewire to have access to private function getApiUrl it seems that I can't access to the imported global values, like GLOBAL_VALUE
in my myOther, I keep getting ReferenceError: GLOBAL_VALUE is not defined, but when I test myOther module directly everything seems to work, can someone throw some light or resources on what I'm doing wrong?

GraphQl , Sequelize-CLi, models bundler - sequelize.import is not a function

I'm following tutorial about sequelize-cli: https://andela.com/insights/using-graphql-and-sequelize/
And I'm getting an err: 'sequelize.import is not a function'
it's coming from models/index.js (which should bundle all models)
'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 = {};
// Set DB Connection
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);
}
// Import model files in models folder and make table associations where present
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
I was searching solution online but whatever I saw it didnt work.
Any ideas??
OK solved!
I havent realized that
.forEach(file => {
const model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
was in the same location so the correct answer was:
.forEach(file => {
db[model.name] = file
});

sequelize raw query in express app

I'm trying to call a simple sequelize raw query to get all the users in the users table but I am getting the error.
Cannot read property 'query' of undefined
what am I doing wrong here?
models/index.js
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(module.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]);
} else {
sequelize = new Sequelize(
config.database, config.username, config.password, config
);
}
fs
.readdirSync(__dirname)
.filter(file =>
(file.indexOf('.') !== 0) &&
(file !== basename) &&
(file.slice(-3) === '.js'))
.forEach(file => {
const model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
module.exports = db;
controllers/users
const db = require('../models/index').db;
module.exports = {
getAllUsers(req, res){
db.query('SELECT * FROM "Users" As Users', { type: sequelize.QueryTypes.SELECT})
.then(result => {
return res.status(201).send({
result
});
})
}
};
Had to change
const db = require('../models/index').db;
to
const db = require('../models/index');
and add const sequelize = require('sequelize');

TypeError: instance.web.core is undefined

I can not add new action in Odoo9
openerp.pr_finance = function(instance, local) {
var _t = instance.web._t, _lt = instance.web._lt;
var QWeb = instance.web.qweb;
var Widget = instance.web.Widget;
var core = instance.web.core;
var data = instance.web.data;
var session = instance.web.session;
var utils = instance.web.utils;
var Model = instance.web.Model;
var ControlPanelMixin = instance.web.ControlPanelMixin;
instance.web.ListView.include({
init: function() {
//console.log('JS loaded');
this._super.apply(this, arguments);
},
render_buttons: function(data) {
console.log('JS loaded load_list');
console.log(data);
this._super(data);
if (this.$buttons) {
this.$buttons.find('.oe_my_button').click(this.proxy('do_import_file_csv_ya_tz')) ;
}
},
do_import_file_csv_ya_tz: function () {
console.log('123123123123123123 ooops....');
this.do_action(
{
name: _t("IMPORT MY FILE"),
type: "ir.actions.client",
tag: 'import_csv',
params: {}
}
);
}
});
var import_csv_yandex = Widget.extend({
template: 'ImportViewYaTC',
start: function () {
console.log("ImportViewYandexTC page loaded");
},
});
var DataImport = Widget.extend(ControlPanelMixin, {
template: 'ImportView',
init: function(parent, action) {
console.log("init ImportView");
this._super.apply(this, arguments);
action.display_name = _t('Import a File');
},
start: function () {
console.log("ImportView page loaded");
},
});
console.log("core.action_registry.add");
try {
instance.web.core.action_registry.add('import_csv', DataImport);
} catch (err) {
console.log(err);
}
console.log("core.action_registry.add - OK!");
}
I received error here:
instance.web.core.action_registry.add('import_csv', DataImport);
Error:
TypeError: instance.web.core is undefined Stack trace:
openerp.pr_finance#http//localhost:8069/web/content/2798-e13ba1c/web.assets_backend.js:4579:1276
start_modules#http//localhost:8069/web/content/2798-e13ba1c/web.assets_backend.js:3235:1
.init#http//localhost:8069/web/content/2798-e13ba1c/web.assets_backend.js:3229:3951
OdooClass.extend/Class.include/
Why this variable is undefined?
You need to use require to get the variables of the env: ie.
odoo.define('yourmodulename.pr_finance', function (require) {
"use strict";
var core = require('web.core');
});
a good place to look at to understand inheritance in odoo is the github.com/oca/web repo.