Tag Archives: react

Is REST tired? GraphQL a stimulant?

Based on my quick review, it seems a company should add GraphQL to their tech stack. It’s not an either/or situation.

REST
Representational State Transfer (REST) is the architecture underlying the WWW. It scales. The REST concept is also be used to create RESTful services as an alternative to older technologies such as Remote Procedure Calls (RPC) and SOAP. REST architecture scales.

REST has some limitations and critiques. For example, few REST APIs are truly “RESTful”. The level of REST is captured in the Richardson Maturity Model (RMM). The highest level requires use of HATEOAS, see “Designing a A True REST State Machine”.

“A very strong argument could be made that if most APIs are REST-ish instead of REST-ful, and assuming that most of the conventions that we’re actually using boil down to making URLs consistent and basic CRUD, then just maybe REST really isn’t buying us all that much.” — @brandur

One claim is that REST has issues since it is misapplied:
“…“REST is intended for long-lived network-based applications that span multiple organizations” according to its inventor. This is not a requirement for APIs that serve a client app built within the same organization.” — https://reactjs.org/blog/2015/05/01/graphql-introduction.html

GraphQL
GraphQL was created to fill a hole in modern web API. GraphQL unlike common REST queries, describes the ‘shape’ of data to retrieve from a single end-point. The structure of that data at the end point is a black box. The host knows how to fill in the shape to create the response. Kind of like SQL (in a very rough kind of comparison): In SQL the data has a shape, the Relational Model, and the single end-point queries, declaratively describe what to get from that shape. In REST when you ask for a cup you get the kitchen sink and all the cabinets.

“GraphQL is a declarative data fetching specification and query language for APIs. It was created by Facebook back in 2012 to power their mobile applications. It is meant to provide a common interface between the client and the server for data fetching and manipulations. GraphQL was open sourced by Facebook in 2015.” — GraphQL vs REST

The single endpoint is a critical distinction. To get distributed, consolidated, or nested data a REST endpoint could, of course, invoke an integration service on the backend, or use techniques such as API Chaining. in GraphQL the “integration” exists semantically on the client query. The declarative query just describes the result and the server provides it. And since the shape determines the data desired at the single endpoint, the over/under fetching of REST is avoided. The query is ‘resolved’ on the server which may invoke of existing multiple SQL, REST services, MQ, or other services. This affords natural growth of the API. In contrast a REST API grows via more endpoints and/or addition of query parameters (which could morph to disguised RPC).

Image on www.graphql.com

“GraphQL was our opportunity to rethink mobile app data-fetching from the perspective of product designers and developers. It moved the focus of development to the client apps, where designers and developers spend their time and attention.” — https://code.facebook.com/posts/1691455094417024/graphql-a-data-query-language/

In “How GraphQL Replaces Redux” after the team started to use GraphQL they had three ‘Startling Realizations’:

  1. Most of our state management code was concerned with merging and mutating data from discrete REST resources into the right shape for our UI (reducers, selectors, actions etc.).
  2. A lot of our most complex state management was trying to manage the asynchronous nature of getting all that data in the right order for a specific route (sagas, middleware, thunks etc.).
  3. Practically everything else, UI state, worked great with plain old React state.

And, then they deleted a lot of code. A similar experience shown here: “Reducing our Redux code with React Apollo”, https://dev-blog.apollodata.com/reducing-our-redux-code-with-react-apollo-5091b9de9c2a

Summary

  • GraphQL is not a replacement, both can be used; even “GraphQL over REST”
  • GraphQL allows less chatty communication
  • GraphQL is not perfect
  • For simple API GraphQL will only add complexity.
  • Has been proven in many production applications and sites.

Critiques of GraphQL
New technology hype hardly ever gives the true efforts and failed approaches that it took to make something work. GraphQL is no exception.

1. “GraphQL Seems Like We Do Not Want to Do the Hard Work of API Design”, https://dzone.com/articles/graphql-seems-like-we-do-not-want-to-do-the-hard-w
2. “Just Because Github Has a GraphQL API Doesn’t Mean You Should Too”, https://www.programmableweb.com/news/just-because-github-has-graphql-api-doesnt-mean-you-should-too/analysis/2016/09/21
a. API chaining is fix for chatty REST?
3. “Are there any disadvantages to GraphQL?”, https://stackoverflow.com/questions/40689858/are-there-any-disadvantages-to-graphql?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
4. “Semantics and complexity of GraphQL”, https://blog.acolyer.org/2018/05/21/semantics-and-complexity-of-graphql/ Provides an algorithm for determining response size of a potential query.

Learning GraphQL
1. Introduction to GraphQL: http://graphql.org/learn/
2. “A Front End Developer’s Guide to GraphQL”, https://css-tricks.com/front-end-developers-guide-graphql/
3. “The Fullstack Tutorial for GraphQL”, https://www.howtographql.com/
4. Graphql.com tutorials: https://www.graphql.com/tutorials/
5. “Five Common Problems in GraphQL Apps (And How to Fix Them)”, https://medium.freecodecamp.org/five-common-problems-in-graphql-apps-and-how-to-fix-them-ac74d37a293c
6. “GraphQL Deep Dive: The Cost of Flexibility”, https://edgecoders.com/graphql-deep-dive-the-cost-of-flexibility-ee50f131a83d
7. GibHub explorer using GraphiQL: https://developer.github.com/v4/explorer/
8. “Thinking in Graphs”,
9. “Dan Schafer, GraphQL at Facebook”, https://www.youtube.com/watch?v=Ey3BtXDO2UM

Implementations
1. Prisma: https://twitter.com/GraphQL
2. Apollo client: https://www.apollographql.com/client/
3. Relay: https://facebook.github.io/relay/
4. GraphQL.js: http://graphql.org/graphql-js/
5. Apollo Server: https://www.apollographql.com/server
6.

YouTube Videos
*TODO*

Further Reading
1. “Is GraphQL Moving Toward Ubiquity?”, https://nordicapis.com/is-graphql-moving-toward-ubiquity/
2. “Top 5 Reasons to Use GraphQL”, https://blog.graph.cool/top-5-reasons-to-use-graphql-b60cfa683511
3. “GraphQL over REST at Reactathon 2018”, https://www.slideshare.net/sashko1/graphql-over-rest-at-reactathon-2018
4. “What are advantages and disadvantages of GraphQL, SOAP and REST?”, https://www.quora.com/What-are-advantages-and-disadvantages-of-GraphQL-SOAP-and-REST
5. “…And GraphQL for all?”, https://apihandyman.io/and-graphql-for-all-a-few-things-to-think-about-before-blindly-dumping-rest-for-graphql/
6. “REST versus GraphQL”, https://blog.pusher.com/rest-versus-graphql/
7. “Simplify relational logic with GraphQL”, https://scaphold.io/community/blog/querying-relational-data-with-graphql/
8. Who is using GraphQL? http://graphql.org/users/
9. “GraphQL is SQL for Knowledge, not Data”, https://react-etc.net/entry/graphql-is-sql-for-knowledge-not-data
10. “GraphQL vs REST comparison – Is This Solution from Facebook Worth Taking the Risk?”, https://www.netguru.co/blog/grapghql-vs-rest
11. “Sharing data in a Microservices Architecture using GraphQL”, https://labs.getninjas.com.br/sharing-data-in-a-microservices-architecture-using-graphql-97db59357602
12. StarBucks use of GraphQL: https://twitter.com/davidbrunelle/status/961103308957147136
13. “Richardson Maturity Model”, https://martinfowler.com/articles/richardsonMaturityModel.html
14. “2 Fast 2 Furious: migrating Medium’s codebase without slowing down”; https://medium.engineering/2-fast-2-furious-migrating-mediums-codebase-without-slowing-down-84b1e33d81f4
15. “Cartoon Guide to Facebook’s relay”, https://code-cartoons.com/a-cartoon-intro-to-facebook-s-relay-part-1-3ec1a127bca5
16. “Thinking in GraphQL”, https://facebook.github.io/relay/docs/en/thinking-in-graphql.html
17. The GitHub GraphQL API: https://githubengineering.com/the-github-graphql-api/
18. You don’t need a fancy framework to use GraphQL with React (All you need is a good naming strategy) : https://edgecoders.com/you-dont-need-a-fancy-framework-to-use-graphql-with-react-b47b436626fb#.hu577b1ln
19. “How GraphQL Replaces Redux”, https://hackernoon.com/how-graphql-replaces-redux-3fff8289221d
20. “Reducing our Redux code with React Apollo”, https://dev-blog.apollodata.com/reducing-our-redux-code-with-react-apollo-5091b9de9c2a
21. The GitHub GraphQL API: https://githubengineering.com/the-github-graphql-api/
22. https://twitter.com/GraphQL
23. “The Evolution of The New York Times Tech Stack”, https://stackshare.io/posts/evolution-of-new-york-times-tech-stack
24. “Designing a A True REST State Machine”, https://nordicapis.com/designing-a-true-rest-state-machine/
25. https://twitter.com/GraphQL
26. “The Evolution of The New York Times Tech Stack”, https://stackshare.io/posts/evolution-of-new-york-times-tech-stack
27. “Here’s my follow-up to REST is the new SOAP: let’s talk about the Original REST”, https://medium.freecodecamp.org/follow-up-to-rest-is-the-new-soap-the-origins-of-rest-21c59d243438
28. “GraphQL vs REST: Overview”, https://philsturgeon.uk/api/2017/01/24/graphql-vs-rest-overview/
29. “Reflections on REST — FSE’17 Keynote”, https://www.youtube.com/watch?v=6oFAmQUM8ws&feature=youtu.be
30. “A Journey Through React Apollo – Peggy Rayzis aka @peggyrayzis at @ReactEurope 2018”, https://www.youtube.com/watch?list=PLCC436JpVnK3xH_ArpIjdkYDGwWNkVa73&time_continue=1&v=fCXYA3lZTbo
31. “Dan Schafer – GraphQL: Client-Driven Development”, https://www.youtube.com/watch?v=vQkGO5q52uE
32. “A Real-World GraphQL Application in Production”, https://www.youtube.com/watch?v=6bRFElKG0a8
33. “What it takes to run the world’s largest GraphQL server”, https://www.youtube.com/watch?v=nOYyix0NpvY
34. “From REST To GraphQL”, https://www.youtube.com/watch?v=ntBU5UXGbM8&t=690s

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

React component with Media queries for Responsive

This is a very simple approach using matchMedia support. We store media queries and a listener function as an object in an array. When the media query returns true the listener function will set the relevant component state true.

In our actual project, this approach is used with Redux. The queries instead of setting component state, update the Store. Containers connected to this store send the breakPoint, orientation, and other props to each child component.

Just an experiment. If pursued further, would probably make it a HOC (Higher Order Component).

Gist available here.

Demo
If packed and loaded into a web page as we resize the browser we should see:

Change size of browser to test

state: { 
    "orientation": "landscape", 
    "breakPoint": "LG" 
}

Why?
While CSS media queries are very useful, sometimes being able to respond ‘behaviorally’ to media events is very powerful.

Tested on
Chrome, FireFox, IE, and Edge. I guess they all have JavaScript MediaQuery support.

How it works

In the life cycle method ‘componentDidMount’ we add a query to an array in the component:

this.mediaQueryFactory(obj, '(orientation: portrait)', this.onPortrait);

this.mediaQueryLists.push({
	mql: obj.mql,
	listener: this.onPortrait
});

the onPortrait is the listener function:

onPortrait : function(flag){
  if(flag){
	this.setState({orientation: 'portrait'});
  }
},

Full Code

Other MediaQuery React implementations

Addendum

{
  "name": "ReactMediaQuery",
  "version": "1.0.0",
  "description": "Attempt at using Media Queries in React",
  "main": "./index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack index.js dist/react-media-query-bundle.js"
  },
  "keywords": [
    "react"
  ],
  "author": "JosefBetancourt",
  "license": "SEE LICENSE IN COPYWRITE.TXT",
  "dependencies": {
    "babel-polyfill": "^6.9.1",
    "classnames": "^2.2.5",
    "react": "^15.3.0",
    "react-dom": "^15.3.0"
  },
  "devDependencies": {
    "babel-core": "^6.10.4",
    "babel-loader": "^6.2.4",
    "babel-plugin-add-module-exports": "^0.2.1",
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-es2016": "^6.11.3",
    "babel-preset-react": "^6.3.13",
    "babel-preset-stage-2": "^6.11.0",
    "eslint": "^3.2.2",
    "webpack": "^1.13.1"
  }
}

package.json

var path = require('path');
const webpack = require('webpack');

module.exports = {
  /* entry point */
  entry: './index.js',
  /* output folder */
  output: {
    filename: 'dist/react-media-query-bundle.js'
  },
  devtool: 'source-map',
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react', 'stage-2']
        }
      },
    ]
  },
  eslint: {
    configFile: path.join(__dirname, 'eslint.js'),
    useEslintrc: false
  },  
  plugins: [
  ],
  resolve: {
    extensions: ['', '.js', '.json'] 
  },
  resolveLoader: {
      modulesDirectories: [
          'node_modules'
      ]
  }
};

webpack.config.js

<!DOCTYPE html>
<html>
  <head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">  
  	<title>React Media Queries</title>
  </head>
  <body class="body">
    <div id="root" class="">Loading page, please wait ....</div>
	<script src="dist/react-media-query-bundle.js"></script>
  </body>
</html>

index.html

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

How to edit React jsx scripts in Eclipse?

I was about to use React in a new project when I hit a development PITA. How do you edit the JSX scripts within a page using Eclipse?

Background
In React, you can use JSX files or JSX script embedded in the page. The JSX transformer converts these to standard JavaScript at compile or in the browser.
Note: Embedding JSX scripts in a page is most likely a very bad thing to do. Maybe justified for learning React, demos, or quick examples.

Eclipse allows the use of shortcut key bindings for various views and content types.

Example
From the React docs, below is a sample jsx script. When this is embedded in an HTML file within Eclipse, such as index.html, there is no way to edit the script using the normal Editing key bindings. Even indentation of highlighted lines fails. Weird, I even tried to create a new key binding for TAB or ctrl+i, to no avail.

<script type="text/jsx">
	var HelloWorld = React.createClass({
	  render: function() {
		return (
		  <p>
			Hello, <input type="text" placeholder="Your name here" />!
			It is {this.props.date.toTimeString()}
		  </p>
		);
	  }
	});

	setInterval(function() {
	  React.render(
		<HelloWorld date={new Date()} />,
		document.getElementById('example')
	  );
	}, 500);
</script>

If I discover how to get around this, I’ll post here. Of course, you can put your jsx code into an external js file, that Eclipse has no problem with.

Updates
Mar 1, 2016: Working on a new React/Redux app. Now in Eclipse, when editing js files and add a line by entering return at the end of a line, Eclipse adds + ” at the new line break. Oh veah. Creating runtime errors.

Links

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.