Implementing express graphql api with Gatsby graphql - express

So I am building an app using express js ,graphql, postgres and react. And I have already build my backend but now instead of using react, I want to use GatsbyJs how do I connect my express graphiql with my Gatsby graphiql or send my data directly to Gatsby graphiql

Add the following in gatsby-config.js
module.exports = {
plugins: [
{
resolve: "gatsby-source-graphql",
options: {
// This type will contain remote schema Query type
typeName: "MyGraph",
// This is the field under which it's accessible
fieldName: "myGraph",
// URL to query from
url: "http://localhost:4000/graphql",
},
},
],
}
Then in say index.js make the query
export const query = graphql
query {
myGraph {
users {
name
age
}
}
}

Related

How do I get only a defined amount of attributes of my Express API with a browser?

Let me give an example: By accessing the following page we have access to all JSON code: https://jsonplaceholder.typicode.com/todos
But if I want I can retrieve just the first 6 elements of the JSON by accessing the following: https://jsonplaceholder.typicode.com/todos?_limit=6
I want to do this same thing with my Express code that I am accessing with http://localhost:3100
When I try http://localhost:3100?_limit=6 it brings the entire JSON file, I don't understand why. How can I fix this? I want the browser to be able to limit the amount that it gets from the API.
Here is my Express code:
const express = require("express");
const app = express();
const projects = [
{ project: "Challenges_jschallenger.com" },
{ project: "Using-Studio-Ghilis-API-With-JS-Only" },
{ project: "my-portfolio-next" },
{ project: "Youtube-Navbar-2021" },
{ project: "Mana-raWozonWebsite" },
{ project: "Movies-Website" },
{ project: "Add-Remove-Mark-and-Mark-off-With-ReactJS" },
{ project: "My-Portfolio" },
{ project: "Github_Explorer" },
{ project: "MestreALMO.github.io" },
{ project: "Tests-With-useState-useEffect-useRef" },
{ project: "Tic-Tac-Toe-React-in-JS" },
{ project: "ReactJS-with-TypeScript-Template" },
{ project: "Retractable-Accordion" },
];
app.get("/", function (req, res) {
res.send(projects);
});
app.listen(3100);
You need to extract the query from the express request. Also the correct way to respond with a json object would be to call the json method.
app.get("/", (req, res) => {
const { limit } = req.query
res.json(projects.slice(0, limit))
})
For it to work you would have to make the request to http://localhost:3100/?limit=6

Why does apollo muation return "Expecting a parsed GraphQL document" inside vuex?

I am trying to execute an apollo mutation from vuex actions. But it always returns this error :
Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a "gql" tag? http://docs.apollostack.com/apollo-client/core.html#gql
This is how I imported the GraphQL file:
import addReservationGql from "#/gql/mutation/addReservation.gql";
Here is the GeaphQL mutation file:
mutation addReservation($reservation:ResrevationInput){
addReservation(reservation:$reservation){
code
success
message
reservation{
createdAt
numberOfPeople
desiredDate
desiredTime
reservationStatus
}
}
}
Here is my mutation call inside vuex actions:
async submitReservation({ state, commit }) {
const userId = this.$cookies.get("user-id");
const reservation = {
numberOfPeople: state.numberOfPeople,
desiredDate: state.reservationDate,
desiredTime: state.reservationTime,
reservedBy: userId
};
try {
let client = this.app.apolloProvider.defaultClient;
const response = await client.mutate({
mutation: addReservationGql,
variables: { reservation }
});
// do something with response
} catch (err) {
console.log('error',err.message);
}
}
By default webpack has no configuration for gql or graphql files. You need to add the configuration explicitly.
install required package.
npm i graphql-tag --save
Then configure webpack.
module: {
rules: [
{
test: /\.(graphql|gql)$/,
exclude: /node_modules/,
loader: 'graphql-tag/loader',
},
],
},

How can I fix nuxt js static site links leading to network error?

I have a very basic nuxt.js application using JSON in a local db.json file, for some reason the generated static site links leading to network error, but I can access them from the url or page refresh.
nuxt config
generate: {
routes () {
return axios.get('http://localhost:3000/projects')
.then((res) => {
return res.data.map((project) => {
return '/project/' + project.id
})
})
}
},
main root index page
data() {
return {
projects: []
}
},
async asyncData({$axios}){
let projects = await $axios.$get('http://localhost:3000/projects')
return {projects}
}
single project page
data() {
return {
id: this.$route.params.id
}
},
async asyncData({params, $axios}){
let project = await $axios.$get(`http://localhost:3000/projects/${params.id}`)
return {project}
}
P.S. I have edited the post with the code for the main and single project page
Issues with server-side requests of your application are caused by conflicts of ports on which app and json-server are running.
By default, both nuxt.js and json-server run on localhost:3000 and requests inside asyncData of the app sometimes do not reach correct endpoint to fetch projects.
Please, check fixed branch of your project's fork.
To ensure issue is easily debuggable, it is important to separate ports of API mock server and app itself for dev, generate and start commands.
Note updated lines in nuxt.config.js:
const baseURL = process.env.API_BASE_URL || 'http://localhost:3000'
export default {
server: {
port: 3001,
host: '0.0.0.0'
},
modules: [
['#nuxtjs/axios', {
baseURL
}]
],
generate: {
async routes () {
return axios.get(`${baseURL}/projects`)
.then((res) => {
return res.data.map((project) => {
return '/project/' + project.id
})
})
}
}
}
This ensures that API configuration is set from a single source and, ideally, comes from environmental variable API_BASE_URL.
Also, app's default port has been changed to 3001, to avoid conflict with json-server.
asyncData hooks have been updated accordingly to pass only necessary path for a request. Also, try..catch blocks are pretty much required for asyncData and fetch hooks, to handle error correctly and access error specifics.

How to use knex with sqlite in a vue-electron app

I'm searching some tutorial to setup a vue-electron(I'm using the vue-electron plugin) app with sqlite3 and knex.
dependency sqlite in package.json
here some configs from my vue.config.js to initiate
module.exports = {
transpileDependencies: ["vuetify"],
configureWebpack: {
externals: {
knex: "require('knex')"
}
},
pluginOptions: {
electronBuilder: {
externals: ["sqlite3"],
builderOptions: {
extraResources: ["src/db/database.sqlite3"]
},
nodeModulesPath: ["../../node_modules", "./node_modules"]
}
}
};
I got the sqlite part working but is not clear how would I deal to open a connection, migrate and execute queries.
here is a structure what I try establish as screenshot
Where do I initiate the database, what would be an appropriate structure in this case

CORS axios Nuxt.js

I'm using an API with my Nuxt, here is my nuxt.config.js to allow the requests :
axios: {
prefix: '/api/',
proxy: true,
},
proxy: {
'/api/': {
target: process.env.API_URL || 'http://localhost:1337',
pathRewrite: {
'^/api/': '/',
}
},
}
On a specific page of my app, I need to send requests to another API from another domain. I'm using axios direclty in this Vue component :
axios.post('mysite.com/widget.rest')
As response, I obtain CORS error. Can I allow multiple API in my config ?
If you mean being able to access APIs under different URLs, AFAIK it's not possible out of the box. We tried adding proxy to different targets, but it only worked on client side, not during SSR.
What we ended up doing is having the default axios instance for our main API, and creating a plugin that creates extra axios instances for our other APIs for SSR.
Add extra "suburl" to proxy - this sorts out client side and means no CORS issues.
proxy: {
'/forum/': {
target: 'https://other.domain.com/',
pathRewrite: {'^/forum/': '/'}
},
'/api/': ...
},
For SSR to work, axios should hit directly the other API
import Vue from 'vue'
var axios = require('axios');
const forumAxios = axios.create(process.client ? {
baseURL: "/"
} : {
baseURL: 'https://other.domain.com/'
});
// this helps Webstorm with autocompletion, otherwise should not be needed
Vue.prototype.$forumAxios = forumAxios;
export default function (context, inject) {
if (process.server) {
forumAxios.interceptors.request.use(function (config) {
config.url = config.url.replace("/forum/", "");
return config;
}, function (error) {
return Promise.reject(error);
});
}
inject('forumAxios', forumAxios);
In components, you can then use something like:
async asyncData({app}) {
let x = await app.$forumAxios.get("/forum/blah.json");
You can use process.env prop of course instead of hardcoded URL.
This will hit https://other.domain.com/blah.json.