Vue mystery mutations in the store - vue.js

I got trouble with mutating a user. User is requested from a server. And it arrives correctly. I can see it in network log.
Then in auth module something happens I don't understand.
Inside getme() there is console.log( "from getme", response.data, response.data.role) and role is different in response.data and response.data.role.
What am I missing??
auth.module.js
async signIn({ commit, state }, credentials) {
let response = await AuthService.signIn(credentials);
commit("SET_TOKEN", response.data.token);
// commit("SET_USER", response.data.user);
commit("SET_AUTHENTICATED", true);
return Promise.resolve(response.data);
// dispatch('getme', localStorage.getItem('token'))
},
async getme({ commit, state }, token) {
if (token) {
commit("SET_TOKEN", token);
}
if (!state.token) {
return;
}
try {
let response = await AuthService.getme();
console.log( "from getme", response.data, response.data.role)
commit("SET_USER", response.data);
} catch (e) {
commit("SET_TOKEN", null);
commit("SET_USER", null);
commit("SET_AUTHENTICATED", false);
}
},
{id: 18, first_name: 'Ed', middle_initial: null, last_name: 'Bre', email: 'admin#me.com', …} Admin
cell_phone:(...)
city: (...)
created_at: (...)
email: (...)
email_verified_at: (...)
first_name: (...)
gender: (...)
id: (...)
land_line: (...)
last_name: (...)
middle_initial: (...)
momemail: (...)
profileimg : (...)
role: "Sales"
state: (...)
status: (...)
street_I: (...)
street_II: (...)
tag: (...)
updated_at: (...)
zip: (...)

Related

Can't insert even static size array into creation mutation into AWS GraphQL API in React Native

I have the the following schema in my schema.graphql folder (please note the relationship keywords):
type Blog #model {
id: ID!
name: String!
description: String
post: [Post] #hasMany
userId: String
username: String
}
type Post #model {
id: ID! #primaryKey
isPrivate: Boolean!
title: String!
description: String
comments: [Comment] #hasMany
userId: String
username: String
}
type Comment #model {
id: ID! #primaryKey
content: String
likes: [Like] #hasMany
userId: String
username: String
}
type Like #model {
id: ID! #primaryKey
isLiked: Boolean!
}
I'm performing creation, deletion and update mutations but somehow I cannot get them to work when I try to insert an array, be its size static or dynamic.
I'll give you an example:
THIS WORKS:
const postCreation = async () => {
try {
const user = await Auth.currentAuthenticatedUser();
const newPost = await API.graphql(
graphqlOperation(createPost, {
input: {
isPrivate: false,
title: "postTitle",
description: "postDescription",
userId: user.attributes.sub,
username: user.username,
},
}),
);
console.log(newPost);
}
catch(e) {
console.log(e.message);
}
}
But this DOES NOT:
const postCreation = async () => {
try {
const user = await Auth.currentAuthenticatedUser();
const newPost = await API.graphql(
graphqlOperation(createPost, {
input: {
isPrivate: false,
title: "postTitle",
description: "postDescription",
comments: [
{
content: "content1",
},
{
content:: "content2",
}
],
userId: user.attributes.sub,
username: user.username,
},
}),
);
console.log(newPost);
} catch(e){
console.log(e.message);
}
}
All I get from the catch block is "undefined"
What's the proper way of doing this?

Unit Test with Express, TypeScript, Prisma and Jest

I'm trying to unit test with Prisma and Jest following this link https://www.prisma.io/docs/guides/testing/unit-testing.
Here is my test code:
test("should create a user ", async () => {
var user: any = {
store_id: "601d6dea-9b89-4c0d-adfc-6ed52424a2a0",
password: '1234',
user_name: "username",
first_name: "Rich",
last_name: "hello#prisma.io",
phone: "12345",
is_phone_verified: true,
is_email_verified: true, };
prismaMock.sec_user_fs.create.mockImplementation(user)
await expect(createUser(user)).resolves.toEqual({
store_id: "601d6dea-9b89-4c0d-adfc-6ed52424a2a0" }); });
createUser method is save data to database. Here is code:
export async function createUser(user: CreateUser) {
user = await prisma.sec_user_fs.create({
data: user,
})
return {"store_id": user.store_id} }
So my questions are:
prismaMock.sec_user_fs.create.mockImplementation(user) - In my understanding this line mocked database table, it prevent not insert data to table while testing. But, it does. How can mock without inserting, updating,deleting to table?
createUser method return json object. But if i test my api end point /code is below/ how expect result? Because it does return res.status(200) etc.?
export default asyncHandler(async (req: CustomRequest, res: Response)=> {
const body = {
user_name: req.body.user_name,
first_name: req.body.first_name,
last_name: req.body.last_name,
phone: req.body.phone,
phone_country_code: req.body.phone_country_code }
const user_id = req.params.id
const user = await prisma.sec_user_fs.updateMany({
where: {
user_id,
status: 'A'
},
data: body });
res.status(200).send({
status: 'Success',
message: req.t('success'),
errors: [],
data: user, }); });
Thanks in advance :)

Successful GraphQL Mutation keeps Returning Undefined

I am sending a mutation over from a React Native Frontend to a NodeJs / GraphQL Backend. The mutation request goes through, and a mutation occurs, but back on the frontend, the value of that mutation is undefined when it should instead be returning an ID. My mutation looks like this...
export default {
Mutation: {
driverCreateCollisionAccident: async (_, {
accidentId,
specific_pictures,
contact_info,
collision_report,
extra_info
}, context) => {
const driver = await checkDriverAuth(context)
const foundAccident = await db.accident.findUnique({
where: {
id: accidentId
}
})
if (!foundAccident) {
throw new Error("Accident does not exist")
}
await handleDriverAccidentOwnership(driver.id, accidentId)
console.log("right before create collision mutation")
try {
return await db.collisionAccident.create({
data: {
specific_pictures: specific_pictures,
contact_info: contact_info,
collision_report: collision_report,
extra_info: extra_info,
accident: {
connect: {
id: accidentId
}
},
accidentId: accidentId
}
}).then( (resolved) => {
console.log(resolved)
return resolved
})
} catch (error) {
console.log(error)
throw new Error(error)
}
}
}
}
The most important part of that code is
.then( (resolved) => {
console.log(resolved)
return resolved
})
As the console.log returns exactly what it is supposed to, an object that looks like this...
id: '81b7cc7c-53d7-43d7-bb14-1438ef53a227',
specific_pictures: { 'Pic One': 'Test url' },
contact_info: {
address: 'Have Picture',
lastname: 'Have Picture',
firstname: 'Have Picture',
phone_number: '123456789',
insurance_provider: 'Have Picture',
driver_license_number: 'Have Picture',
insurance_policy_number: 'Have Picture'
},
extra_info: 'null',
collision_report: {
towed: true,
legal_fault: 'I caused the accident',
fire_or_explode: true
},
accidentId: '0b5fd832-9540-475e-9b34-ece6dfdc58df'
}
But for some reason, when I try to log the results of this mutation on the frontend, all I get is undefined, but no errors occur, and I still get the backend's console.logs to hit properly so the mutation itself is working. My front end code looks like this...
const handleSubmit = () => {
handleMutation().then( (resolved) => {
console.log(resolved)
})
}
const handleMutation = async () => {
await driverCreateCollisionAccident({
variables: {
accidentId: collisionData.accidentId,
specific_pictures: collisionData.specific_pictures,
contact_info: collisionData.contact_info,
collision_report: collisionData.collision_report,
extra_info: collisionData.extra_info,
}
})
}
I don't even need the full object returned, I JUST need an ID. Does anyone see what could be going wrong here?
Maybe you can try something like this
const result = await db.collisionAccident.create({
data: {
specific_pictures: specific_pictures,
contact_info: contact_info,
collision_report: collision_report,
extra_info: extra_info,
accident: {
connect: {
id: accidentId
}
},
accidentId: accidentId
}
})
return result
instead of
return await db.collisionAccident.create({
data: {
specific_pictures: specific_pictures,
contact_info: contact_info,
collision_report: collision_report,
extra_info: extra_info,
accident: {
connect: {
id: accidentId
}
},
accidentId: accidentId
}
}).then( (resolved) => {
console.log(resolved)
return resolved
})

Relay mutation for React native returning 400 bad request?

I have been having SO much trouble trying to get a mutation to work.
Given this GraphQL Schema, can anyone PLEASE help me create a simple create User mutation? I don't understand what I am missing. I got it to a point where it throws a 400 error from the GraphQL server and it does not fire the resolve function.
var userType = new GraphQLObjectType({
name: 'User',
description: 'User creator',
fields: () => ({
id: {
type: new GraphQLNonNull(GraphQLString),
description: 'The id of the user.'
},
email: {
type: GraphQLString,
description: 'The email of the user.'
},
business: {
type: GraphQLString,
description:
'The name of the business of the user as the app refers to it.'
},
businessDisplayName: {
type: GraphQLString,
description: 'The name of the business of the user as they typed it in.'
},
trips: {
type: new GraphQLList(tripType),
description: 'The trips of the user, or an empty list if they have none.',
resolve: (user, params, source, fieldASTs) => {
var projections = infoToProjection(fieldASTs)
return Trip.find(
{
_id: {
// to make it easily testable
$in: user.trips.map(id => id.toString())
}
},
projections,
function(err, docs) {
return docs
}
)
}
}
})
})
var schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'root',
fields: {
trips: {
type: new GraphQLList(tripType),
resolve: function() {
return Trip.find({})
}
},
users: {
type: new GraphQLList(userType),
resolve: function() {
return User.find({})
}
},
user: {
type: userType,
args: {
id: {
name: 'id',
type: new GraphQLNonNull(GraphQLString)
}
},
resolve: (root, { id }, source, fieldASTs) => {
return User.findOne(
{ _id: id },
infoToProjection(fieldASTs),
function(err, doc) {
return doc
}
)
}
},
trip: {
type: tripType,
args: {
id: {
name: 'id',
type: new GraphQLNonNull(GraphQLString)
}
},
resolve: (root, { id }, source, fieldASTs) => {
var projections = infoToProjection(fieldASTs)
return Trip.findOne({ _id: id }, projections, function(err, doc) {
return doc
})
}
}
}
}),
// mutation
mutation: new GraphQLObjectType({
name: 'Mutation',
fields: {
createUser: {
name: 'createUser',
type: userType,
args: {
input: { type: new GraphQLInputObjectType({
name: 'user',
fields: {
business: { type: GraphQLString },
email: { type: GraphQLString },
businessDisplayName: { type: GraphQLString }
}
})
}},
resolve: (parentValue, args) => {
let user = new User({ ...args.input })
user.save()
return user
}
}
})
})
export var getProjections = infoToProjection
export default schema
This works with GraphiQL using the following queries or mutations:
mutation {
createUser(input:{business:"business", email: "e#mai.l", businessDisplayName: "businessDN"}) {
id
email
business
businessDisplayName
}
}
fragment UserFragment on User {
id
business
businessDisplayName
trips{
title
}
}
{
hideya: user(id: "someid") {
...UserFragment
}
}
I finally fixed the problem. Tried to understand the source of the problem so I used a new NetworkLayer to enable appropriate logging and meaningful error messages. Then threw the an error when my mutation failed. The error message was : "Cannot query field clientMutationId". Looked that up and found that to be able to mutate objects you need to have that field on your GraphQL type. So I added it.
Lesson learned: I highly recommend using react-relay-network-layer.
More details:
Here is my code for it:
import {
RelayNetworkLayer,
urlMiddleware,
batchMiddleware,
} from 'react-relay-network-layer';
Relay.injectNetworkLayer(new RelayNetworkLayer([
batchMiddleware({
batchUrl: 'http://localhost:3000/graphql',
}),
urlMiddleware({
url: 'http://localhost:3000/graphql',
}),
]));
Note: This enables logging and by default it's a simple console.log.
Here is how I threw the error:
const params = {
email: email.toLowerCase(),
businessDisplayName: business,
business: business.toLowerCase()
}
var onSuccess = () => {
console.log('Mutation successful!')
}
var onFailure = transaction => {
var error = transaction.getError() || new Error('Mutation failed.')
console.error(error)
}
Relay.Store.commitUpdate(new FindOrCreateUser({ user: { ...params } }), { onFailure, onSuccess })
And of course you always need to clean your cache and restart your packager.

How can I override builtin login method in Loopback?

I've created a new User model, based on builtin one. I'm trying this:
module.exports = function(TiUser) {
TiUser.on('dataSourceAttached', function(obj) {
var login = TiUser.login;
TiUser.login = function(credentials, include, cb) {
var result = login.apply(this, credentials);
// Do my stuff
cb(null, my_data);
};
});
};
But I can't get it working... What is wrong? or how could this be done right?
Thanks
You may want to consider adding an afterRemote() hook to login(). Now you can achieve to add role( using Role model ) to user. For example:
TiUser.afterRemote('login', function(ctx, next) {
//add role to the user.
next();
});
At the end I've created a new method instead of overriding a current one:
module.exports = function(TiUser) {
TiUser.auth = function(credentials, include, fn) {
var self = this;
self.login(credentials, include, function(err, token) {
authInfo = {
token: token
};
fn(err, authInfo);
});
};
TiUser.remoteMethod(
'auth',
{
description: 'Login method with Role data information embedded in return',
accepts: [
{arg: 'credentials', type: 'object', required: true, http: {source: 'body'}},
{arg: 'include', type: ['string'], http: {source: 'query' },
description: 'Related objects to include in the response. ' +
'See the description of return value for more details.'}
],
returns: {
arg: 'accessToken', type: 'object', root: true,
description: 'User Model'
},
http: {verb: 'post'}
}
);
};