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?
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 set up GraphQL Subscriptions but it seems to get connected to the backend but it's not pushing any updates.
On frontend, I am using Nuxt 2 and that's how I am trying to get it working:
That's my test query
export const pendingInquiresSubscription = () => {
return gql`
subscription PendingInquires {
countPendingInquires {
amount
}
}`
}
My smartQuery on the page component
apollo: {
$subscribe: {
pendingInquires: {
query: pendingInquiresSubscription(),
result({ data, loading }) {
this.loading = loading;
console.log(data)
},
error(err) {
this.$notify({ message: `Что-то пошло не так пытаясь обновить количество новый запросов: ${err.message}`, type: 'error' })
},
}
}
},
Backend:
my pubsub
import { RedisPubSub } from 'graphql-redis-subscriptions';
import Redis from 'ioredis';
const REDIS_DOMAIN_NAME = '127.0.0.1'
const PORT_NUMBER = 6379
const options = {
host: REDIS_DOMAIN_NAME,
port: PORT_NUMBER,
retryStrategy: (times: any) => {
return Math.min(times * 50, 2000);
}
}
export const pubsub = new RedisPubSub({
publisher: new Redis(options),
subscriber: new Redis(options)
})
My Schema:
extend type Subscription {
countPendingInquires: PendingInquires!
}
type PendingInquires {
amount: Int!
}
My resolver
...
Subscription: {
countPendingInquires: {
subscribe: () => pubsub.asyncIterator(['countPendingInquires'])
},
},
...
That's the way I am trying to push the event:
pubsub.publish('countPendingInquires', {
PendingInquires: {
amount: await TelegramInguireModel.find({ }).countDocuments()
}
})
And I also wonder if there is any built-in way to set the initial state for subscriptions.
The issue was in the way I was trying to push the event
The correct way of pushing is like this:
pubsub.publish('countPendingInquires', {
countPendingInquires: { // <- here was the issue
amount: await TelegramInquireModel.find({ }).countDocuments()
}
)
I've just set wrong subscription name
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
}
}
}
I have meet this situation for my requirements:
step 1. save data to local db which in the mobile phone (realm)
step 2. upload the local data to the server, and the server will return the data ids if success
step 3. delete the records in local db by the returned ids which get by step2
Realm.open({schema:[MySchame],encryptionKey:getRealmKey()})
.then(realm =>{
realm.write(() => {
// 1. get all step data from db
let objetcs = realm.objects('MySchema');
// 2. upload obtained data to server
if(objetcs.length > 0){
let recordArr = [];
for (let o of steps){
recordArr.push(o.get());
}
uploadDataToServer(recordArr,(res)=>{
//3. filter the uploaded steps and delete them
let uploadedSteps = realm.objects('MySchema').filtered('id=$0',res.id);
if(uploadedSteps.length > 0){
realm.delete(uploadedSteps);
}
});
}
});
realm.close();
})
.catch(error =>{
console.log(error);
});
but this is not works as expected, it seems DB is closed too early than networks success callback.
Thanks for any ideas.
Finally ,I use realm like this:
let realm = new Realm({schema:[JOB_SCHEMA.jobTrack],encryptionKey:getRealmKey()});
let objects = realm.objects('JobTrack');
realm.beginTransaction();
realm.delete(objects);
realm.commitTransaction();
realm.close();
First create a service like one below
import repository from "./realmConfig";
let CatalogsService = {
findAll: function () {
return repository.objects("CatalogsModel");
},
save: function (catalogs) {
repository.write(() => {
repository.create("CatalogsModel", catalogs);
});
},
delete: function () {
repository.write(() => {
let all = repository.objects("CatalogsModel");
repository.delete(all);
});
},
update: function (catalogs, callback) {
if (!callback) return;
repository.write(() => {
callback();
catalogs.updatedAt = new Date();
});
}
};
module.exports = CatalogsService;
where my realmConfig file is as
import Realm from "realm";
class CatalogsModel extends Realm.Object { }
CatalogsModel.schema = {
name: "CatalogsModel",
primaryKey: "id",
properties: {
id: "string",
name: "string",
url: "string",
status: "int"
}
};
class OffersModel extends Realm.Object { }
OffersModel.schema = {
name: "OffersModel",
primaryKey: "id",
properties: {
id: "string",
name: "string",
url: "string",
status: "int",
machineId: "string",
machineName: "string"
}
};
export default new Realm({
schema: [CatalogsModel, OffersModel],
schemaVersion: 1,
deleteRealmIfMigrationNeeded: true
});
Now import Service.js where you are calling async server call and do your job. For reference see below code
import CatalogService from './path/to/CatalogService .js'
//get objects
var catalogs = CatalogsService.findAll();
// fire async function , I prefer axios for network calls
Axios.post("SERVER_URL", {
data: catalogs
})
.then(function (response) {
if (response.success)
CatalogsService.delete()
}
I assume you can easily modify findAll() and delete() method as per your need
I am trying to fetch data with apollo and then write it to realm. I have created a js file that I know works, because it has worked before. But, when I try to write to a particular model I get an error message. More details as follows:
Code (Not entire code) LocationQuery.js:
const realm = new Realm({ schema: [testBuilding1], schemaVersion: 1 });
let buildingTypeArray = [];
const temp = [];
class LocationQuery extends Component {
static get propTypes() {
return {
data: React.PropTypes.shape({
loading: React.PropTypes.bool,
error: React.PropTypes.object,
sites: React.PropTypes.array,
}).isRequired,
};
}
render() {
if (this.props.data.loading) {
return (null);
}
if (this.props.data.error) {
return (<Text>An unexpected error occurred</Text>);
}
if (this.props.data.sites) {
this.props.data.sites.map((value) => {
buildingTypeArray.push(value.locations);
});
buildingTypeArray.forEach((locationValues) => {
realm.write(() => {
realm.create('testBuilding1', {
building: '273',
});
});
});
}
return null;
}
}
const locationQueryCall = gql`
query locationQueryCall($id: String!){
sites(id: $id){
locations {
building
type
}
}
}`;
const ViewWithData = graphql(locationQueryCall, {
options: props => ({
variables: {
id: 'SCH1',
},
}),
})(LocationQuery);
export default connect(mapStateToProp)(ViewWithData);
The error I get is a big red screen that read:
console.error: "Error in observe.next.... blah blah blah"
The Model I am using:
export const testBuilding1 = {
name: 'testBuilding1',
properties: {
building: 'string',
},
};
The weird thing is that the code works when I use this model:
export const locationScene = {
name: 'locationScene',
properties: {
building: 'string',
},
};
I am calling LocationQuery.js in another piece of code passing it through at render.
Thank you in advance for the help!