GraphQL, Mysql equivalent OR operation - javascript

I have just learnt GraphQL and I want to find the user id=2 OR user id=3 now how will I make the GraphQL query,I am getting the whole set using the bellow query
{
users() {
id
username
posts {
title
tags {
name
}
}
}
}
2nd issue --
{
people(id:[1,2,3]) {
id
username
posts(id:2) {
title
tags {
name
}
}
}
}
if I add the arg on Posts filed then i got an error msg "Unknown argument id on field posts of type user"
This is my Schema js file
var graphql = require('graphql');
var Db = require('./db');
var users = new graphql.GraphQLObjectType({
name : 'user',
description : 'this is user info',
fields : function(){
return {
id :{
type : graphql.GraphQLInt,
resolve(user){
return user.id;
}
},
username :{
type : graphql.GraphQLString,
resolve(user){
return user.username;
}
},
posts:{
id:{
type : graphql.GraphQLString,
resolve(post){
return post.id;
}
},
type: new graphql.GraphQLList(posts),
resolve(user){
return user.getPosts();
}
}
}
}
});
var posts = new graphql.GraphQLObjectType({
name : 'Posts',
description : 'this is post info',
fields : function(){
return {
id :{
type : graphql.GraphQLInt,
resolve(post){
return post.id;
}
},
title :{
type : graphql.GraphQLString,
resolve(post){
return post.title;
}
},
content:{
type : graphql.GraphQLString,
resolve(post){
return post.content;
}
},
person :{
type: users,
resolve(post){
return post.getUser();
}
},
tags :{
type: new graphql.GraphQLList(tags),
resolve(post){
return post.getTags();
}
}
}
}
});
var tags = new graphql.GraphQLObjectType({
name : 'Tags',
description : 'this is Tags info',
fields : function(){
return {
id :{
type : graphql.GraphQLInt,
resolve(tag){
return tag.id;
}
},
name:{
type : graphql.GraphQLString,
resolve(tag){
return tag.name;
}
},
posts :{
type: new graphql.GraphQLList(posts),
resolve(tag){
return tag.getPosts();
}
}
}
}
});
var query = new graphql.GraphQLObjectType({
name : 'query',
description : 'Root query',
fields : function(){
return {
people :{
type : new graphql.GraphQLList(users),
args :{
id:{type: new graphql.GraphQLList(graphql.GraphQLInt)},
username:{
type: graphql.GraphQLString
}
},
resolve(root,args){
return Db.models.user.findAll({where:args});
}
},
posts:{
type : new graphql.GraphQLList(posts),
args :{
id:{
type: graphql.GraphQLInt
},
title:{
type: graphql.GraphQLString
},
},
resolve(root,args){
return Db.models.post.findAll({where:args});
}
},
tags :{
type : new graphql.GraphQLList(tags),
args :{
id:{
type: graphql.GraphQLInt
},
name:{
type: graphql.GraphQLString
},
},
resolve(root,args){
return Db.models.tag.findAll({where:args});
}
}
}
}
});
var Mutation = new graphql.GraphQLObjectType({
name : "mutation",
description : 'function for mutaion',
fields : function(){
return {
addPerson : {
type : users,
args :{
username : {
type : new graphql.GraphQLNonNull(graphql.GraphQLString)
},
email :{
type : new graphql.GraphQLNonNull(graphql.GraphQLString)
}
},
resolve(_, args){
return Db.models.user.create({
username : args.username,
email : args.email
});
}
}
}
}
})
var Schama = new graphql.GraphQLSchema({
query : query,
mutation : Mutation
})
module.exports = Schama;

In order to fetch multiple data from your schema using an array of ids you should define the args given to the users in your schema as follows:
fields: () => ({
users: {
type: new GraphQLList(USER_GRAPHQL_OBJECT_TYPE),
args: {
id: {type: new GraphQLList(GraphQLInt)}
},
resolve: (root, args) => {
// fetch users
}
}
})
notice the new GraphQLList wrapping the GraphQLInt type of the id.
Then, when querying your schema you can :
{
users(id: [2, 3]) {
id
username
posts {
title
tags {
name
}
}
}
}
Please let me know if it was helpful :)

Related

Sequelize ORM - Error: not returning database values

I'm try to return a password from database to another javascript file. The function will retrieve the data correctly. But when I return the value to another function, it will be changed to undefined. I want to return a password from model.js to controller.js.
code :
model.js
const Sequelize = require('sequelize'); //import sequelize orm
// connect with psql db
var connection = new Sequelize('emd','postgres','test',{
dialect : 'postgres'
});
//create a table;
var student = connection.define('student',{
name : {
type : Sequelize.STRING,
allowNull : false},
email : {
type: Sequelize.STRING,
unique : true,
allowNull : false},
password : {
type : Sequelize.STRING,
allowNull : false },
mobile : {
type: Sequelize.BIGINT(11),
unique : true,
allowNull : false }
});
var methods = {};
methods.signup = function(u_name,u_email,u_password,u_mobile){
connection.sync().then(function(){
student.create({
name : u_name,
email : u_email,
password : u_email,
mobile : u_mobile
});
});
}
methods.login = function(email_id){
connection.sync().then(function(){
student.findOne({where : {email : email_id }} ).then(results =>{
return results.dataValues.password;
});
});
}
exports.fun = methods;
code: Controller.js
var model = require('./model.js')
var methods={}
methods.login = function(email,password){
let res = model.fun.login(email)
console.log(res);
if(password===res){
console.log("success");
}
else {
console.log("failure");
}
}
exports.cont = methods
To add on to #Sagar Jojoriya,
Change your model.js like this
methods.login = function(email_id, callbackFun){
connection.sync().then(function(){
student.findOne({where : {email : email_id }} ).then(results =>{
console.log("debug pass => ", results.dataValues.password);
callbackFun(results.dataValues.password);
});
});
}
And in your controller.js
methods.login = function(email,password){
model.fun.login(email, function(resPassword) {
if(password === resPassword){
console.log("success");
} else {
console.log("failure");
}
})
}
It's because the function model.fun.login is asynchronous so before getting response from this function, it'll move to the next statement, which returns undefined.
methods.login = function(email,password){
model.fun.login(email, function(resPassword) {
if(password === resPassword){
console.log("success");
}
else {
console.log("failure");
}
})
}
You can return the Promise and handle it in then block inside controller.
reutrn student.findOne({where : {email : email_id }} ));
This will return the promise. In the controller, you can call the method as
model.fun.login(email).then(function(result){
console.log(JSON.stringfy(result));
});

Using Firebase, how can I create a query based on UID?

I created a function that adds a UID to the database along with an item's state:
changestate(item) {
var postData = {
state: "listed",
};
var user = firebase.auth().currentUser;
var uid = user.uid;
var updates = {};
updates['foods' + '/' + item.$key + '/' + 'state' + '/' + uid] = postData;
return firebase.database().ref().update(updates);
}
I want to create a query that only shows the data corresponding to that UID. In a previous query I was using:
getLists(): FirebaseListObservable<any> {
return this.db.list('/foods', {
query: {
orderByChild: 'state',
equalTo: 'listed'
}
});}
This is the structure of my database:
{
"foods" : {
"foodID1" : {
"category" : "Produce",
"foodname" : "Apples",
"state" : {
"aePQkvozV6gehP7ihjN0OWCltKu2" : {
"state" : "listed"
}
}
},
"foodID2" : {
"category" : "Dairy",
"foodname" : "Cheese",
"state" : {
"aePQkvozV6gehP7ihjN0OWCltKu2" : {
"state" : "listed"
}
}
}
}
}
What do I need to do to show the items that correspond to a signed in user's UID?
The orderByChild property can take a path. So the code then simple becomes:
getLists(): FirebaseListObservable<any> {
return this.db.list('/foods', {
query: {
orderByChild: 'state/'+firebase.auth().currentUser.uid+'/state',
equalTo: 'listed'
}
});
}
This requires that the user is signed in of course. To test the query without a signed-in user, you can use a hard-coded value:
getLists(): FirebaseListObservable<any> {
return this.db.list('/foods', {
query: {
orderByChild: 'state/aePQkvozV6gehP7ihjN0OWCltKu2/state',
equalTo: 'listed'
}
});
}

search in array filed of mongodb by mongoos in query

I have a collection Events in my Mongodb and it has an array filed called for_who.
This field is for checking if a user id is in this array, so this user can see this Event. I want to get the Events that for_who field contains user_id.
This is my current query:
Events.find(
{ for_who: { "$in" : [user_id]} }
).lean().exec(function(err , obj) { ... });
my schema:
var eventSchema = new mongoose.Schema({
id : { type: Number , required: true , unique: true } ,
title : { type: String , required: true } ,
created_at : { type: String , required: true } ,
for_who : { type: Array }
});
var Events = mongoose.model('Events', eventSchema);
Events.find().then((events) => {
var userData = events.find((v) => {
return v.for_who === user_id
})
if(userData){
//user was found
}
})
i think this cloud work

node Sequelize how to write static functions

I have experience in writing statics functions in moongose like
var mongoose =require('mongoose');
var Schema = mongoose.Schema;
var adminSchema = new Schema({
fullname : String,
number : Number,
email: String,
auth : {
username: String,
password : String,
salt: String
}
});
adminSchema.statics.usernameInUse = function (username, callback) {
this.findOne({ 'auth.username' : username }, function (err, doc) {
if (err) callback(err);
else if (doc) callback(null, true);
else callback(null, false);
});
};
here usernameInUse is the function I wana write but using sequelize for mysql database
my model
/*
This module is attendant_user table model.
It will store attendants accounts details.
*/
"use strict";
module.exports = function(sequelize, DataTypes) {
var AttendantUser = sequelize.define('AttendantUser', {
username : {
type : DataTypes.STRING,
allowNull : false,
validate : {
isAlpha : true
}
},{
freezeTableName : true,
paranoid : true
});
return AttendantUser;
};
How to add statics function here..??
Well, you can easily use Expansion of models
var User = sequelize.define('user', { firstname: Sequelize.STRING });
// Adding a class level method
User.classLevelMethod = function() {
return 'foo';
};
// Adding an instance level method
User.prototype.instanceLevelMethod = function() {
return 'bar';
};
OR in some cases you may use getter and setter on your models. See the docs:
A) Defining as part of a property:
var Employee = sequelize.define('employee', {
name: {
type : Sequelize.STRING,
allowNull: false,
get : function() {
var title = this.getDataValue('title');
// 'this' allows you to access attributes of the instance
return this.getDataValue('name') + ' (' + title + ')';
},
},
title: {
type : Sequelize.STRING,
allowNull: false,
set : function(val) {
this.setDataValue('title', val.toUpperCase());
}
}
});
Employee
.create({ name: 'John Doe', title: 'senior engineer' })
.then(function(employee) {
console.log(employee.get('name')); // John Doe (SENIOR ENGINEER)
console.log(employee.get('title')); // SENIOR ENGINEER
})
B) Defining as part of the model:
var Foo = sequelize.define('foo', {
firstname: Sequelize.STRING,
lastname: Sequelize.STRING
}, {
getterMethods : {
fullName : function() { return this.firstname + ' ' + this.lastname }
},
setterMethods : {
fullName : function(value) {
var names = value.split(' ');
this.setDataValue('firstname', names.slice(0, -1).join(' '));
this.setDataValue('lastname', names.slice(-1).join(' '));
},
}
});
Hope it helps.
AttendantUser.usernameInUse = function (username, callback) {
...
};
return AttendantUser;

Populate not working for an array of ObjectIDs

This is the implementation of my models :
var itemSchema = new Schema({
name : String,
qte : Number
});
var Item = mongoose.model('Item', itemSchema);
var orderSchema = new Schema({
state : {
type: String,
enum: ['created', 'validated', 'closed', 'starter', 'meal', 'dessert'],
required : true
},
table : {
number : {
type : Number,
required : true
},
name : {
type : String,
required : false
}
},
date: { type: Date, default: Date.now },
_items : [{type:Schema.Types.ObjectId, ref:'Item'}]
});
And this is how I do my query
getByIdRaw : function (orderId, callback) {
Order.findById(orderId)
.populate('_items')
.exec(function(err, order) {
debug(order);
callback(order);
});
}
This is my response without populating
{
_id: "5549e17c1cde3a4308ed70d5"
state: "created"
_items: [1]
0: "5549e1851cde3a4308ed70d6"
-
date: "2015-05-06T09:40:12.721Z"
table: {
number: 1
}-
__v: 1
}
...and my response when populating _items
{
_id: "5549e17c1cde3a4308ed70d5"
state: "created"
__v: 1
_items: [0]
date: "2015-05-06T09:40:12.721Z"
table: {
number: 1
}-
}
Why the _items array is empty ? What am I doing wrong ?
EDIT : the addItem function
addItem : function (orderId, item, callback) {
Order.findById(orderId)
.exec(function(err, order) {
if (err) {
error(err);
return callback(err);
}
if (order === null) {
return callback("No order with this id");
}
var newItem = new Item({
name : item.name,
qte :item.qte
});
order._items.push(newItem);
order.markModified('_items');
order.save();
callback();
});
}
The issue is the new item is never persisted to the items collection. Mongoose references only populate they don't persist a new item to the referenced collection.
addItem: function(orderId, item, callback) {
var newItem = new Item({
name: item.name,
qte: item.qte
});
newItem.save(function(err, savedItem) {
if (err) {
error(err);
return callback(err);
}
Order.findById(orderId).exec(function(err, order) {
if (err) {
error(err);
return callback(err);
}
if (order === null) {
return callback("No order with this id");
}
order._items.push(savedItem);
order.markModified('_items');
order.save(callback);
});
});
}

Categories

Resources