"Not Authorized to access " error on create mutation + GraphQL - node.js

I'm running the below GraphQL query to create data on dynamodb table, but gets the response with "Not Authorized to access createClient on type Client"
Why this is happening at.
GraphQL query:
`mutation addClient{
createClient(input:{
fullName: "Jhon Smith"
title: "Software Engineer"
organization: "AWS"
contactNo: "+341289655524"
email: "smithj#amazon.com"
country: "Canada"
address: "AN/458, Norton place, Down Town"
}){
fullName
}
}`
Response :
{
"data": {
"createClient": null
},
"errors": [
{
"path": [
"createClient"
],
"data": null,
"errorType": "Unauthorized",
"errorInfo": null,
"locations": [
{
"line": 2,
"column": 3,
"sourceName": null
}
],
"message": "Not Authorized to access createClient on type Client"
}
]
}

It solved with authMode
const newTodo = await API.graphql({ query: mutations.createClient, variables: {input: inputData}, authMode: "AMAZON_COGNITO_USER_POOLS" });

Related

Bad Request for an omitted field in GQL

I'm getting "Bad request" response with message "roleId must be a string" when running a mutation. I don't know why since the "roleId" field is optional.
Schema
input CustomerUpdateInput {
name: String
roleId: String
}
updateCustomer(customerId: String!, customer: CustomerUpdateInput!): Customer!
Mutation (ERROR)
mutation updateCustomer{
updateCustomer(customerId:"62c6d6ba303c734ef44ea4ed",
customer: {name:"Pablo"}
),
{id, name }
}
Mutation (WITHOUT ERROR)
mutation updateCustomer{
updateCustomer(customerId:"62c6d6ba303c734ef44ea4ed",
customer: {
name:"Pablo",
roleId:"62c6d64f303c734ef44ea4d8"
}
),
{id, name }
}
Error
{
"errors": [
{
"message": "Bad Request Exception",
"extensions": {
"code": "BAD_USER_INPUT",
"response": {
"statusCode": 400,
"message": [
"roleId must be a string"
],
"error": "Bad Request"
}
}
}
],
"data": null
}

Remove object from nested array in MongoDB using NodeJS

I can see that this question should have been answered here, but the code simply doesn't work for me (I have tried multiple, similar variations).
Here is my data:
[{
"_id": {
"$oid": "628cadf43a2fd997be8ce242"
},
"dcm": 2,
"status": true,
"comments": [
{
"id": 289733,
"dcm": 2,
"status": true,
"clock": "158",
"user": "Nathan Field",
"dept": "IT",
"department": [],
"dueback": "",
"comment": "test 1"
},
{
"id": 289733,
"dcm": 2,
"status": true,
"clock": "158",
"user": "Nathan Field",
"dept": "IT",
"department": [],
"dueback": "",
"comment": "test 2"
}
],
"department": [],
"dueback": ""
}]
And here is my code
const deleteResult = await db.collection('status').updateOne(
{ "dcm": comments.dcm },
{ $pull: { "comments": { "id": comments.id } } },
{ upsert: false },
{ multi: true }
);
Absolutely nothing happens...
So the issue ended up being something to do with running multiple update operations within one function. I have a database connection function like this:
const withDB = async (operations, res) => {
try {
const client = await MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true });
const db = client.db('collection');
await operations(db);
client.close();
} catch (error) {
res.status(500).json({ message: 'Error connecting to db', error });
}
}
And then I call this by using:
withDB(async (db) => {
await db.collection('status').updateMany(
{ "dcm": comments.dcm },
{ $pull: { "comments": { "id": comments.id } } },
{ multi: true }
);
});
The issue occurred it would seem because I had two of these update operations within one withDB function. I have multiple operations in other instances (update item, then fetch collection), but for some reason this caused an issue.
I created a separate call to the withDB function to perform the '$pull' (delete) request, and then updated the array with the new comments.
To check that there was nothing wrong with my actual query, I used Studio3T's IntelliShell feature. If I'd done that sooner I would saved myself a lot of time!

Unsuccessfull payment transfer using Paypal with nodejs

I am trying to implement the Paypal gateway method in nodejs. I am successful redirecting to paypal from my nodejs and when I click on pay I get "Error": "Response Status : 400", with an unsuccessful payment.
My API and its response are given below in detail.
paypal.configure({
'mode': 'sandbox', //sandbox or live
'client_id': 'ATXsRtel_YoAQHVIwP4Z_bmX3VkL1n1N_fJ6FH2os0GynozBJo-Oler8wFVvXzoPpNwbfCAYFvCL76Ke',
'client_secret': 'EAwUmjDRpC-fqz_Fcs262MKrdMDltXJnWiA-
N6gURWcJq1N9IpwzISfcCMLNHzXFJ_38YLQXG3jtUK8a'
});
Post Api for req.body and get the url back
Router.post('/Pay',(req,res)=>{
const create_payment_json = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "http://localhost:7070/PayPal/PaymentSuccess",
"cancel_url": "http://localhost:7070/PayPal/PaymentCancel"
},
"transactions": [{
"item_list": {
"items": [{
"name": "ball",
"sku": "001",
"price": "25.00",
"currency": "USD",
"quantity": 1
}]
},
"amount": {
"currency": "USD",
"total": "25.00"
},
"description": "Testing Product"
}]
};
paypal.payment.create(create_payment_json, function (error, payment) {
if (error) {
res.json({
Message:'Un Approved',
Error:error.message
})
} else {
payment.links.map(_AllLinks=>{
if(_AllLinks.rel === 'approval_url'){
res.json({
Message:'Approved',
Url:_AllLinks.href
})
}
})
}
});
})
Rout to get payerID
Router.get('/PaymentSuccess',(req,res)=>{
let payerId = req.query.PayerID;
let paymentId = req.query.paymentId;
console.log({
payerId:payerId,
paymentId:paymentId
});
let execute_payment_json = {
"payer_id" : payerId,
"transaction" : [{
"amount":{
"currency":"USD",
"total":"25.00"
}
}]
}
paypal.payment.execute(paymentId,execute_payment_json, function(error,payment){
if(error){
res.json({
Error:error.message,
Message:error
})
}else {
res.json({
Result:payment
})
}
})
})
Router.get('/PaymentCancel',(req,res)=>{
res.json({
Result:'Cancelled'
})
})
The response i get and my payment got unsuccessful.
// 20210504063330
// http://localhost:7070/PayPal/PaymentSuccess?paymentId=PAYID-MCIKIRQ60G27157PA787072M&token=EC-
9EU01414K39004833&PayerID=GFYGLAXW36YPW
{
"Error": "Response Status : 400",
"Message": {
"response": {
"name": "VALIDATION_ERROR",
"message": "Invalid request - see details",
"debug_id": "cfeb4eab621c7",
"details": [
{
"field": "/transaction",
"location": "body",
"issue": "MALFORMED_REQUEST_JSON"
}
],
"links": [
],
"httpStatusCode": 400
},
"httpStatusCode": 400
}
}
The v1/payments REST API is deprecated. Use the current v2/checkout/orders API instead.
The best integration uses no redirects, and keeps your site loaded in the background with an in-context approval.
Make two routes on your server, one for 'Create Order' and one for 'Capture Order', documented here. These routes should return only JSON data (no HTML or text). The latter one should (on success) store the payment details in your database before it does the return (particularly purchase_units[0].payments.captures[0].id, the PayPal transaction ID)
Pair those two routes with the following approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server

Apollo Server Express + GraphQL relationships

I am using Express + Apollo Server + GraphQL + Mongoose + MongoDB to "perform" several CRUD operations on a database.
One of the operations I am trying to make is to get the sites from the database and expand its users with their information for each record like this:
query {
getSites {
id
name
owner {
name
email
}
origins
}
}
Instead, I am getting these results:
{
"data": {
"getSites": [{
"id": "5cae36182ab9b94e94ba9af5",
"name": "Test site 1",
"owner": [{
"name": null,
"email": null
}
],
"origins": [
"test1",
"test2"
]
}, {
"id": "5cae3a3798c302247c036544",
"name": "Test site 2",
"owner": [{
"name": null,
"email": null
}
],
"origins": [
"test1",
"test2"
]
}
]
}
}
This is my typeDef code for Site:
import { gql } from 'apollo-server-express';
const site = gql `
extend type Site {
id: ID!
name: String!
origins: [String]
owner: [User]
createdOn: String
updatedOn: String
}
extend type Query {
getSites: [Site]
getSite(id: ID!): Site
}
extend type Mutation {
addSite(name: String!, owner: [String!], origins: [String]): Site
}
`;
export default site;
If I console.log(sites) I see owner is an array of Strings.
Edit:
If I change addSite(name: String!, owner: [User], origins: [String]): Site then I get when compiling:
Error: The type of Mutation.addSite(owner:) must be Input Type but got: [User]
My resolver looks like this:
getSites: async () => await Site.find().exec()
What's the proper way to define relationships today? Thanks.
I just edited my resolver to this:
getSites: async () => {
let sites = await Site.find().exec();
let ownedSites = await User.populate(sites, { path: 'owner' });
return ownedSites;
}
And that solved the errors.

Sails swagger api documentation

I am using sails in my node js application. And want to implement swagger api documentation. And I follow Swagger Sails JS document. I got the result from my api doc. And my expected result from api doc . I have write the route in router.js file like below
'post /login': {
controller: 'user/UserController',
action: 'login',
skipAssets: 'true',
//swagger path object
"get": {
"tags": [
"Users"
],
"description": "Get a login user data",
"parameters": [{
"email": "abc#gmail.com",
"password": "12345678y",
"deviceToken": "12345678y",
"deviceType": 2
}],
"responses": {
"200": {
"statusCode": 0,
"status": true,
"message": "string",
"result": {}
}
}
}
}
If I had write wrong in my routes. Then how to write the routes, so that I will get my expected result from api docs?
Thanks!
You can try using this.
And I suppose router file should be like this:
'post /login': {
controller: 'user/UserController',
action: 'login',
skipAssets: 'true',
swagger: {
methods: ["get"],
tags: ["Users"],
description: "Get a login user data",
parameters: [{
email: "abc#gmail.com",
password: "12345678y",
deviceToken: "12345678y",
deviceType: 2
}],
responses: {
'200': {
statusCode: 0,
status: true,
message: "string",
result: {}
}
}
}
}

Resources