Should I run "apolloServer.executeOperation" on Next's "getServerSideProps"? - node.js

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.

Related

How should the correct tests be?

I am searching to write correct and understandable tests on react. I have read a lot of articles and texts. But I haven't understood a few matters. I have a component which request with axios. So there are requests like GET, POST.
How should the backend behave during frontend testing? Should the backend switch to test mode after frontend tests started ? Should the database reset itself after each frontend test ?
I think I shouldn't mock API to check if component correct render. What is the correct logic ?
The way that I approach this will be to mock the API call, the reason to do that will be, that I am reducing my scope of testing, As I am testing the React part, I would mock the success response and mock the error response and check how my components are working.
For the API testing, I will create a separate test case on the backend side. This way there will separation of concern. That is when I am testing react side I limit myself to the react side only and also this will make your test run fast as you are mocking the response, the actual request will not be sent and so you will get the response quickly.

How can I use react with a custom webserver?

I want to use React for a project I am working on, but I also want to use an API.
How can I do it?
I have tried to Google this and ask different people, but I have not got a response yet, so I thought I would ask here. I want to use express and maybe not use create-react-app (as it takes up a lot of storage).
Working on a custom server doesen't preclude the use of an API.
If you want fetch the API from the express server and inject it directly on react frontend you need to enable server side rendering (useful post) and pass the data collected as a props from the server (check this example).
Rather then you can build your react project (using even create-react-app) and build an express server who return the index.html on call.
Personally I prefer the first one solution.

HTTP Calls integration pattern- Making HTTP calls directly from Javascript vs Axios vs Node, which is more secure?

A novice javascript developer here!
A have a basic question on whats the best and secured way to make HTTP calls from a front application to a backend service that needs an authentication. My application is a SPA (using Vue.js) & getting data from Java services. Java services need authentication details and return sensitive user data.
I see there are a few options and I wanted to understand a better approach amongst all 3-
Making direct HTTP calls from javascript code- Concern for using this approach is, as Javascript code can also be viewed via dev tools in browser, wont it be easier for anyone to do an inspect and view all critical authentication details hence making overall integration less secure?
Making an HTTP call using Axios via Vue framework- Seems like Axios is Promise based HTTP client for the browser that lets you easily make HTTP calls without much code overhead. but is this secure? is Javascript code loaded in the browser? Or the front end code sends the request and axios makes the request from backend server where the application is hosted?
Using Node- If front end application has unique routes configured for each API call and in my application if I have a route mapping to use request module and node js backend code to make those HTTP calls, is that going to be a robust and secure way of integration?
Please let me know your thoughts and apologies if this is a dumb question!
Not dumb at all. You're just learning.
My first question to your answer 😅 will be: is your application server-side rendered or it's sap + backend?
If it's server-side rendered then I would say it's secured since Node will be sending pages with all required data. On the dev tool, you will only see static files being loaded.
However, if it's SAP, I am not sure whether there is a way to hide whatsoever you send to the server from the dev tool. The only one thing you will need to do is to make sure you encrypt whatever is sensitive to your application.

How to show GraphQL schema on client-side (test tools like postman)

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.

How to build a website on Node.js?

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!

Resources