Data does not save on database after implementing validation - validation

I have problem with my validation where after I implement it saveProduct() function, the data that I want to store does not add or update to the database. Also, I shared the product service file, because someone said also have to pass the 'this.productForm.value' inside service file. but I'm not quite sure how.
Below is the code: details.page.ts
ngOnInit() {
this.productForm = this.fb.group({
productName: new FormControl('', Validators.compose([
Validators.required,
])),
productDecs: new FormControl('', Validators.compose([
Validators.required,
])),
});
}
async saveProduct() {
await this.presentLoading();
this.product.userId = this.authService.getAuth().currentUser.uid;
if (this.productId) {
try {
console.log('product update');
console.log(this.productForm.value);
await this.productService.updateProduct(this.productId, this.productForm.value);
await this.loading.dismiss();
this.navCtrl.navigateBack('/vendor-tabs/home-vendor');
} catch (error) {
console.log('product dont update');
this.presentToast('Error trying to save');
this.loading.dismiss();
}
} else {
this.product.createdAt = new Date().getTime();
try {
console.log(this.productForm.value);
console.log('product add');
await this.productService.addProduct(this.productForm.value);
await this.loading.dismiss();
this.navCtrl.navigateBack('/vendor-tabs/home-vendor');
} catch (error) {
console.log('product dont add');
this.presentToast('Error trying to save');
this.loading.dismiss();
}
}
}
Below is the code for product.service.ts
addProduct(product: Product) {
return this.productsCollection.add(product);
}
getProduct(id: string) {
return this.productsCollection.doc<Product>(id).valueChanges();
}
updateProduct(id: string, product: Product) {
return this.productsCollection.doc<Product>(id).update(product);
}
deleteProduct(id: string) {
return this.productsCollection.doc(id).delete();
}

Related

How to add custom header in NestJS GraphQL Resolver

I want to add custom header in the response of one of my GraphQL resolver Queries in Nestjs. here is the code.
#Query(() => LoginUnion)
async login(
#Args({ type: () => LoginArgs }) { LoginInfo: { email, password } } : LoginArgs
): Promise<typeof LoginUnion> {
try {
let userInfo = await this.userModel.findOne({ email, password: SHA256(password).toString() }, { 'password': false });
if (userInfo === null) {
return new CustomErrorResponse({ message: 'Wrong password or username'});
}
if (!userInfo.isVerified) {
return new CustomErrorResponse({ message: 'User in not verified'});
}
const token = await this.authentication.sign(userInfo, config.get('Secure_JWT_Sign_Key'));
// set header here
console.log('_DEBUG_ =>', token);
} catch(error) {
console.log('user.resolver.login => ', error);
return new CustomErrorResponse({ message: 'Server Exception', additonalInfo: JSON.stringify(error) });
}
}

Graphql - universal permission guards

I am trying to implement permission guards in a graphql backend using apollo server. The following code works:
Resolvers
const Notification = require('../../database/models/notifications');
const Task = require('../../database/models/tasks');
notification: combineResolvers(isNotificationOwner, async (_, { id }) => {
try {
const notification = await Notification.findById(id);
return notification;
} catch (error) {
throw error;
}
})
task: combineResolvers(isTaskOwner, async (_, { id }) => {
try {
const task = await Task.findById(id);
return task;
} catch (error) {
throw error;
}
})
Resolver Middleware (permission guards)
const Notification = require('../../database/models/notifications');
const Task = require('../../database/models/tasks');
// userId is the id of the logged in user retrieved from the context
module.exports.isNotificationOwner = async (_, { id }, { userId }) => {
try {
const notification = await Notification.findById(id);
if (notification.user.toString() !== userId) {
throw new ForbiddenError('You are not the owner');
}
return skip;
} catch (error) {
throw error;
}
}
module.exports.isTaskOwner = async (_, { id }, { userId }) => {
try {
const task = await Task.findById(id);
if (task.user.toString() !== userId) {
throw new ForbiddenError('You are not the owner');
}
return skip;
} catch (error) {
throw error;
}
}
Going on like this will create a lot of duplicate code and does not feel very DRY. Therefore, I am trying to create a more universal solution, to no evail so far.
What I tried:
Resolvers
const Notification = require('../../database/models/notifications');
const Task = require('../../database/models/tasks');
notification: combineResolvers(isOwner, async (_, { id }) => {
try {
const notification = await Notification.findById(id);
return notification;
} catch (error) {
throw error;
}
})
task: combineResolvers(isOwner, async (_, { id }) => {
try {
const task = await Task.findById(id);
return task;
} catch (error) {
throw error;
}
})
Resolver Middleware
const Notification = require('../../database/models/notifications');
const Task = require('../../database/models/tasks');
module.exports.isOwner = async (_, { id, collection }, { userId }) => {
try {
const document = await collection.findById(id);
if (document.user.toString() !== userId) {
throw new ForbiddenError('You are not the owner');
}
return skip;
} catch (error) {
throw error;
}
}
I am unable to pass a collection name as an argument to the middleware resolver.
I would be tremendously thankful for any kind of help!
Based off your code, it seems like you're looking for making isOwner a higher-order function, so that you can pass in the collection, and it returns the curried method.
module.exports.isOwner = (collection) => {
return async (_, { id }, { userId }) => {
try {
const document = await collection.findById(id);
if (document.user.toString() !== userId) {
throw new ForbiddenError('You are not the owner');
}
return skip;
} catch (error) {
throw error;
}
}
}
Usage:
const resolvers = {
Query: {
task: combineResolvers(isOwner(Task), async (_, { id }) => {
try {
const task = await Task.findById(id);
return task;
} catch (error) {
throw error;
}
})
},
};

How do I add recursive logic in resolvers using GraphQL mutations?

Is it possible to add logic in resolvers using GraphQL mutations?
I am trying to create a four-digit string as an alias for a post if the user does not provide it. Then, I would like to check the database to see if the four-digit string exists. If the string exists, I would like to create another four-digit string recursively.
At the moment, I'm exploring adding logic to mutations within resolvers, but I'm not sure if this is doable. I'm using these documents for my foundation: graphql.org sequelize.org
This is my current code block:
Working as of 12/4/2020
const MakeSlug = require("./services/MakeSlug");
const resolvers = {
Query: {
async allLinks(root, args, { models }) {
return models.Link.findAll();
},
async link(root, { id }, { models }) {
return models.Link.findByPk(id);
}
},
Mutation: {
async createLink(root, { slug, description, link }, { models }) {
if (slug !== undefined) {
const foundSlug = await models.Link.findOne({
where: { slug: slug }
});
if (foundSlug === undefined) {
return await models.Link.create({
slug,
description,
link,
shortLink: `https://shink.com/${slug}`
});
} else {
throw new Error(slug + " exists. Try a new short description.");
}
}
if (slug === undefined) {
const MAX_ATTEMPTS = 10;
let attempts = 0;
while (attempts < MAX_ATTEMPTS) {
attempts++;
let madeSlug = MakeSlug(4);
const foundSlug = await models.Link.findOne({
where: { slug: madeSlug }
});
if (foundSlug !== undefined) {
return await models.Link.create({
slug: madeSlug,
description,
link,
shortLink: `https://shink.com/${madeSlug}`
});
}
}
throw new Error("Unable to generate unique alias.");
}
}
}
};
module.exports = resolvers;
This is my full codebase.
Thank you!
A while loop solved the challenge. Thanks xadm.
const MakeSlug = require("./services/MakeSlug");
const resolvers = {
Query: {
async allLinks(root, args, { models }) {
return models.Link.findAll();
},
async link(root, { id }, { models }) {
return models.Link.findByPk(id);
}
},
Mutation: {
async createLink(root, { slug, description, link }, { models }) {
if (slug !== undefined) {
const foundSlug = await models.Link.findOne({
where: { slug: slug }
});
if (foundSlug === undefined) {
return await models.Link.create({
slug,
description,
link,
shortLink: `https://shink.com/${slug}`
});
} else {
throw new Error(slug + " exists. Try a new short description.");
}
}
if (slug === undefined) {
const MAX_ATTEMPTS = 10;
let attempts = 0;
while (attempts < MAX_ATTEMPTS) {
attempts++;
let madeSlug = MakeSlug(4);
const foundSlug = await models.Link.findOne({
where: { slug: madeSlug }
});
if (foundSlug !== undefined) {
return await models.Link.create({
slug: madeSlug,
description,
link,
shortLink: `https://shink.com/${madeSlug}`
});
}
}
throw new Error("Unable to generate unique alias.");
}
}
}
};
module.exports = resolvers;

How can i return rejected from async-await?

I would like to return rejected, when fetch request is fail. How can i reject async await?
class FetchUrl {
static async getJson(api) {
try {
const response = await fetch(api);
if (response.ok) {
const questions = await response.json();
return questions;
}
} catch (error) {
throw new Error("Request Failed!");
}
}
}
FetchUrl.getJson(this.api).then((resolved) => {
console.log(resolved)
// this sampe of code is executing even fetch is rejected.. what can i do
to avoid it?
}, rejected => {
console.log(rejected)
})
}

Cannot set property 'clientMutationId' of undefined" Error

outputFields: {
token: {
type: GraphQLString,
resolve: (token) => token
}
},
outputfields never gets called, not sure whether i am doing in a right way or not, doesn't the resolve function gets called while returning data from mutateAndGetPayload method.
mutateAndGetPayload: (credentials) => {
console.log('credentials', credentials);
userprof.findOne({email: credentials.email}).exec(function(err, r) {
if(!r) {
return new Error('no user')
} else if(r) {
if(r.password != credentials.password) {
return new Error('password error');
} else {
var token = jwt.getToken(r);
console.log(token);
return {token};
}
}
});
}
I think that you need to return something from the mutateAndGetPayload method. That could be a promise. Try to return the userprof.findOne.
Solution
token: {
type: GraphQLString,
resolve: ({token}) => token
}
},
mutateAndGetPayload: (credentials) => {
return UserProf.findOne({ email: credentials.email }).then((r) => {
if (!r) {
return new Error('no user');
} else if (r) {
if (r.password != credentials.password) {
return new Error('password error');
} else {
return { token: jwt.getToken(r) };
}
}
});
}

Resources