Sequelize, Mysql how to return deleted ids - mysql

I have a GraphQL mutation that deletes items. I'm trying to retrieve the deleted ids. However null ids are returned but items are deleted from the database.
Shema
type Mutation{
deletePropertyItems(id: [ID!]!): DeletePropertyItemsRes!
}
type DeletePropertyItemsRes {
success: Boolean!
message: String!
propertyItem:PropertyItem
}
type PropertyItem {
id: ID!
title: String!
description: String!
}
Mutation Resolver
async deletePropertyItems(_, { id }, { models }) {
try {
const deletedRows = await models.PropertyItem.destroy({
where: { id: id },
});
if (deletedRows) {
return {
success: true,
message: "Property Item(s) Deleted Successfully!",
propertyItem: deletedRows,
};
}
return {
success: false,
message: "Operation not Successful",
};
} catch (error) {
throw new Error(error.message);
}
},
Apollo Studio Error

Related

Sails.JS: AUTO INCREMENT Implementation Failed

I'm developing a Sails.JS app that performs CRUD operations with a MySQL database using waterline ORM. My models have an attribute id set to auto-increment with the beforeCreate function, yet every time I try to call the create function, this error occurs:
{
"error": {
"name": "UsageError",
"code": "E_INVALID_NEW_RECORD",
"details": "Missing value for required attribute id. Expected a number, but instead, got: undefined"
} }
Here's my model:
module.exports = {
primaryKey: 'id',
attributes: {
id: {
type: "number",
required: true,
unique: true,
autoIncrement: true
},
name: {
type: "string",
required: true
},
beforeCreate : function(item, next) {
Counter.native(function(err, collection) {
if (err) console.log(err);
collection.findAndModify(
{ _id: "id" },
null,
{ $inc: { seq: 1 } },
{ new:true, upsert:true },
function(err, object){
if (err) console.log(err);
item.id = object.seq;
next();
}
);
});
}
};
Here's my model controller:
module.exports = {
create :function(req,res,next) {
let params = {name:req.param('name') };
model.create(params , function(err , createdData) {
if(err){
return res.badRequest({
error: err
});
}
else
{
return res.json({ added});
}
});
},

How to return the result from a raw query (Sequelize) to GraphQL

I'm newbie with GraphQL and Sequelize but I have developed a test where I can make querys and get results from Graphiql using the functions of Sequalize, but I'm interested in making more complex querys with querys with several tables.
Now, this code works fine:
schema.js
import {
GraphQLObjectType,
GraphQLNonNull,
GraphQLID,
GraphQLInt,
GraphQLString,
GraphQLFloat,
GraphQLList,
GraphQLSchema
} from "graphql";
import { DB } from "../db";
import {DateTime} from "../scalar/dateTime";
import {Player} from "./Player";
import {League} from "./League";
import {Group} from "./Group";
import {Season} from "./Season";
const Query = new GraphQLObjectType({
name: "Query",
description: "This is root query",
fields: () => {
return {
players: {
type: GraphQLList(Player),
args: {
id: {
type: GraphQLID
}
},
resolve(root, args){
return DB.db.models.tbl003_player.findAll({where: args});
}
},
leagues: {
type: GraphQLList(League),
args: {
id: {
type: GraphQLID
}
},
resolve(root, args){
return DB.db.models.tbl001_league.findAll({where: args});
}
},
groups: {
type: GraphQLList(Group),
args: {
id: {
type: GraphQLID
}
},
resolve(root, args){
return DB.db.models.tbl024_group.findAll({where: args});
}
},
seasons: {
type:GraphQLList(Season),
args: {
id: {
type: GraphQLID
}
},
resolve(root, args){
return DB.db.models.tbl015_seasons.findAll({where: args})
}
}
}
}
});
const Schema = new GraphQLSchema({
query: Query
});
module.exports.Schema = Schema;
So, I would like to make an easy test to know how to return the data from a raw query to GraphQL. I have read that resolve method returns a promise, and I have tried to return a promise with the result of the query, but it doesn't work.
players: {
type: GraphQLList(Player),
args: {
id: {
type: GraphQLID
}
},
resolve(root, args){
DB.db.query("select * from tbl003_player where id = 14",
{raw: true, type: DB.db.QueryTypes.SELECT}).then((players)=>{
let myPromise = new Promise((resolve, reject)=>{
resolve(players);
});
return myPromise;
}).catch((reject)=>{
console.log("Error: " + reject);
});
}
},
Therefore, how can I return data from a query with Sequelize to GraphQL?
Return the promise you get from sequelize. You are also doing a lot of work that is not required after your promise. Maybe read more about promises before moving on :)
resolve(root, args){
return DB.db.query(
"select * from tbl003_player where id = 14",
{ raw: true, type: DB.db.QueryTypes.SELECT }
);
}

GraphQL error update mutation "Resolve function for \"User.id\" returned undefined"

I am a newbie to GraphQL and trying to write an update mutation. However, I am receiving Resolve function for \"User.id\" returned undefined" error although the database is actually got updated.
What am I doing wrong?
userSchema.js:
import Sequelize from 'sequelize';
import SqlHelper from '../helpers/sqlhelper';
const config = require('../../config');
const sequelizer = new SqlHelper(config).Init();
const createUser = sequelizer.define(
'createUser',
{
...
}
);
const updateUser = sequelizer.define(
'updateUser',
{
id: {
type: Sequelize.UUID,
field: 'Id',
primaryKey: true,
defaultValue: Sequelize.UUIDV4,
},
username: {
type: Sequelize.STRING,
field: 'Username',
allowNull: true,
},
email: {
type: Sequelize.STRING,
field: 'Email',
allowNull: true,
},
firstname: {
type: Sequelize.STRING,
field: 'FirstName',
allowNull: true,
},
lastname: {
type: Sequelize.STRING,
field: 'LastName',
allowNull: true,
},
....
},
{
// define the table's name
tableName: 'Users',
},
);
module.exports = User;
UserResolver.js:
import User from '../dbschemas/user';
import Sequelize from 'sequelize';
const Op = Sequelize.Op;
export default {
Mutation: {
createUser: async (obj, args) =>
(await User.create(args)),
updateUser: async (obj, args) =>
(await User.update(args,
{
where: {
id: args.id,
},
returning: true
}))
}
};
Although calling updateUser from GraphiQL updates the records (in db), it results in a "Resolve function for \"User.id\" returned undefined" error:
mutation{
updateUser(id: "2ecd38ca-cf12-4e79-ac93-e922f24af9e3",
username: "newUserTesting",
email: "testemail#yahoo.com",
lastname: "TestUserLName",
firstname: "fname1") {
id
}
}
{
"data": null,
"errors": [
{
"message": "Resolve function for \"User.id\" returned undefined",
"locations": [
{
"line": 16,
"column": 4
}
],
"path": [
"updateUser",
"id"
]
}
]
}
The issue is clear, your resolver does not return an object containing id.
The docs say that Model.update returns an array in which the 2nd element is the affected row.
Hence, your resolver should look like:
async updateUser(obj, args) {
const resultArray = await User.update( ... )
return resultArray[1]
}
... To be replaced by whatever you need.
So apparently, update does NOT return affected rows for MSSQL, only the number of records affected.
This is true only for postgres when returning: true:
public static update(values: Object, options: Object): Promise<Array<affectedCount, affectedRows>>
Setting returning: true (for MSSQL) returns undefined (and order of params in the array is not even in the right order... i.e. first affectedRows -> undefined, then affectedCount ->num of affected rows.)
Tho get an object back you would need to do something like this:
Mutation: {
createUser: async (obj, args) =>
(await User.create(args.user)),
updateUser: async (obj, args, context, info) =>{
let user = args.user;
let response = await User.update(user,
{
where: {
[Op.or]: [{ email: user.email }, { id: user.id }, { username: user.username }, { lastname: user.lastname}]
},
//returning: true //not working... only for postgres db :(
}).then(ret => {
console.log('ret', ret);
return ret[0];
}).catch(error => {
console.log('error', error)
});
if (response > 0) return user; //return record
//return response > 0; //return true
}
}

Sails/Waterline: Return model relation

So, I'm creating a small application using SailsJS. My database is MySQL.
When I'm testing, first I create a "market" record, then a "stock" record linked to "market" and in another moment, I retrieve this stock record.
I have the following models:
Stock model:
module.exports = {
attributes: {
intern_id: {
type: 'string'
},
tick: {
type: 'string'
},
market: {
model: 'market'
}
}
};
Market model:
module.exports = {
attributes: {
tick: {
type: 'string'
},
name: {
type: 'string'
},
description: {
type: 'string'
},
stocks: {
collection: 'stock',
via: 'market'
},
}
}
Then, first I create a "market" and use the object returned to associate with my "stock" object:
Create and get my market record:
Market.create({tick: 'BVMF', name: 'Bovespa', description: 'Bolsa de Valores'}).exec(function(err, market) {
if(err) done(err);
});
var market = Market.findOne({tick: 'BVMF'}).then(function(results){return results;});
Create my stock record:
Stock.create({intern_id: '1234', tick: 'VALE5', description: 'Vale SA', market: market}).exec(function(err, stock) {
if(err) done(err);
});
And then, when I try to get back this stock, the market object is not retrieved, even if I call populate('market'):
Stock.findOne({tick: 'VALE5'}).populate('market').exec(function(err, record) {
console.log(record);
});
Not too much information, but I guess.
Instead:
Stock.findOne({tick: 'VALE5'}).populate('market').exec(function(err, record) {
console.log(marketObj);
});
Should be:
Stock.findOne({tick: 'VALE5'}).populate('market').exec(function(err, record) {
console.log(record);
});
Second answer:
You forgot about asynchronous. You should do this like that:
Market.create({tick: 'BVMF', name: 'Bovespa', description: 'Bolsa de Valores'}).exec(function(err, market) {
if(err){
done(err);
} else {
Stock.create({intern_id: '1234', tick: 'VALE5', description: 'Vale SA', market: market.id}).exec(function(err, stock) {
if(err){
done(err);
} else {
Stock.findOne({tick: stock.tick}).populate('market').exec(function(err, record) {
console.log(record); // and there is your "Stock" with populated "market"
});
}
});
}
});

Single JSON argument in mutation

Below I'm trying to set a mutation example with one object-arg credentials. I had this working previously then all the sudden it stopped working failing on the JSON part. Why can't I send json through credentials?
import {
GraphQLSchema,
GraphQLObjectType,
GraphQLString,
GraphQLInt,
GraphQLInputObjectType,
GraphQLNonNull,
graphql
} from 'graphql'
let requestType = new GraphQLInputObjectType({
name: 'Request',
fields: {
name: {type: GraphQLString},
}
})
let responseType = new GraphQLObjectType({
name: 'Response',
fields: {
name: {type: GraphQLString},
age: {type: GraphQLInt}
}
})
let schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
author: {
type: GraphQLString,
resolve: (source, args, context, info) => {
return 'Thomas Reggi'
}
}
}
}),
mutation: new GraphQLObjectType({
name: 'Mutation',
fields: {
example: {
type: responseType,
args: {
credentials: {
name: 'credentials',
type: requestType
}
},
resolve: (source, args, context, info) => {
return {
'name': 'Thomas Reggi',
'age': 26
}
}
}
}
})
})
let credentials = { name: "Thomas Reggi" }
let requestString = `
mutation {
example(credentials: ${JSON.stringify(credentials)}) {
name,
age
}
}`
graphql(schema, requestString).then(result => {
console.log(result)
})
Here's the error:
{ errors:
[ Syntax Error GraphQL request (3:25) Expected Name, found String "name: "
2: mutation {
3: example(credentials: {"name":"Thomas Reggi"}) {
^
4: name,
] }
Where does the reference to Name come from? Why is this throwing an error?
Just found out the hard way. You can't have {"name": "Thomas Reggi"} because name is in quotes.
This query works.
mutation {
example(credentials: {name: "Thomas Reggi"}) {
name,
age
}
}