I am using Node.js & GraphQL to build an API server.
I was wondering how I can enable the feature that the schema will show automatically when using tools like Postman/GraphQL Playground to send requests to remote API endpoints(currently using heroku).
When I launch the server and GraphQL Playground on localhost, it will show the schema and docs on the right side like below.
But when I change the endpoint to remote server (heroku in this case), it won't show any schema or docs. The schema and docs sidebar just keeps loading like the picture below (I hide the url for privacy issue)
Also not showing in Postman
Do I need to configure something or use some package in my server so that it will return and show the schema automatically on client-side?
Thank you.
You might try either set introspection: true flag in the constructor parameters of your apollo-server or, if it is suitable for your needs, to deploy onto heroku the development version of your app.
An explanation:
To see the schema and docs, your client should obviously fetch it first.
This request for graphQL schema usually called an "introspection".
Having the full schema of backend graphQL API is undoubtedly convenient during the development.
However, when our app is running in the production environment, we usually should expect malicious clients. Therefore, sending introspection in the production mode might be unsafe, because it would give a lot of additional information to the potential attacker.
That's why the introspection turned off by default in the production environment for the current version of appolo-server.
Related
I'm trying to figure out the best way of running GraphQL queries in the getServerSideProps of a Next.js app.
Since the GraphQL server is running on the same Next.js instance, the obvious solution is to run apolloServer.executeOperation() on the getServerSideProps function of my pages.
However, I'm worried about this solution because:
The documentation of executeOperation describes it as an integration tests function. It literally says "The executeOperation method provides a single hook to run operations through the request pipeline, enabling the most thorough tests possible without starting up an HTTP server.". But it doesn't say it should only be used for testing.
Pretty much all online Guides I find online about running GraphQL on Next.js says I should use an apollo client (Example). However, running an Apollo Client on the same server as my GraphQL server seems like an obvious unnecessary overhead.
Which leads me to think I maybe missing something obvious.
Is it OK to call apolloServer.executeOperation on my Next.js getServerSideProps?
We run a basic async fetch on the getStaticProps, in our Next app, a formatted response gets passed to the Home component and used to setup the redux store.
I imagine that if you were to do a graphql request you would need to init the graphql client before you can use it - which happens later in the call chain for us, and i imagine you. You could maybe do your GQL client setup server side and pass the object by props to Home, but doesn't seem like thats the intended use.
I'd say if you need to server side request with GQL, create a client getServerSideProps and close it after your request, don't see much of an issue with that.
Why should I use graphql if I setup a react frontend and mongo db backend?
And Why should i put graphql server between mongo db and react?
Since you didn't mention what is your alternative API style I will just assume it's REST. GraphQL gives you many features a plain old REST api won't have out of the box.
This is probably the best answer listing advantages and disadvantages of both.
You already have validation(via mongoose schemas), but using GQL you can get:
excellent documentation for your API generated for you
avoid underfetching/overfetching on frontend
ability to batch FE requests easily
you can tap into a very rich ecosystem of GraphQL tooling which only gets better as time passes
easier testing-you can just execute your graphql queries on backend even without sending them over the network saving a little bit of performance overhead
I believe you should use GraphQL for any non trivial API, because it adds ton of typesafety and the price you pay as a developer is very low.
I am trying out React-Starter-Kit for the first time and loving all the cutting edge features baked in (apollo/graphql-client in particular). A crucial part of any app for me is the database, and for that my understanding is the same author provides nodejs-api-starter which sets up a REST interface for accessing Postgres at localhost:5000 and has a graphql webui at localhost:5000/graphl.
That is about as far as I have been able to understand of the setup so far. I have changed the frontend code a little bit so a new Component "Counter" is loaded on the home page. I need to be able to make a new counter, fetch the latest counter, and increment decrement the counter. Write now the component just outputs the 'value' retrieved from the server at 5000.
I do not think I am accessing the 5000 server correctly, do I put the port in this url line somehow?
You can pull the repo down from : https://github.com/Falieson/react-starter-kit-crud-counter-demo
This is my first time setting up a nodejs api server, I am used to using MeteorJS which has pub/sub to MongoDB baked in. I am looking forward to the separation the RSK strategy (which seems more industry standard?) provides.
I've just done setting up the full site with Database from React-Stater-Kit, I'm also a newbie so I understand your frustration.
About this question, you don't need the NodeJS-API-Starter, it has enhanced function ( such as Redis cache ) and it's not suited for newbies. You should look deeper into the RSK, it already has the DB. If you ran the boilerplate and played around, change is you'll see file database.sqlite in your folder, it's the database. Here are the things you should learn:
Use SequelizeJS to connect the NodeJS server with database. Your database can be MySQL/MariaDB, PostgreSQL or SQLite. The connection is easy and there's tool to auto-generate Models from your database
How to create GraphQL's Types and Queries. If your queries need to search through the database, import Sequelize's models and use its functions.
Test your API via GraphQLi
Note: if you want to use MongoDB or other NoSQL, try Mongoose instead of Sequelize.
I went through the Zza sample where BreezeJS is used in combination with an NodeJS (+ MongoDb) backend.
http://www.breezejs.com/samples/zza
In the sample there is no client nor server side validation implemented as we can do with a .Net backend.
Is this simply not possible when using breeze + MongoDb or is it just not present in the sample?
The big difference with the .Net backend is that the meta data are stored client side and not autogenerated from the server. Can we assume that something similar will be possible one day with MongoDb ?
Is Breeze + MEAN production ready or is it still beta material?
Client side validation in Breeze is not dependent on the server. You can define validations directly on the client. There are plenty of examples of this in the documentation for the other non Mongo providers, but the code is the same. In terms of metadata coming from the server, since MongoDB has no schema there is no way to return what would be nonexistent metadata to the client. The only way to do this would be if you were to also use something on the server that more strongly typed the Mongo data ( i.e. something like Mongoose). This has been a request on the Breeze User Voice.
We have not yet created a Mongo example where we automatically validate the data on the server before saving, but this shouldn't be that much of a stretch, but it will be "custom" code.
In terms of being production ready, we are still adding features to the breeze ecosystem, both on the client and the server. However, we do try to limit the number of breaking changes.
I've just started diving into Node.js after several years of PHP programming and I would like to build a Node.js app for my next project, but I have no clue how to do it.
Are there any resources for a Node.js jumpstart?
Thanks in advance!
You should think of Node.js as some kind of Apache + PHP, meaning that you can program your website and your webserver with Node.
Node has some important differences with your basic PHP, it's evented, asynchronous, non-blocking. You have to learn how to deal with callbacks, don't block the event loop and other things.
What you should do is try to learn the basic stuff with Node at the beginning, here are some great resources: https://stackoverflow.com/tags/node.js/info (my favorite has been nodetuts.com and the excellent book by it's author, Hands on Node).
After you've learned the basics, you can find Express really useful as a web framework and Socket.IO if your app is focused on real-time.
I think you're searching for a node.js jump start to build some meaningful web page with node. Take a look at express, which is a node web framework. They offer a nice but short tutorial (under guide).
You need to run Node.js on a web server. Basically, you need a VPS or Dedicated Server over which you have full control. [PHP runs through the standard web server, Apache. Node.js is the webserver.]
Or you find a Node.js host that'll do it for you.
Node.js is essentially your webserver that would replace Apache so the only hosting that you would find to run Nodejs is a dedicated server or a cloud instance in which you would have to install and run nodejs on. The machine that you run node.js on needs to have a domain name pointed to it or the only way you can access the server is by its IP address which is this case your localhost.
Another option is to use something like Knockout.js (http://knockoutjs.com/), and have the page make JSONP calls to the Node.js server. It's really easy to use Node to send JSON to the client, since it's JavaScript on the server. Using a framework on the client makes it really easy to create a dynamic page based on that JSON data.
The disadvantage is there is no graceful degredation for older browsers. The advantage is a potentially blazing fast website with great AJAX built-in right from the start.
Here is some sample code for using Node to generate a JSONP response:
function writeJsonpResponse(res, jsonpcallback, obj) {
var serialized = JSON.stringify(obj);
res.writeHead(200, {'Content-Type': 'application/javascript'});
res.write(jsonpcallback + '(' + serialized + ');');
res.end();
}
Read the README.
Setup environment.
take a look at package.json (or npm init to create one)
install dependencies (npm install / axios, nodemon, express, mysql, react, babel)
add scripts to start server & webpack if needed
Get acquainted with file structure.
separation of concerns - public/dist, server, db, client
think about the flow of data
Ensure basic HTML structure.
check that bundle.js file / everything it needs is loaded in
need a div id to render react with (like app or root)
Spin up Express server.
Start server and webpack is separate terminals.
check for console.log that server is listening!
Write routes (get and post requests) on your server.
check that get & post requests are working w/ Postman!
Create mySQL database (db/index.js).
Design & import schema (how to structure data tables).
make sure you’re in the db folder when importing yr schema girl!
Connect db to server.
check for console.log that connection is successful!
Write insert/retrieve db query functions.
don’t forget to module.exports those queries to the server!
will call query functions in routes/get & post requests in server
Set up basic React structure.
index.js’s only task is to render your app component to the div id app
need a stateful App component to render all other components
remember to import & export default everything!
Design the rest of your components, decide whether or not they will be functional (stateless) or class components (stateful).
draw it out!
what props (data & functions) do you need to pass down?
Write those components.
Work through one data flow that executes through all the pieces. Get your input handler to send the client side POST request (using axios) to the server route, which will execute your API call (if there is one) and then insert that data to the database.
remember to handle your errors!
Handle events / conditional rendering.
1. user event gives input (onChange e.target.value)
2. write a handleChange f(x) to update state to that new input
3. input is submitted (onClick)
3. write a handleSubmit f(x) that takes in the updated state and makes an axios POST request w/ that { input } to the appropriate server route
remember to bind method functions appropriately!
Call query functions in routes/get & post requests.
Check that data from the client is being stored in the database.
describe those tables my friend!
Do an AJAX get request (use axios or fetch) on client side to api endpoint.
Store the incoming data in setState
May want to do a GET request in componentDidMount to always render appropriate info for client
Yay! You successfully set up your server, database, and client, passed data between them, potentially manipulated the data, stored that data, and displayed the appropriate data to the client!
Tackle those user stories!