I'm using expressjs and apollo-server-express. I'm trying to set up a query in graphql to return a product from my database. The problem is that the results never show up in graphql, but when I console log resultsArr the results show up fine. Just to note the resultsArr is an array of objects.
Express:
const typeDefs = gql`
type Search {
brand: String
title: String
url: String
thumbnail: String
}
type Query {
results(query: String!): Search
}
`;
const resolvers = {
Query: {
results: (parent, args) => {
const queries = [
{
indexName: 'products',
query: args.query,
params: {
hitsPerPage: 1,
},
},
//
];
return AlgoliaClient.multipleQueries(queries).then(({ results }) => {
// Store Results
const resultsArr = [];
results.forEach((item) => {
resultsArr.push(item.hits[0]);
});
// console logging this shows the products
return resultsArr;
});
},
},
};
and my query the graphql playground is:
query Search {
results(query: "Test product") {
title
}
}
The problem is when I console log resultsArr the products show up no problem, however when it try it though the query I get:
{
"data": {
"results": {
"title": null
}
}
}
Related
I'm trying to make graphql query calls using apollo on NuxtJS and I'm getting the following error.
WARN Missing field description in { 11:29:49
"__typename": "EduExp"
}
WARN Missing field componentName in { 11:29:49
"__typename": "EduExp"
}
{ 11:29:49
data: null,
loading: false,
networkStatus: 7,
stale: true
}
Here is my query
fragment IntroCardFields on IntroCard {
legend
profile {
title
url
}
introList
description {
json
}
componentName
}
query getPage($pageId: String!) {
page(id: $pageId) {
slug
name
componentsCollection {
items {
...IntroCardFields
}
}
}
}
I'm using it like this in vuex
async fetchPageData({ commit, state }) {
const apollo = this.app.apolloProvider.defaultClient;
const pageData = [];
const res = await apollo.query({
query: getPage,
variables: {
pageId: '2S3x7vBmaB2FhTUbNXWvwY',
},
});
console.log(res);
},
When I try this query without parameters on a api tool like postman or insomnia works well.
I don't get it why not working on Nuxt
I am trying to pull some data from my pinned repos using the github v4 API within Nuxt.js I have set up the following as per the docs:
buildModules: [
'#nuxtjs/eslint-module',
'#nuxtjs/tailwindcss',
'#nuxtjs/color-mode',
'#nuxtjs/apollo',
],
apollo: {
clientConfigs: {
default: {
httpEndpoint: 'https://api.github.com/graphql',
authenticationType: 'Bearer',
tokenName: process.env.GITHUB_TOKEN,
},
},
},
My query in another component is:
export default {
apollo: {
opensource: gql`
query github {
user(login: "mrpbennett") {
pinnedItems(first: 6, types: REPOSITORY) {
edges {
node {
... on GitHub_Repository {
name
description
url
primaryLanguage {
name
color
}
}
}
}
}
}
}
`,
},
But I am getting the following Network error: Response not successful: Received status code 401 which presents me with
function ApolloError(_a) {
var graphQLErrors = _a.graphQLErrors,
networkError = _a.networkError,
errorMessage = _a.errorMessage,
extraInfo = _a.extraInfo;
var _this = _super.call(this, errorMessage) || this;
_this.graphQLErrors = graphQLErrors || [];
_this.networkError = networkError || null;
if (!errorMessage) {
_this.message = generateErrorMessage(_this);
} else {
_this.message = errorMessage;
}
_this.extraInfo = extraInfo;
_this.__proto__ = ApolloError.prototype;
return _this;
}
Within file bundle.umd.js
I know the query works as I have used the same one within Gatsby. Any ideas where I am going wrong with the authentication?
In Nuxt.js, I'm trying to do a query like this with the nuxt apollo-module based in vue-apollo
apollo: {
magazines: {
query: gql`query($id: String!) {
magazines( where: { url_contains:$id })
{
url
title
thumbnail
}
}`,
prefetch: ({ route }) => ({ id: route.params.id }),
variables() {
return {
id: this.$route.params.id
}
}
}
The query is sent, but the variable $id is sent unrendered (in the petition, I can see query($id: String!)—instead of query('my-page-route': String!)— and where: { url_contains:$id } as it is—instead of where: { url_contains:'my-page-route' }
The query is surprisingly valid, as it responds with all the items in the db —so it doesn't apply the where: { url_contains:$id }
I have tried with query($id: String) but that doesn't change anything. Any hints about what could be going wrong?
Thanks in advance!
In my vue screen I'd like to use one apollo graphql I've defined for two properties. As far as I understand the name of the property must match a name of the attribute in the returned json structure.
I naivly tried to use the queries for two properties but it throws an error for the second one.
...
data() {
return {
userId: number,
user: null as User | null,
previousUserId: number,
previousUser: null as User | null
};
},
...
apollo {
user: {
query: READ_ONE_USER,
variables() {
return {
userId: this.userId
};
}
},
previousUser: {
query: READ_ONE_USER,
variables() {
return {
userId: this.previousUserId
};
},
export const READ_ONE_USER = gql(`
query user($userId: Int!) { user(userId: $userId)
{
id
firstName
lastName
email
}
}
`);
I expected no problems but I get "Missing previousUser attribute on result {user: ...}"
Daniel's solution didn't work out for me, I still got the same error message.
But there's another way to do it, you can provide an update function to tell apollo how to extract the result out of the data read from the server:
apollo {
user: {
query: READ_ONE_USER,
variables() {
return {
userId: this.userId
};
}
},
previousUser: {
query: READ_ONE_USER,
variables() {
return {
userId: this.previousUserId
};
},
update(data) {
return data.user;
}
}
This is documented at https://github.com/vuejs/vue-apollo/blob/v4/packages/docs/src/api/smart-query.md#options
As shown in the docs, you can manually add smart queries inside the created hook:
created () {
this.$apollo.addSmartQuery('user', {
query: READ_ONE_USER,
variables() {
return {
userId: this.userId
};
},
})
this.$apollo.addSmartQuery('previousUser', {
query: READ_ONE_USER,
variables() {
return {
userId: this.previousUserId
};
},
})
}
I would like to create a checkout object via the GraphQL API provided by the Saleor eCommerce platform.
According to the gql playground there is a mutation to do so that takes a CheckoutCreateInput object as it's argument.
Here is an example mutation that works fine within the playground.
Here is the current code that I have tried (I am doing this within a vuex action)
export const actions = {
addToCart({ commit, dispatch }, cartItem) {
const currentCartItems = this.state.cartItems
// Check to see if we already have a checkout object
if (this.state.checkoutId !== '') {
// Create a new checkout ID
console.log('creating new checkout object')
try {
this.app.apolloProvider.defaultClient
.mutate({
mutation: CREATE_CART_MUTATION,
variables: {
checkoutInput: {
lines: { quantity: 10, variantId: 'UHJvZHVjdFZhcmlhbnQ6NQ==' },
email: 'test#test.com'
}
}
})
.then(({ data }) => {
console.log(data)
})
} catch (e) {
console.log(e)
}
} else {
console.log('checkout id already set')
}
// TODO: Check to see if the cart already contains the current Cart Item
commit('ADD_CART_ITEM', cartItem)
}
and here is the CREATE_CART_MUTATION:
import gql from 'graphql-tag'
export const CREATE_CART_MUTATION = gql`
mutation($checkoutInput: CheckoutCreateInput!) {
checkoutCreate(input: $checkoutInput) {
checkout {
id
created
lastChange
lines {
id
variant {
id
name
}
quantity
totalPrice {
gross {
localized
}
net {
localized
}
}
}
totalPrice {
gross {
localized
}
net {
localized
}
}
}
}
}
`
On the server this comes back with the following error:
graphql.error.base.GraphQLError: Variable "$checkoutInput" got invalid value {"email": "test#test.com", "lines": {"quantity": 10, "variantId": "UHJvZHVjdFZhcmlhbnQ6NQ=="}}.
In field "lines": In element #0: Expected "CheckoutLineInput", found not an object.
Looks like I was most of the way there, I was just passing a single lines object rather than an array of them. The correct code is as follows:
try {
this.app.apolloProvider.defaultClient
.mutate({
mutation: CREATE_CART_MUTATION,
variables: {
checkoutInput: {
lines: [
{ quantity: cartItem.quantity, variantId: cartItem.variantId }
],
email: 'test#test.com'
}
}
})
.then(({ data }) => {
console.log('mutation done!')
commit('SET_CHECKOUT_OBJECT', data.checkoutCreate.checkout)
})
} catch (e) {
console.log('error:')
console.log(e)
}