so i wrote this function to check weather the login given exists already in the odoo database, but it always returns undefined, my guess is that it returns undefined because the return line is inside the calling method,
i tried to use it as an async function but it didn't work either, i need to know how can i make the return line refrences to the global function scope and not just the calling method.(i need the calling method to get the full list of users from the odoo database). Any suggestions ??
`
function user_exist(email){
odoo.connect(function (err) {
if (err) { return console.log(err); }
console.log('Connected to Odoo server.');
var inParams = [];
inParams.push([['active', '=', true]]);
var params = [];
params.push(inParams);
// 4- Read
odoo.execute_kw('res.users', 'search', params, function (err, value) {
if (err) { return console.log(err); }
var inParams = [];
inParams.push(value); //ids
inParams.push(['login']);
var params = [];
params.push(inParams);
odoo.execute_kw('res.users', 'read', params, function (err2, value) {
if (err2) { return console.log(err2); }
for (let i = 0; i < value.length; i++) {
if (email == value[i].login){
return "User exist"
}
}
return "user doesn't exist"
});
});
});
}
`
if you are making your api you need to learn how to use postman, and in this solution we are using axios:
var axios = require('axios');
let data = JSON.stringify({
"jsonrpc": "2.0",
"method":"call",
"params": {
"service":"object",
"method":"execute",
//arg1 : your database name must be "string"
//arg2 : id of the user admin must be "int" ex:1 or 3 or 66
//arg3 : password of the user admin must be "string"
// admin:admin do like this 2:"admin"
//arg4 : object or model name ex:"res.users"
//arg5 : orm methods ex:"search,search_read..."
//"args":["arg1",'arg2',"arg3","arg4","arg5"]}
"args":["app",2,"admin","res.users","search_read",[],[]]
}
});
let config = {
method: 'get',
url: 'http://localhost:8069/jsonrpc',
headers: {'Content-Type': 'application/json'},
data : data
};
axios(config).then(response => {handleResult(response)})
function handleResult(data) {
// if you want you can remove result
console.log(JSON.stringify(data.data.result));
}
i hope this will be help you
Related
I have a NODE.JS api using expressjs that connects to an SQL Server, and I want to use it in an angular project. I make use two files, a route file and a controllers file. My route file is as follows:
module.exports = (app) => {
const UsrContrllr = require('../Controllers/users.controllers');
//1. GET ALL USERS
app.get('/api/users', UsrContrllr.func1);
//2. POST NEW USER
app.post('/api/user/new', UsrContrllr.func2);
};
And my controllers file is given below:
const mssql = require('mssql');
exports.func1 = (req, res) =>
{
// Validate request
console.log(`Fetching RESPONSE`);
// create Request object
var request = new mssql.Request();
// query to the database and get the records
const queryStr = `SELECT * FROM USERS`;
request.query(queryStr, function (err, recordset) {
if (err) console.log(err)
else {
if (recordset.recordset.toString() === '') {
res.send('Oops!!! Required data not found...');
}
else {
// send records as a response
res.send(recordset);
}
};
});
};
exports.func2 = (req, res) =>
{
// Validate request
console.log(`INSERTING RECORD ${req}`);
// create Request object
var request = new mssql.Request();
// query to the database and get the records
const queryStr = `INSERT INTO GDUSERS (USERCODE, PASSWORD, LANGUAGE, USERCLASS, FIRSTNAME, LASTNAME, CONTACTNO) VALUES ('${req.body.usercode}', '${req.body.password}', 'EN', '0', '${req.body.firstname}', '${req.body.lastname}', '${req.body.contactno}');`;
request.query(queryStr, function (err, recordset) {
if (err) console.log(err)
else {
if (recordset.recordset.toString() == '') {
res.send('Oops!!! Required data not found...');
}
else {
// Send records as response
res.send(recordset);
}
};
});
};
The GET request works well, but when I try to run the POST request directly from the angular application, I get an error stating
Cannot GET URL/api/user/new
The angular code in my angular project is:
signup() {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
console.log(this.user); //User details come from a form
this.http.post(“URL", this.user, options)
.subscribe(
(err) => {
if(err) console.log(err);
console.log("Success");
});
}
I’m not sure whether the angular code I’m using, is right or not, and I don’t know where I’m going wrong. How does one exactly send a http POST request from an Angular project?
this i the way i handled my user signup with http.post calls. my approach is slightly different when signing up user because i am using a promise instead of observable (which i normally use for my servicecalls). but i will show you both ways.
createUser(user: User): Promise < string > {
const promise = new Promise < string > ((resolve, reject) => {
const userForPost = this.createUserForPost(user);
this.http.post(environment.backendUrl + '/api/user/signup', userForPost, this.config).toPromise < HttpConfig > ()
.then(createdUser => {
}).catch(error => {
console.log(error);
});
});
return promise;
}
here another example with an observable
createForumPost(forumPost: ForumPost) {
this.http.post < { message: string, forumPostId: string } > (environment.backendUrl + '/api/forumPosts', forumPost).subscribe((responseData) => {
const id = responseData.forumPostId;
forumPost.id = id;
});
}
i defined my URL somewhere else and then just use the environment.backedUrl + 'path' to define my path (the same as the path in your backend controller)
this is one of my first answers here on SO. i am sry if it is a bit messy
i hope i was able to help with my examples :)
community. I am trying to implement a live search using the autocomplete library but every try is unsuccessful. I get every time a 500 server error. Every assistant is appreciated because I am new in coding.
I have a simple model for an article with title and body and I would like to show suggestions when the user search for an article
model/article.js
// Method to construct the json result set
module.exports.buildResultSet=function(docs) {
var result = [];
for(var object in docs){
result.push(docs[object]);
}
return result;
}
routes/article.js
router.get('/search', function(req, res){
encyclopediaModel.getMyArticlesByName(theRequester, function (pError, pFoundedArticles) {
if (!pError) {
// Method to construct the json result set
var result = encyclopediaModel.buildResultSet(pFoundedArticles);
res.json(result);
} else {
return res.json(JSON.stringify(pError), {
'Content-Type': 'application/json'
}, 404);
}
},req.query.title)
});
//Ajax call
$("#search-query").autocomplete({
source: function (request, response) {
$.ajax({
url: "/encyclopedia/search",
type: "GET",
data: request, // request is the value of search input
success: function (data) {
response( data );
console.log('success', data);
}
});
},
// The minimum number of characters a user must type before a search is performed.
minLength: 3,
// set an onFocus event to show the result on input field when result is focused
focus: function (event, ui) {
this.value = ui.item.label;
// Prevent other event from not being execute
event.preventDefault();
},
select: function (event, ui) {
}
});
<input id="search-query" type="text" placeholder="Articles...">
module.exports.getMyArticlesByName = function (requester, callback, pTitle){
var regex = new RegExp(pTitle["term"], 'i');
article.find({title: regex}, { 'title': 1 }).sort({"updated_at":-1}).sort({"created_at":-1}).limit(20).exec(callback);
}
I'm developing a simple app with Node/Hapi/Mongodb, but running into a strange issue. Below is the route that handles adding/updating scores; when I send some data to this endpoint through Insomnia/Postman it works as expected. However, when this POST is coming from a different app I'm getting strange results; the value is always null for every field (again this only happens when the POST is coming from another site, but I've logged out the request payload and can see that the data is correct, just gets set to null when assigning to an object, or trying to use it a query)
server.route({
method: 'POST',
path: '/update-score',
handler: (request, h) => {
var scores = db.collection('scores');
var updateScore = new Promise((resp, rej) => {
console.log('payload ', request.payload);
scores.findOneAndUpdate({customerID: request.payload.customerID}, {$set: {customerID: request.payload.customerID, customerName: request.payload.customerName, highScore: request.payload.highScore}}, {upsert: true}, (err, res) => {
if (err) {
return rej(err);
}
else {
return resp(res);
}
})
});
return updateScore;
}
});
The console logs out the request payload correctly, but its null/undefined when the query tries to use it. I have also tried creating two objects, outside the mongo method call (like below), and after console logging these pre-defined objects out the value was null there as well; even though I can console.log the request.payload after defining these objects and the data is good.
server.route({
method: 'POST',
path: '/update-score',
handler: (request, h) => {
var scores = db.collection('scores');
var queryObj = {
customerID: request.payload.customerID
};
var updateObj = {
$set: {
customerName: request.payload.customerName,
highScore: request.payload.highScore
}
}
var updateScore = new Promise((resp, rej) => {
console.log('again ', request.payload);
scores.findOneAndUpdate(queryObj, updateObj, {upsert: true}, (err, res) => {
if (err) {
return rej(err);
}
else {
return resp(res);
}
})
});
return updateScore;
}
});
Logging the queryObj and valueObj would show the values are all null, even though I can log the request.payload and see the data correctly. Why can't I use the request.payload values anywhere?
Long story short, Insomnia/Postman sends an object as the POST body, but I was JSON encoding the POST from the app; just needed to parse that on the server!
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'm implementing a simple local auth with express and mongoDB(using mongoose) and for some reason the server sends back an empty response object for user, but the token gets sent in the response. I included a console.log statement immediately before the return to try and debug it a little bit, and the object logged there is the correct one with all of the data. This is what the create code looks like
import mongoose from 'mongoose';
import jwt from 'jsonwebtoken';
import json from '../helpers/json';
var User = mongoose.model('User');
module.exports = function() {
var obj = {};
obj.create = function (req, res) {
var roles = ['authenticated'];
User.count({}, (err, len) => {
if (!len) {
roles.push('admin');
}
var user = new User(req.body);
user.roles = roles;
user.provider = 'local';
user.token = jwt.sign(user, global.config.secret, {expiresIn: 10800});
user.save((err, user) => {
if (err) {
return json.bad(err, res);
}
json.good({
record: user,
token: user.token
}, res);
});
});
};
return obj;
};
Like I said, I had included a console.log statement and the user will display properly.
If you are wondering, the json.good is a helper function that I wrote that basically looks like this
module.exports = {
good: function (obj, res) {
res.send({
success: 1,
res: obj
});
},
bad: function (err, res) {
var obj = {
success: 0,
res: err
};
if (obj.res.errors) {
obj.res.messages = [];
for (var i in obj.res.errors) {
obj.res.messages.push(obj.res.errors[i].message;
}
obj.res.messages = obj.res.messages[0];
}
res.send(obj);
}
};
I am also allowing the correct headers and methods in my express file. This code is identical to code that I have used before, but I am missing something it seems.
Any help would be appreciated, thank you!
!!!!!!! FIXED FIXED FIXED !!!!
I figured out the problem, it was in my model. I had
UserSchema.methods = {
toJSON: function() {
var obj = this.toObject();
delete obj.password;
delete obj.following;
}
};
I had forgotten to return the obj at the end. Thanks everyone!
Make sure that the Value Type in MongoDB matches the Variable type...
So if you have a Key named 'fav' that is an Int32, Then make sure that the variable you use to find it is an Int32.
I am using Apigee BaaS. From the UI i.e., apigee.com/appservices, I can create multiple entities at the same time using a JSON array. For example the json array here creates three entities on collection /employees.
[
{
"name": "John",
"employeeId": "1"
},
{
"name": "Doe",
"employeeId": "2"
},
{
"name": "Danny",
"employeeId": "3"
}
]
Now I am trying to emulate the same with the nodeJs SDK - https://github.com/usergrid/usergrid/tree/master/sdks/nodejs
client.createEntity(options, function(err, entity) {
if (err) {
//error - entity not created
} else {
//set is additive, so previously set properties are not overwritten
entity.set(entityJsonArr);
//finally, call save on the object to save it back to the database
entity.save(function(err) {
if (err) {
//error - entity not saved
console.log('failure');
} else {
//success - new entity is saved
console.log('success');
}
});
}
});
This doesnt help in creating multiple entities at the same time. Method createCollection creates a collection and not necessarily bunch of entities. Can anyone please help me with this?
Or should I just go ahead use request and fire a HTTP post on the Apigee BaaS? In that case I wouldnt be using the sdk.
You're correct, the existing Node SDK doesn't handle this case. In case you want and it's useful to you, I used the following monkey patch to work around this for now:
var Usergrid = require('usergrid');
Usergrid.client.prototype.batchCreate = function (type, entities, callback) {
if (!entities.length) { callback(); }
var data = _.map(entities, function(entity) {
var data = (entity instanceof Usergrid.entity) ? entity.get() : entity;
return _.omit(data, 'metadata', 'created', 'modified', 'type', 'activated');
});
var options = {
method: 'POST',
endpoint: type,
body: data
};
var self = this;
this.request(options, function (err, data) {
if (err && self.logging) {
console.log('could not save entities');
if (typeof(callback) === 'function') { callback(err, data); }
return;
}
var entities = _.map(data.entities, function(data) {
var options = {
type: type,
client: self,
uuid: data.uuid,
data: data || {}
};
var entity = new Usergrid.entity(options);
entity._json = JSON.stringify(options.data, null, 2);
return entity;
});
if (typeof(callback) === 'function') {
return callback(err, entities);
}
});
};