react, graphql и relay - вполне себе нормальный компонентный...
TRANSCRIPT
React, Relay и GraphQL — вполне себе нормальный компонентный подход
Расскажу про горячо любимый GraphQL: чем он лучше старичка REST API.
Расскажу про Relay: как c его помощью красиво дёргать данные для React-компонентов с GraphQL-сервера
History
2001
2004
HTML 2000 - hover на кнопках - анимированные GIF - under construction и powered by,
- выпадающее меню вверх мастерства,
- marquee
2004.04 Дата запуска Gmail Первое на моей
памяти SPA
2005.02 AJAX
2006.09 jQuery
2006
2008
2008.06 AppStore
2009.05 NodeJS
2008.09 V8
History
2010-11 Responsive Web Design
2010
2011.08 Bootstrap
2010.10 Backbone
2011.12 Meteor
2010 Angular 1
2011.09 Ember 1
2011
2013
History
2015 Sep
2014.08 ServiceWorker
2014-2016 and not ready yet Angular 2 RC
2.0.0-alpha.13 (Mar 14, 2015) 2.0.0-alpha.55 (Dec 15, 2015) 2.0.0-beta.17 (Apr 29, 2016)
2.0.0-rc.6 (Sep 1, 2016)
2013.03 React
Dan Abramov показал Hot Reload
на ReactEurope 2015
Sebastian Markbage влюбил принципами
разработки React
2015
2015.07 GraphQL
2015.08 Relay
2014
React
React
VirtualDom Обновляет в DOM только то, что поменялось. Быстро и без скрипа.
Great life cycles Делайте с компонентами что хотите, на любом из этапов их жизненного цикла.
Errors on build Очень много проверок на этапе билда.
Events Своя event система, работающая во всех браузерах/устройствах, которые использовал.
JS oriented HTML in JS. Not html extension. Всё что вы пишите, пишите на JavaScript.
JSX syntax Удобное решение для разметки элементов. Очень похож на html.
React
Quick start from scratch
July 22, 2016 by Dan Abramov, Christopher Chedeau, Kevin Lacker
Create React App
https://facebook.github.io/react/blog/2016/07/22/create-apps-with-no-configuration.html
May 5, 2016 by Konstantin Tarkus (@koistya)
React App SDK
Uses Webpack, Babel, Jest, ESLint under the hood
https://github.com/kriasoft/react-app
Uses Webpack, Babel, ESLint, Hot Loader, Postcss, Browser-sync
Why Kostya still does not work at Facebook?! I can not understand.
Best of the Best / Suggested Reading List
https://github.com/markerikson/react-redux-links
Curated tutorial and resource links by Mark Erikson (@acemarke)This collection gets more than 150 reactions in my twitter.
React
Quick start from scratch
Other recommended resources:
https://www.udemy.com/user/sgslo/ For React recommended author is Stephen Grider
https://www.fullstackreact.com/articles/react-tutorial-cloning-yelp/
Paid courses on udemy.com
https://www.pluralsight.com/authors/cory-house Building apps with React and Redux in ES6 by Cory House
http://egghead.io
Huge tutorial with screenshots: Cloning Yelp by Ari Lerner
Many lessons available free and by subscription
Weird parts in JS and NodeJS by Anthony Alicea
(also great courses by Docker, AWS)
Paid courses on pluralsight.com
https://www.udemy.com/user/anthonypalicea/
Many many FREE talks on YouTube. Eg. ReactEurope 2015-2016https://www.youtube.com/channel/UCorlLn2oZfgOJ-FUcF2eZ1A
GraphQL
GraphQL is a query language developed by Facebook
Lee Byron
Nicholas Schrock
Daniel Schafer
Authors before and after releasing GraphQL SPEC
GraphQL
GraphQL with any mix of databases!
Implements any custom business logic. Also works with existing code.
One GraphQL query may combine results from different data sources.
GraphQL
GraphQL at any client as you wish!
The best solution to fetch data for web apps, mobile apps, and 3rd party clients.
Any nesting and combination of data in one request. No more nor less then the client requests.
GraphQL
GraphiQL — interactive in-browser GraphQL IDE
Try it!
/ˈɡrafək(ə)l/
https://graphql-compose.herokuapp.com/northwind/
GraphQL
Several queries in one request
Only requested data, no more nor less!
3 REST requests in single GraphQL query
GraphQL
Any nesting in one request
ProTIP: Use DataLoader for reducing over-fetching (one record several times) https://github.com/facebook/dataloader
https://medium.com/apollo-stack/graphql-explained-5844742f195eHow nested queries works:
GraphQL
Fragments (preparation for components) In GraphQL, fragments are the way to group commonly used fields and reuse them.
GraphQL
Mutations and SubscriptionsMutations = add, change or remove data on server
Subscriptions = send requested data, as soon you have new one
Mutation have similar syntax as Query.But multiple Mutations in a single request are executed one by one.
https://github.com/edvinerikson/relay-subscriptions
GraphQL
Live DEMO
https://graphql-compose.herokuapp.com/northwind/
GraphQL Server (backend)
9 models, 14 files, ~750 LOC thanks to graphql-compose
GraphQL
Any complex queries on your frontend
less network trafficless time for processingless time to develop
less requests number
less possibilities for errors
less stress more success
“With GraphQL, we could simply stop writing API documentation or reading it. I think that’s the dream of every developer.”
— by @arunoda (Kadira)
GraphQL
GraphQL tutorial for Frontenders
https://learngraphql.com
you’ll need a couple of hours or days…
GraphQL
GraphQL tutorials for Backenders
http://graphql.org/docs/getting-started/ Official
Useful OSS libraries
https://github.com/matthewmueller/graph.ql Faster and simpler technique for creating and querying GraphQL schemas on server
https://github.com/mickhansen/graphql-sequelize GraphQL & Relay for MySQL & Postgres via Sequelize
A GraphQL API created by reflection over a PostgreSQL schemahttps://github.com/calebmer/postgraphql
My OSS family of packages graphql-composehttps://github.com/nodkz/graphql-compose
https://medium.com/apollo-stack/the-basics-of-graphql-in-5-links-9e1dc4cac055The basics of GraphQL in 5 links, by Jonas Helfer
Mongoose models converter, Connection Type, Relay wrapper and more…
Get ready! You will need a couple of WEEKS or MONTHS…
GraphQL
GitHub GraphQL APIhttps://developer.github.com/early-access/graphql/
GraphQL is a new way to think about building and querying APIs. Rather than construct several
REST requests to fetch data that you're interested in, you can often make a single call to
fetch the information you need.
Relay
Components are perfect correlated with Fragments
Required Data InstructionsRender instructions
Relay
A javascript framework for building data-driven React application with GraphQL
Relay
1
2
3
Correlate Component with GQ Type
Correlate prop name
Define needed fields
Single Component: React, Relay, GraphQL all together
React component
Relay HOC
GraphQL fragment on Address type
https://github.com/nodkz/relay-northwind-app/blob/master/app/components/Address.js
RelayNested components: component in component,fragment in fragment
1
2
3
4
Define topcomponent
Include sub-component sub-fragment
Correctly pass data from component to sub-component
Correctly choose child’s prop name
https://github.com/nodkz/relay-northwind-app/blob/master/app/components/customers/Customer.js
Relay
И как же всё это работает?
React-relay-router (Relay.RootContainer) берет верхней компоненты фрагмент и под-фрагменты, собирает запрос.
Relay отправляет GraphQL запрос на сервер через RelayNetworkLayer, получает ответ.
Записывает ответ в свой плоский Relay.Store (благодаря GlobalID, node interface).
Запускает рендеринг React компоненты.
При дополнительных запросах, сверяется с Relay.Store и пытается отдать данные из кеша, но если чего-то не хватает, то запрашивает только недостающие кусочки данных с сервера.
Relay
8 crazy pages, 47 files, ~3000 LOC
Live DEMORelay (frontend)
https://nodkz.github.io/relay-northwind/
Relay
Conditional fetching Mutations
Optimistic updates
Pagination
Retry
Error handling
Rollback
Cache
Relay
https://github.com/nodkz/react-relay-network-layer
My custom OSS Relay-Network-Layer (query batch, auth, retry, defer):
Relay
https://www.youtube.com/results?search_query=relay+react Talks from authors Joseph Savona, Greg Hurrell, Steven Luscher
Lokka — Simple JavaScript Client for GraphQL
Tutorials
Competitive set
Official docshttps://facebook.github.io/relay/
https://github.com/kadirahq/lokka
Apollo is an incrementally-adoptable data stack that manages the flow of data between clients and backends.http://www.apollostack.com/
Relay
До “безобразия” настолько всё декларативно, что в Relay2 решили добавить немного императивных вещей для “эстетов”.
Relay vs ReRelay2
Заявлено: — Мутации попроще, погибче — Новые скорости — Более доступный/открытый Store
https://speakerdeck.com/josephsavona/reintroducing-relay
Рекомендую к просмотру:
Удобные API с GraphQL — @freiksenet
https://youtu.be/5GCwXh6ocxY
ES6, Babel, Webpack, React, GraphQL, Relay — @nodkz
https://youtu.be/i6i1xGlaVwY
Backend ~750 LOCExpress, GraphQL, Mongoose, graphql-compose
Frontend ~3000 LOCReact, Relay, react-router, react-router-relay, react-bootstrap
https://github.com/nodkz/relay-northwind-app
https://github.com/nodkz/graphql-compose-examples
В сухом остатке про React, Relay и GraphQL — вполне себе
нормальный компонентный подход