Http Headers vue-apollo - vue.js

👩‍💻,
I have see many articles of how to use headers in apollo with context options but I don't know how to make it work in vue-apollo , is already other isssue in github about these (https://github.com/vuejs/vue-apollo/issues/713) config the vue-apollo.js, but I want to use headers to individuals querys, ÂżIs these possible?.
My Query with vue-apollo:
apollo:{
getPipedrivePersons: {
query: gql`query{
getPipedrivePersons(
term:"email"
){
id
name
detail{
firstName
lastName
}
email{
value
}
phone{
value
}
}
}
`,
pollInterval: 950,
},
}

solved by using context:
context: {
headers: { foo: this.fooHeader }
}

Related

Calling function in VueApollo after API response

I am using Vue and Apollo and I am making a querie that looks just like the box below.
After I get the API response, I would like to call a method from my methods object. However Vue, doesn't give me acess to it within apollo object.
I would like to know how can I call one of my methods, but only after I am sure I got that response, without having to manually trigger it with a button or something else.
apollo: {
materials: {
query: gql`
query allMaterials($tenantId: ID, $name: String) {
tenantMaterials(tenantId: $tenantId, name: $name) {
edges {
node {
name
materialType {
name
id
}
brand
vendor
size
unit
inventory
createdAt
updatedAt
isActive
updatedBy
id
}
}
totalCount
}
}
`,
variables() {
return {
name: null
};
},
fetchPolicy: "cache-and-network",
update: response => {
return response.tenantMaterials.edges;
//I want to call a function/method after this response
},
skip: false
},
}
Use update(data) or result(result, key)
update(data) {return ...} to customize the value that is set in the
vue property, for example if the field names don't match.
result(ApolloQueryResult, key) is a hook called when a result is
received (see documentation for ApolloQueryResult (opens new window)).
key is the query key in the apollo option.
https://apollo.vuejs.org/api/smart-query.html

Fetching nearest events with user location using meetup.com GraphQL API

I am trying to find out a way to fetch nearby events using GraphQL meetup.com API. After digging into the documentation for quite some time, I wasn't able to find a query that suits my needs. Furthermore, I wasn't able to find old, REST, documentation, where, the solution for my case might be present.
Thanks in advance !
This is what I could figure out so far, the Documentation for SearchNode is missing, but I could get id's for events:
query($filter: SearchConnectionFilter!) {
keywordSearch(filter: $filter) {
count
edges {
cursor
node {
id
}
}
}
}
Input JSON:
{ "filter" : {
"query" : "party",
"lat" : 43.8,
"lon" : -79.4, "radius" : 100,
"source" : "EVENTS"
}
}
Hope that helps. Trying to figure out this new GraphQL API
You can do something like this (customize it with whatever fields you want from Event):
const axios = require('axios');
const data = {
query: `
query($filter: SearchConnectionFilter!) {
keywordSearch(filter: $filter) {
count
edges {
cursor
node {
id
result {
... on Event {
title
eventUrl
description
dateTime
going
}
}
}
}
}
}`,
variables: {
filter: {
query: "party",
lat: 43.8,
lon: -79.4,
radius: 100,
source: "EVENTS",
},
},
};
axios({
method: "post",
url: `https://api.meetup.com/gql`,
headers: {
Authorization: `Bearer YOUR_OAUTH_ACCESS_TOKEN`,
},
data,
})

BigCommerce Stencil - GraphQL query using front matter not returning anything

I'm not sure if it's a bug, but I'm not able to make GraphQL work in the Cornerstone template. I'm expecting an error or something getting returned at least, but nothing is being rendered at all from gql.
I am on the pages/product.html template, and I even tried this example from the docs:
---
product:
videos:
limit: {{theme_settings.productpage_videos_count}}
reviews:
limit: {{theme_settings.productpage_reviews_count}}
related_products:
limit: {{theme_settings.productpage_related_products_count}}
similar_by_views:
limit: {{theme_settings.productpage_similar_by_views_count}}
gql: "query productById($productId: Int!) {
site {
product(entityId: $productId) {
variants(first: 25) {
edges {
node {
sku
defaultImage {
url(width: 1000)
}
}
}
}
}
}
}
"
My goal is to have access to the paths/URL on each of the product's category because product.category is just an array of category names. Here's the query I am able to make work on the GraphQL playground (86 to be replaced by $productId in the front matter GraphQL query, I think?):
query getProductCategories {
site {
product(entityId: 86) {
categories {
edges {
node {
name
path
}
}
}
}
}
}
If there's no way around this, maybe I'll just try to do the fetching in the client side.
This now works correctly, as of 20-Sep-2021.
There was a bug, tracked as an issue here: https://github.com/bigcommerce/stencil-cli/issues/732 which has been resolved and closed.

How to access parameter from graphql query

Using DatoCMS, with VueJS and gridsome. The page query looks like
<page-query>
{
DatoCms {
_site {
globalSeo {
facebookPageUrl
siteName
titleSuffix
twitterAccount
fallbackSeo {
description
title
twitterCard
image {
url
}
}
}
}
}
}
</page-query>
Below does not work to get the values from the query
export default {
metaInfo: {
title: this.$page.DatoCms._site[0].globalSeo.fallbackSeo.title,
the query needed to be adjusted and metainfo method updated

Get GraphQL whole schema query

I want to get the schema from the server.
I can get all entities with the types but I'm unable to get the properties.
Getting all types:
query {
__schema {
queryType {
fields {
name
type {
kind
ofType {
kind
name
}
}
}
}
}
}
How to get the properties for type:
__type(name: "Person") {
kind
name
fields {
name
type {
kind
name
description
}
}
}
How can I get all types with the properties in only 1 request? Or ever better: How can I get the whole schema with the mutators, enums, types ...
Update
Using graphql-cli is now the recommended workflow to get and update your schema.
The following commands will get you started:
# install via NPM
npm install -g graphql-cli
# Setup your .graphqlconfig file (configure endpoints + schema path)
graphql init
# Download the schema from the server
graphql get-schema
You can even listen for schema changes and continuously update your schema by running:
graphql get-schema --watch
In case you just want to download the GraphQL schema, use the following approach:
The easiest way to get a GraphQL schema is using the CLI tool get-graphql-schema.
You can install it via NPM:
npm install -g get-graphql-schema
There are two ways to get your schema. 1) GraphQL IDL format or 2) JSON introspection query format.
GraphQL IDL format
get-graphql-schema ENDPOINT_URL > schema.graphql
JSON introspection format
get-graphql-schema ENDPOINT_URL --json > schema.json
or
get-graphql-schema ENDPOINT_URL -j > schema.json
For more information you can refer to the following tutorial: How to download the GraphQL IDL Schema
This is the query that GraphiQL uses (network capture):
query IntrospectionQuery {
__schema {
queryType {
name
}
mutationType {
name
}
subscriptionType {
name
}
types {
...FullType
}
directives {
name
description
locations
args {
...InputValue
}
}
}
}
fragment FullType on __Type {
kind
name
description
fields(includeDeprecated: true) {
name
description
args {
...InputValue
}
type {
...TypeRef
}
isDeprecated
deprecationReason
}
inputFields {
...InputValue
}
interfaces {
...TypeRef
}
enumValues(includeDeprecated: true) {
name
description
isDeprecated
deprecationReason
}
possibleTypes {
...TypeRef
}
}
fragment InputValue on __InputValue {
name
description
type {
...TypeRef
}
defaultValue
}
fragment TypeRef on __Type {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
}
}
}
}
}
}
}
}
You can use GraphQL-JS's introspection query to get everything you'd like to know about the schema:
import { introspectionQuery } from 'graphql';
If you want just the information for types, you can use this:
{
__schema: {
types: {
...fullType
}
}
}
Which uses the following fragment from the introspection query:
fragment FullType on __Type {
kind
name
description
fields(includeDeprecated: true) {
name
description
args {
...InputValue
}
type {
...TypeRef
}
isDeprecated
deprecationReason
}
inputFields {
...InputValue
}
interfaces {
...TypeRef
}
enumValues(includeDeprecated: true) {
name
description
isDeprecated
deprecationReason
}
possibleTypes {
...TypeRef
}
}
fragment InputValue on __InputValue {
name
description
type { ...TypeRef }
defaultValue
}
fragment TypeRef on __Type {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
}
}
}
}
}
}
}
}
`;
If that seems complicated, it's because fields can be arbitrarility deeply wrapped in nonNulls and Lists, which means that technically even the query above does not reflect the full schema if your fields are wrapped in more than 7 layers (which probably isn't the case).
You can see the source code for introspectionQuery here.
Using apollo cli:
npx apollo schema:download --endpoint=http://localhost:4000/graphql schema.json
Update
After getting sick of modifying my previous script all the time, I caved and made my own CLI tool gql-sdl. I still can't find a different tool that can download GraphQL SDL with zero config but would love for one to exist.
Basic usage:
$ gql-sdl https://api.github.com/graphql -H "Authorization: Bearer ghp_[redacted]"
directive #requiredCapabilities(requiredCapabilities: [String!]) on OBJECT | SCALAR | ARGUMENT_DEFINITION | INTERFACE | INPUT_OBJECT | FIELD_DEFINITION | ENUM | ENUM_VALUE | UNION | INPUT_FIELD_DEFINITION
"""Autogenerated input type of AbortQueuedMigrations"""
input AbortQueuedMigrationsInput {
"""The ID of the organization that is running the migrations."""
ownerId: ID!
"""A unique identifier for the client performing the mutation."""
clientMutationId: String
}
...
The header argument -H is technically optional but most GraphQL APIs require authentication via headers. You can also download the JSON response instead (--json) but that's a use case already well served by other tools.
Under the hood this still uses the introspection query provided by GraphQL.js, so if you're looking to incorporate this functionality into your own code see the example below.
Previous answer
Somehow I wasn't able to get any of the suggested CLI tools to output the schema in GraphQL's Schema Definition Language (SDL) instead of the introspection result JSON. I ended up throwing together a really quick Node script to make the GraphQL library do it for me:
const fs = require("fs");
const { buildClientSchema, getIntrospectionQuery, printSchema } = require("graphql");
const fetch = require("node-fetch");
async function saveSchema(endpoint, filename) {
const response = await fetch(endpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ query: getIntrospectionQuery() })
});
const graphqlSchemaObj = buildClientSchema((await response.json()).data);
const sdlString = printSchema(graphqlSchemaObj);
fs.writeFileSync(filename, sdlString);
}
saveSchema("https://example.com/graphql", "schema.graphql");
getIntrospectionQuery() has the complete introspection query you need to get everything, and then buildClientSchema() and printSchema() turns the JSON mess into GraphQL SDL.
Wouldn't be too difficult to make this into a CLI tool itself but that feels like overkill.
You can use the Hasura's graphqurl utility
npm install -g graphqurl
gq <endpoint> --introspect > schema.graphql
# or if you want it in json
gq <endpoint> --introspect --format json > schema.json
Full documentation: https://github.com/hasura/graphqurl
You can download a remote GraphQL server's schema with the following command. When the command succeeds, you should see a new file named schema.json in the current working directory.
~$ npx apollo-cli download-schema $GRAPHQL_URL --output schema.json
You can use GraphQL-Codegen with the ast-plugin
npm install --save graphql
npm install --save-dev #graphql-codegen/cli
npx graphql-codegen init
Follow the steps to generate the codegen.yml file
Once the tool is installed, you can use the plugin to download the schema which is schema-ast
The best is to follow the instruction on the page to install it… but basically:
npm install --save-dev #graphql-codegen/schema-ast
Then configure the codegen.yml file to set which schema(s) is/are the source of truth and where to put the downloaded schema(s) file:
schema:
- 'http://localhost:3000/graphql'
generates:
path/to/file.graphql:
plugins:
- schema-ast
config:
includeDirectives: true
I was also looking and came across this Medium article on GraphQL
The below query returned many details regarding schema, queries and their input & output params type.
fragment FullType on __Type {
kind
name
fields(includeDeprecated: true) {
name
args {
...InputValue
}
type {
...TypeRef
}
isDeprecated
deprecationReason
}
inputFields {
...InputValue
}
interfaces {
...TypeRef
}
enumValues(includeDeprecated: true) {
name
isDeprecated
deprecationReason
}
possibleTypes {
...TypeRef
}
}
fragment InputValue on __InputValue {
name
type {
...TypeRef
}
defaultValue
}
fragment TypeRef on __Type {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
}
}
}
}
}
}
}
}
query IntrospectionQuery {
__schema {
queryType {
name
}
mutationType {
name
}
types {
...FullType
}
directives {
name
locations
args {
...InputValue
}
}
}
}
You can use IntelliJ plugin JS GraphQL then IDEA will ask you create two files "graphql.config.json" and "graphql.schema.json"
Then you can edit "graphql.config.json" to point to your local or remote GraphQL server:
"schema": {
"README_request" : "To request the schema from a url instead, remove the 'file' JSON property above (and optionally delete the default graphql.schema.json file).",
"request": {
"url" : "http://localhost:4000",
"method" : "POST",
"README_postIntrospectionQuery" : "Whether to POST an introspectionQuery to the url. If the url always returns the schema JSON, set to false and consider using GET",
"postIntrospectionQuery" : true,
"README_options" : "See the 'Options' section at https://github.com/then/then-request",
"options" : {
"headers": {
"user-agent" : "JS GraphQL"
}
}
}
After that IDEA plugin will auto load schema from GraphQL server and show the schema json in the console like this:
Loaded schema from 'http://localhost:4000': {"data":{"__schema":{"queryType":{"name":"Query"},"mutationType":{"name":"Mutation"},"subscriptionType":null,"types":[{"kind":"OBJECT","name":"Query","description":"","fields":[{"name":"launche
Refer to https://stackoverflow.com/a/42010467/10189759
Would like to point out that if authentications are needed, that you probably cannot just use the config file generated from graphql init
You might have to do something like this, for example, using the github graphql API
{
"projects": {
"graphqlProjectTestingGraphql": {
"schemaPath": "schema.graphql",
"extensions": {
"endpoints": {
"dev": {
"url": "https://api.github.com/graphql",
"headers": {
"Authorization": "Bearer <Your token here>"
}
}
}
}
}
}
}
If you want to do it by your self, read these code:
There is a modular state-of-art tool 「graphql-cli」, consider looking at it. It uses package 「graphql」's buildClientSchema to build IDL .graphql file from introspection data.
graphql-cli get-schema :integrated into graphql-cli part 1
graphql-config EndpointsExtension :integrated into graphql-cli part 2
The graphql npm package's IntrospectionQuery does
query IntrospectionQuery {
__schema {
queryType {
name
}
mutationType {
name
}
subscriptionType {
name
}
types {
...FullType
}
directives {
name
description
locations
args {
...InputValue
}
}
}
}
fragment FullType on __Type {
kind
name
description
fields(includeDeprecated: true) {
name
description
args {
...InputValue
}
type {
...TypeRef
}
isDeprecated
deprecationReason
}
inputFields {
...InputValue
}
interfaces {
...TypeRef
}
enumValues(includeDeprecated: true) {
name
description
isDeprecated
deprecationReason
}
possibleTypes {
...TypeRef
}
}
fragment InputValue on __InputValue {
name
description
type {
...TypeRef
}
defaultValue
}
fragment TypeRef on __Type {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
}
}
}
}
}
}
}
}
source
You could use apollo codegen:client. See https://github.com/apollographql/apollo-tooling#apollo-clientcodegen-output