Trying to pass parameter with graph ql query getting an error - javascript

I have below graphl api query that i am using to send the data from react front app with the object to get the desired results
{
allSectionRequests(data:{
requestStageName:"Request Submitted"
}){
section
type
}
}
and then i am trying to pass variable from react like below
export const GET_SECTIONREQUESTS = gql`
query AllSectionRequests($data: sectionRequestParamsInput){
allSectionRequests(data: $data){
section
type
}
}
`;
I have attached the image that i need to send to graphql api below
and the below is the react code that i will be calling query inside component and then passing data object to graphql api
const { data: dashBoardData, loading: dashBoardDataLoading, error: dashBoardDataError } = useQuery(GET_SECTIONREQUESTS, {
variables: { data: { requestStageName: 'Request Submitted' } },
});
I am getting error like this below
The variable **data** type is not compatible with the type of the argument **data**.
↵Expected type: SectionRequestParamsInput.
i am not sure where i am doing wrong with this code, could any one please help on this one .
Many thanks

I have rectified my problem with the below solution
export const GET_SECTIONREQUESTS = gql`
query AllSectionRequests($sectionRequestParamsInput: SectionRequestParamsInput){
allSectionRequests(data: $sectionRequestParamsInput){
id
section
type
createdBy
description
status
age
}
}
`;
and then changed my input parameters in react like this
const { data: dashBoardData, loading: dashBoardDataLoading, error: dashBoardDataError } = useQuery(GET_SECTIONREQUESTS, {
variables: { sectionRequestParamsInput: { requestStageName: 'Request Submitted' } },
});
i hope this will helps to any person who is looking for graphql api query with parameters passed in.

Related

Can't pass array from react to django

I m trying to get an array from react frontend (stored in local storage) to my view class in django but i'm getting this error:
In console:
GET http://127.0.0.1:8000/api/quiz/multiple/ 500 (Internal Server Error)
Django LOGS:
for quiz in quizzes:
TypeError: 'NoneType' object is not iterable
ERROR:django.server:"GET /api/quiz/multiple/ HTTP/1.1" 500 20064
Here's how i store the data in the LocalStorage:
localStorage.setItem('quizzes', JSON.stringify(quizList));
history.push('/start')
And here's how i get it from local storage and pass it to the django using axios:
export default function QuizPage() {
const [DataState,setDataState] = useState([]);
const storedQuizzes = JSON.parse(localStorage.getItem("quizzes"))
useEffect(() => {
axiosInstance
.get(`quiz/multiple/`, {
quizzes: storedQuizzes
}).then((res) => {
setDataState(res.data);
})
.catch((function (error) {
console.log(error)
}));
}, [setDataState]);
and, finally, that's my django view:
class MultipleQuizView(APIView):
permission_classes = [IsAuthenticated]
def get(self,request):
questionsList = []
quizzes = request.data.get('quizzes')
for quiz in quizzes:
currentQuiz = Quiz.objects.get(url=quiz)
quizSerializer = QuizSerializerForMultipleQuizzes(currentQuiz)
question = Question.objects.filter(quiz__url=quiz)
questionSerializer = QuestionSerializer(question, many=True)
quizSerializerData = quizSerializer.data.copy()
quizSerializerData["questions"]=questionSerializer.data
questionsList.append(quizSerializerData)
if questionsList:
return Response(questionsList)
else:
return Response(status=status.HTTP_400_BAD_REQUEST)
I'm pretty sure the problem isn't from my view class because i tested it using Postman and it works without any problem.
EDIT:
I just tryed with postman using this body and it works properly:
https://i.stack.imgur.com/3RJ5A.png
So i need to send data from react like this but i don't know how:
{
"quizzes":["securitate","aparare"]
}
Try changing the second param to axios.get as follows:
axiosInstance
.get(`quiz/multiple/`, {
params: {
quizzes: storedQuizzes
}
}).then(...)
Read more about the properties that the second param supports.
SOLVED!
The problem was that i wrote:
quizzes = request.data('quizzes')
instead of:
quizzes = request.data['quizzes']

Unexpected error when querying for a field from Firebase

I am using React.js to query a field in a document from Firebase. However, when I try to get the data, I keep getting an error. The code, the collection on Firestore, and and the error message are below. How do I properly query specific fields of data without running into this error?
import React from 'react';
import styled from 'styled-components';
import { firestore } from '../../firebase/firebase.utils';
class Economics extends React.Component {
constructor() {
super();
this.state = {
name: firestore.collection('blog-categories').doc('8uVaHd22tT5oXSzpOOuj').get('name')
}
}
render() {
return (
<div>
hi
</div>
)
}
}
export default Economics;
I think this is proper reference for the API you are using.
When you enter parameter to get method API is expecting options object, so when you enter String "name" there you will get this error massage.
The method is asynchronous so you have to take value form DocumentSnapshot (reference) object returned as Promise which result of the method.
I hope it will help!
UPDATE: As requested I'm adding example:
Firestore has collection collection1 with document doc1 that has field field1 with value 'value1':
var Firestore = require('#google-cloud/firestore');
var db = new Firestore();
var docRef = db.collection("collection1").doc("doc1");
docRef.get().then(docSnap => {
console.log(docSnap.data().field1);
console.log(docSnap.get("field1"));
});
If you run this in node result is:
value1
value1

How to check if object exists in mLab using _id?

I am working on an angular application with a node.js backend where my architecture goes like this:
front-end => angular.service => node backend => mLab DB
Currently, I'm trying to push an object into the DB provided that it does not exist yet. If it already does, it should update. This function would be accessible via a button from the cards in my front-end.
to give a clearer understanding here's some of my code.
front-end: admin-edit-home.component.html
<a mdbBtn class='btn btn-md btn-primary' mdbWavesEffect (click)="addCard()">Add</a>
the code above is a button where I can add a card to the interface. The TS below shows how the code works.
front-end: admin-edit-home.component.ts
addCard() {
this.carousels.push(this.carousels.length);
}
To give an explanation of the TS code, 'carousels' is an array that I use to do an *ngFor loop in my HTML wherein it presents the data in a card format. It is declared as:
carousels: any = [];
So in pushing a length to the 'carousels' array, it present an empty card with no collected data but still possessing the HTML elements from the original card which contains the supposed update function that I would like to have.
My problem is, how do I do the checking of the object existence from the back-end and present the results back to the front-end? I have tried this,
back-end: api.js
router.route('/carousel/update/:id').put(function(req,res) {
var data = req.body;
const myquery = { _id: ObjectId(req.params.id) };
db.collection('home').updateOne(myquery, {
$set: {
"header" : data.header,
"subheader" : data.subheader,
"img" : data.img
}
})
if (myquery === -1) {
arr.push(obj);
} else {
arr[myquery] = obj
}
}
I know my back-end code is wrong and non-functional but I just wanted to let you guys have a visualisation of what my logic is trying to achieve.
Furthermore, this back-end code should now be accessible by my angular service through this chunk of code below:
home.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable ({
providedIn: 'root'
})
export class HomeService {
constructor(private http: HttpClient) {}
updateCard(id: string, header: string, subheader: string, img: string) {
var json = {id: id, header: header, subheader: subheader, img: img}
return this.http.put<any[]>(`./api/carousel/update/${id}`, json);
}
}
After trying these things, to sum up my problem in a more concise manner, I need to check from the database if the object is already existing via ObjectId and then update it through my input fields but if not, the updateCard() should create another object in my database. I hope to get help!
EDIT
router.route('/carousel/update/:id').put(function (req, res) {
var data = req.body;
const myquery = { "_id": ObjectId };
// console.log('header: ' + data.header + " id: " + data.id)
console.log(req.params)
db.collection("home").updateMany(myquery, {
$set: {
"img" : data.img,
"header" : data.header,
"subheader": data.subheader
}
}, (err, results) => {
res.status(200).json({status: "ok"})
})
})
This is the new api.js. Please refer.

Feathers-mongoose : Get by custom attribute in feathers-mongoose

I have a very basic feathers service which stores data in mongoose using the feathers-mongoose package. The issue is with the get functionality. My model is as follows:
module.exports = function (app) {
const mongooseClient = app.get('mongooseClient');
const { Schema } = mongooseClient;
const messages = new Schema({
message: { type: String, required: true }
}, {
timestamps: true
});
return mongooseClient.model('messages', messages);
};
When the a user runs a GET command :
curl http://localhost:3030/messages/test
I have the following requirements
This essentially tries to convert test to ObjectID. What i would
like it to do is to run a query against the message attribute
{message : "test"} , i am not sure how i can achieve this. There is
not enough documentation for to understand to write or change this
in the hooks. Can some one please help
I want to return a custom error code (http) when a row is not found or does not match some of my criterias. How can i achive this?
Thanks
In a Feathers before hook you can set context.result in which case the original database call will be skipped. So the flow is
In a before get hook, try to find the message by name
If it exists set context.result to what was found
Otherwise do nothing which will return the original get by id
This is how it looks:
async context => {
const messages = context.service.find({
...context.params,
query: {
$limit: 1,
name: context.id
}
});
if (messages.total > 0) {
context.result = messages.data[0];
}
return context;
}
How to create custom errors and set the error code is documented in the Errors API.

Graphql react-apollo IntrospectionFragmentMatcher

I'm using GitHub Graphql API and I wrote following code with react-apollo but when I paginate after many requests I get following errors on the console.
You are using the simple (heuristic) fragment matcher, but your queries contain union or interface types. Apollo Client will not be able to accurately map fragments. To make this error go away, use the IntrospectionFragmentMatcher as described in the docs: https://www.apollographql.com/docs/react/recipes/fragment-matching.html
.
WARNING: heuristic fragment matching going on!
.
Missing field name in {
"__typename": "Organization"
}
Missing field avatarUrl in {
"__typename": "Organization"
}
Missing field repositories in {
"__typename": "Organization"
}
and I wrote the following codes:
gql`
query($username: String!, $nextPage: String) {
search(query: $username, type: USER, first: 100, after: $nextPage) {
pageInfo {
hasNextPage
endCursor
}
edges {
node {
... on User {
name
avatarUrl
repositories {
totalCount
}
}
}
}
}
}
`;
handleSubmit = ({ username }) => {
const { client } = this.props;
this.setState({
loading: true,
searchTerm: username,
});
client
.query({
query: SEARCH_USER,
variables: {
username
}
})
.then(({ data }) => {
this.setState({
loading: false,
searchList: data.search.edges,
pagination: data.search.pageInfo,
});
})
.catch(err => {
console.warn(err);
});
};
Because Apollo has not enough information about your GraphQL Schema you need to provide it somehow. Apollo has a well written documentation on that topic.
It describes to use a script to introspect your GraphQL Server in order to get that missing information about Unions and Interfaces.
To make the process even easier I wrote a plugin for GraphQL Code Generator that automates everything. There's a chapter called "Fragment Matcher" that I recommend to read.
Either first, the manual solution or the second should fix your problem :)

Categories