Hi I am working with GraphQl with the combination of es6.
While removing a particular record from graphql, I am getting details(values) of the deleted record, I want to print some custom message like "Record deleted". Please help me accordingly.
Here is my graphQL code:
removeUser:{
type: UserType,
args: {
_id: {
description: 'The _id of the user',
type: GraphQLString,
},
},
resolve: (obj, {_id}) =>{
return new Promise((resolve, reject) => {
User.findOne({_id:_id},(err,res)=> {
if(err || res == null) {
reject('User was not found')
}
else {
User.remove({_id: _id},(err,result)=>{
err ? reject(err) : reject('User removed successfully')
});
}
})
})
}
}
You declare UserType as the type of the removeUser field. Obviously, the string 'User removed successfully' is not a UserType; it's a String type.
Also, if the delete operation is successful, you should call resolve in the Promise, not reject.
I think something like this should work:
removeUser:{
type: GraphQLString,
args: {
_id: {
description: 'The _id of the user',
type: GraphQLString,
},
},
resolve: (obj, {_id}) =>{
return new Promise((resolve, reject) => {
User.findOne({_id:_id},(err,res)=> {
if(err || res == null) {
reject('User was not found')
}
else {
User.remove({_id: _id},(err,result)=>{
err ? reject(err) : resolve('User removed successfully')
});
}
})
})
}
}
Related
I'm using mongoose and I would like that when I get all users send me uid instead of _id.
const allUssers = (req, res, next) => {
try {
User.find({})
.select("username")
.select("email")
.select("image")
.exec((err, users) => {
if (err) {
return res.status(400).json({
ok: false,
msg: "Error listing users",
});
}
return res.status(200).json({
ok: true,
users: users,
});
});
} catch (err) {
return res.status(500).json({
ok: false,
msg: "Please contact with administrator",
});
}
};
You can update your schema to use an alias:
let User = new Schema({
_id: { type: String, alias: "uid" }
});
Or you can map your users to something different:
return res.status(200).json({
ok: true,
users: users.map(({ _id, ...user }) => ({ uid: _id, ...user }),
});
I am facing one issue with Mongoose. When I use find or findOne method and there is no matching results, then callback function is not returning null / err and hung the process. Using Mongoss 5.1.5 , MongoDB V3.4.2. Please advise
module.exports.validateappsubscripition = function (userid, appkey, cb) {
//console.error(userid + ' ' + appkey)
var userobj_id = mongoose.Types.ObjectId(userid);
appsubscripitions.model.findOne({'subscribersuserid': userobj_id , 'appkey'
:appkey }, function(err,doc){
console.error('test2');
if(doc ){
cb(null, doc );
}
else{
cb(null, null );
}
} );
}
Calling Block : Trying to validate the key from req header. I am trying to call the function validateappsubscripition from below block.
module.exports.sendEmail = function (req, res, next) {
let appkey;
let userid;
if (req.headers.appkey) {
appkey = req.headers.appkey;
console.error(appkey);
}
else {
appkey = '';
}
if(req.user._id){
userid = req.user._id ;
console.error(userid);
}
if (!req.body.fromEmail || !req.body.toEmail || !req.body.subject || !req.body.content) {
res.json({ success: false, msg: 'Please pass all the required parameters' });
next();
}
appsubcripitions.validateappsubscripition(userid, appkey, function (err, doc) {
console.error('test2');
if (err) {
res.json({ success: false, msg: 'Unauthorized. App Key is misssing on the header or App key is not valid' });
next();
}
else if (doc ) {
this.getSMTP('smtp.gmail.com', 'arbalu#gmail.com', function (err, userInfo) {
if (err) {
res.json({ success: false, msg: err.message });
next();
}
if (userInfo) {
//userInfo = user;
var send = require('gmail-send')({
user: userInfo.user,
pass: userInfo.pass,
from: req.body.fromEmail,
to: req.body.toEmail,
subject: req.body.subject, // Override value set as default
text: req.body.content
});
send({ // Overriding default parameters
// to: req.toEmail,
// subject: req.subject, // Override value set as default
// text: req.content
// files: [filepath],
}, function (err, response) {
//console.log('* [example 1.1] send() callback returned: err:', err, '; res:', res);
if (err) {
res.json({ success: false, msg: err.message });
next();
}
else {
res.json({ success: true, msg: response });
next();
}
});
}
})
}
else {
res.json({ success: false, msg: 'Some issue on sending email.Please contact the support.' });
next();
}
});
}
I'm trying to build a simple server in SailsJS and encountered a problem: I send a POST request to the service in Sails, and I always get a 200 response, even when there's no matching user in the on-disk DB.
My model:
module.exports = {
attributes: {
name: { type: "string" },
lastName: { type: "string" }
}
};
My routes file:
module.exports.routes = {
'post /authTest' : 'UserController.testingAuth'
};
My controller:
module.exports = {
testingAuth : function(req, res) {
var temp = req.param("name");
sails.log(temp);
User.find({ name: 'testing123' }).exec(function(err, user) {
if (err) {
sails.log("inside err block");
return res.serverError(err);
}
sails.log("skipped err block");
return res.json(user);
})
}
};
The way I call the service:
var testUser = { name: 'notMyName', lastName: 'myLastName' };
$http.post("http://localhost:1337/authTest", testUser);
Then on the SailsJS console I see:
debug: notMyName
debug: skipped err block
My local DB has just the following though (localDiskDb.db in .tmp):
{
"data": {
"passport": [],
"user": [
{
"name": "myName",
"lastName": "myLastName",
"createdAt": "2017-11-18T17:26:13.609Z",
"updatedAt": "2017-11-18T17:26:13.609Z",
"id": 1
}
]
},
// some schema stuff, irrelevant here
}
Can someone see anything wrong here? The service receives the posted request object fine, searches for a user that is not in the DB, but finds one anyway?
Check this out:
User.find({ name: 'testing123' }).exec(function(err, user) {
if (err) {
sails.log("inside err block");
return res.serverError(err);
}
sails.log("skipped err block");
return res.json(user);
})
to
User.findOne({ name: 'testing123' }).exec(function(err, user) {
if (err) {
sails.log("inside err block");
return res.serverError(err);
} else if(user){
// user found here
return res.json(user);
} else {
//no user found
return res.json(null);
}
})
If you want to stick with find():
User.find({ name: 'testing123' }).exec(function(err, users) {
if (err) {
sails.log("inside err block");
return res.serverError(err);
} else if(users.length == 0) {
//users is empty array of results
return res.json(users)
} else {
//users is array of N records with criteria 'testing123' in field 'name'
return res.json(users);
}
})
i am trying to make a game. I need tu create a Match. I think the problem on this Way. The User create a Match. In a third table I save playerId and gameId. When another user join the match, I save again, playerId and gameId. Then, I make a query with player with gameId in common, and start the game.
first, One User may have many Games. second, One Match may have many Games. this is the Match model:
module.exports = {
attributes: {
name: {
type: 'string'
},
description: {
type: 'string'
},
game: {
collection: 'game',
via: 'gameId',
}
}
};
This is the User model:
var bcrypt = require('bcrypt');
module.exports = {
attributes: {
name: {
type:'string'
},
email: {
type: 'email',
required: true,
unique: true
},
password: {
type: 'string',
},
passwordConfirmation: {
type: 'string'
},
passwordEncrypted: {
type: 'string'
},
creator: {
collection: 'game',
via: 'playerId'
},
toJSON: function(){
var obj = this.toObject();
delete obj.password;
delete obj.passwordConfirmation;
delete obj._csrf;
return obj;
}
}, beforeCreate: function(values, next){
console.log("Acabo de entrar a eforeCreate");
var password = values.password;
var passwordConfirmation = values.passwordConfirmation;
if(!password || !passwordConfirmation || password != values.passwordConfirmation) {
var passwordDoesNotMatchError = [{
name: 'passwordDoesNotMatchError',
message: 'Las contraseñas deben coincidir'
}]
return next({
err: passwordDoesNotMatchError
});
}
require('bcrypt').hash(values.password, 10, function passwordEncrypted(err, EncryptedPassword){
values.EncryptedPassword = EncryptedPassword;
next();
});
}
};
This is the Game model:
module.exports = {
attributes: {
gameId: {
model: 'match'
},
playerId: {
model: 'user'
}
}
};
finally, this is my controller:
module.exports = {
createMatch: function(req,res){
var matchObj = {
name: req.param('name'),
description: req.param('description'),
}
Match.create(matchObj, function(err, match){
if(err){
console.log("el error fue: " + err);
return res.send(err);
} console.log("Entro en create");
return res.json(match);
})
var gameObj = {
gameId: 'aclaration: I dont know how do I get the match.id',
playerId: req.session.me
}
Game.create(gameObj,function(err,game){
console.log("entro a GameCreate");
if(err){
return res.send(err);
} return res.json(game);
})
}
};
I can create the Match, but Game.create send this error:
_http_outgoing.js:344 throw new Error('Can\'t set headers after they are sent.'); ^
Error: Can't set headers after they are sent.
Somebody can help me? probably, I have many errors. Thanks.
Couple of things here:
Having an explicit Game model is not required in Sails. It can manage it implicitly, unless you want to store more information than just gameId and userId. So, you can just do away with Game model.
Please refer for async programming: How do I return the response from an asynchronous call?
Below code should work for you. Hope it helps.
module.exports = {
createMatch: function(req, res) {
var matchObj = {
name: req.param('name'),
description: req.param('description'),
};
Match.create(matchObj, function(err, match) {
if (err) {
console.log("el error fue: " + err);
return res.send(err);
}
console.log("Entro en create");
var gameObj = {
gameId: match.id,
playerId: req.session.me
};
Game.create(gameObj, function(err, game) {
console.log("entro a GameCreate");
if (err) {
return res.send(err);
}
return res.json(game);
// return res.json(match);
});
});
}
};
I have a schema like this
{
'cr':[
{ key: 'key1' },
{ key: 'key2' }
]
}
function addCriteriaKey(id, key, callback) {
var options = {new: false, select: '_id'};
if (typeof key === 'string') {
Model.update({'uid': id}, {'$addToSet': {'cr': {'key': key}}}, options, function (err, data) {
if (err) callback(err, null);
else callback(null, data);
})
} else if (typeof key == 'object' && (key instanceof Array)) {
Model.update({'uid': id}, {'$addToSet': {'cr': {'key': {'$each': key}}}}, options, function (err, data) {
if (err) callback(err, null);
else callback(null, data);
})
}
}
what this method does is to add key into the 'cr' filed, if the key is a string, add it directly, if the key is a array of string, then add them all by suing the '$each' command
Adding a string works pretty well, the problem rises when adding to a array of string, I expect it could add one by one, but the result is different
For example:
addCriteriaKey('id',['111','222','333'],function(err,data){})
My expected result :
{
'cr':[
{ key: '111' }, { key: '222' }, { key: '333' }
]
}
However the result is :
{
'cr':[
{ key: {'$each':{'111','222','333'}} }
]
}
I wondered what is the problem for this?
either we can do in this way,
Model.addNotiCriteriaKey( 5, [{'key':'111'},{'key':'222'},{'key':'333'}], function(err,data){})
or using underscore to sort out array into key-value arrays
Model.addNotiCriteriaKey( 5, ['111','222','333'], function(err,data){})
function(id,key,callback){
_.map(key, function(element){ return {'key':element}; });
UserModel.update({'uid':id},{'$pull':{'cr':{ '$each': key}}},options,function(err,data){
if(err) callback(err,null);
else callback(null,data);
})
}