506 points · by sbr464 · 8y ago · 171 comments
I hope this book will cover some topics for others that was real head scratchers for us
- DataLoaders
- Authentication example
- Unions and Interfaces are your friend. Use them early.
- Try to define your custom Scalars early (especially DateTime format)
- return Connections (edge/node) instead of List cause you probably want to paginate at some point
- Folder structure (we redid ours 4 times lol)
- Naming convention (we redid ours 3 times lol)
- Subscriptions
After 2 years of using it and hacking it, we're still impressed. Once you get past the learning curves and have set conventions, writing GraphQL is a lot faster and better. Define your types, and some custom root queries, and done.
The neatest thing is that we made a schema validator -- compile all the graphql queries from the frontend and mobile, and validate them against the server schema. It really help when we changed folder structure and naming convention to see if we'd break something on the frontend.
I can't vouch for this book yet, but I'll swear my life on GQL. It's been a real game-changer.
https://pragprog.com/book/wwgraphql/craft-graphql-apis-in-el...
A nice thing about this stack is it supports the GraphQL Subscriptions protocol out of the box without the need to set up a separate pubsub server.
Worth a try if you’d to learn more about the stack or the author’s pedagogic style before buying the book.
Our implementation is a little bit naive - it doesn't "clean out" or see which resources are being used.
On the frontend:
There's a script that globs all `.graphql` files and compiles them into a list of {query, variables}. This probably could be made better if it was a webpack plugin that compiles this on build time. This was a Friday project so our time was pretty limited. This was honestly good enough since it caught a shitload of bad queries =).
Query contains the graphql query. Variables contains test arguments.
It saves them into a gigantic file (example: https://gist.github.com/maktouch/074339517a8da5128d62869356b...)
On the GQL server:
We take that file, we parse it, and we loop it and pass it thru the validate function (https://graphql.org/graphql-js/validation/#validate)
(truncated example: https://gist.github.com/maktouch/e1a2955dfcca42541a41665a361...)
Ops:
Frontend and GraphQL are its own Docker image. We build both in parallel. When both succeeds (in building and running their own tests), there's an extra build step that runs this specific test. It does it by taking the gql-queries.json file from the frontend container, adding it to the GraphQL image, and running the validate command.
You can do this by doing multi-stage builds in Docker (https://docs.docker.com/develop/develop-images/multistage-bu...). We don't push the resulting image - it's just there for testing.
In our current service, I think we're pretty happy with the way our structure is. It's almost similar to saturn-gql but with raw javascript instead of parsing with `graphql-tools`.
John's vote of confidence means a lot to me. The software industry has lots of abstractions that are different ways of arranging the chairs on the deck, shuffling the work around while providing marginal productivity magnifiers.
jQuery's been somewhat superseded because it isn't an application-organizing framework, but it's still one of the best conceived and fitted abstractions for the problems it was meant to solve I've encountered in the entire time I've worked in software. If the person who conceived it thinks GraphQL yields productivity benefits, then I want to check it out.
Don't get me wrong, some aspects of today's GraphQL are still a little rough around the edges, but I think it's a strong pointer towards the future of service integration.
by selling a $80 book?
I don't see how I can implement complex object hierarchies that are not rigid. Only list is supported as an unbounded data type and for some reason there is no unbounded map/dictionary data type even with simple restrictions like requiring string key type. There is not even good advice on what key/value pair naming convention should be for all languages. The other is that there is very poor support for more general include/exclude/where filters. The idea being arbitrary complex join/filter clauses to function like sql statement with multiple joins and where clauses. Have to rely on implementation specific conventions like what sequelize does to get that but not for arbitrary object graphs. Solve some of this and it might actually become as powerful as it is frequently claimed to be.
The most common issue I see is when folks list "what about arbitrary complex join/filter clauses to function like sql statement with multiple joins and where clauses" which, in my use of GraphQL, is literally never something I would want. GraphQL is not SQL or designed to be an arbitrary data access layer.
One of the driving principles of GraphQL, taken straight from the spec, is: "Product‐centric: GraphQL is unapologetically driven by the requirements of views and the front‐end engineers that write them. GraphQL starts with their way of thinking and requirements and builds the language and runtime necessary to enable that."
IMO GraphQL is designed to start with the UI, and develop models that conform to the needs of the UI, not to start with the data and develop arbitrary joining and fetching strategies for that data.
What would the UI data requirements have to be? Aren't they often arbitrary data fetching driven by the user? Aren't the requirements of views what data the user wants to see and handle? Depending on what user chooses, the fetching of data will have to go deeper and deeper into the data store.
I seem to remember, perhaps mistakenly, that GraphQL came as a solution to fetch arbitrary data structures that the view needed instead of having to mix and match multiple RESTful endpoints.
Facebook long ago mastered server-side performance for this sort of use case [1]. Minimizing the number of network requests a mobile app has to make (enter GraphQL) is more important than mitigating costly requests, especially on slow or unreliable networks where the bulk of time in spent waiting on bytes. Entire pages/screens can now be fetched in a single HTTPS request vs. multiple.
As an added bonus, it allows front-end engineers more autonomy and flexibility without having to involve back-end API changes to support ever-changing product updates.
The confusion exists because nothing even remotely formal appears to have been written down or documented. I can only find references like "a query language", which tells all of us very little.
If GraphQL solved all querying problems between the front and the back end, it would be amazing, but it only solves the most naive problems.
> I don't see how I can implement complex object hierarchies that are not rigid.
I'm not sure I understand what you're trying to do, but did you try the JSON scalar type? https://github.com/taion/graphql-type-json
With that, it just returns JSON but you can't pick and choose what keys gets returned.
We never had to use that though. We prefer to use interfaces or unions.
What I sort of what is to be able to craft a query against a large set of objects like a customer/location/asset hierarchy and filter on different levels like sql query without it being in a database. I might have 10 different orthogonal dimensions with foreign keys than can be returned and filtered against. I'm trying to avoid pulling the complete object hierarchy only for it to filter out some of the data after the fact and then finally return the expected json format. Accessing some objects might be very expensive so being able to filter data as part of the query request rather than afterwords would speed things up. These actions are usually quite hard to do in libraries I've used. Maybe if you only use javascript/node.js, I don't know its not what I've need to start with. I may have misinterpreted what GraphQL was for if it is not for querying nearly arbitrary object graphs and returning json that the client wants returned.
The standard is made to be extended (https://www.apollographql.com/docs/graphql-tools/scalars.htm...)
For example, you should start with making your own DateTime scalar.
> What I sort of what is to be able to craft a query against a large set of objects like a customer/location/asset hierarchy and filter on different levels like sql query without it being in a database.
You can totally do this without raw json scalar. Actually, it would be better without it.
If you could go more in-depth details, I could make you a PoC.
I tried doing a GraphQL project in Python/Django recently, using Graphene for the GraphQL bits. I didn't end up getting that far because the documentation was so lacking, as were examples generally (for graphene-python I mean; I could find stuff on GraphQL in the abstract).
I'm thinking about giving it another shot, maybe on node.js this time, largely because I get the impression that the supporting tech for it is more mature there—but I'd love to hear opinions on what the most mature lib for using it is at the moment (whatever language)!
[1]: https://pylondinium.org/ [2]: https://alexchamberlain.github.io/presentation-pylondinium-g... [3]: https://github.com/alexchamberlain/city-api/
Python is older than HTML, CSS, JavaScript, PHP, Java, C#, etc.
We have a significant investment in python so it was a question of spending time training backend devs on JS for one service or working out the kinks and having one of us become the expert to help others. I think we got to a point where we are ok with graphene and al. but I can't direct my team towards any decent documentation. I'm basically going to have to write my own cookbook style docs for them. Not a huge deal but I'd say if you have the option I'm not convinced you should go the python route today as the nodejs ecosystem for graphql is much more mature (yet still has a long way to go).
I'm pretty sure the GraphQL gains will be worth it in the end but we are all early adopters right now, regardless of stack.
"We’ll be looking at the core fundamentals of GraphQL along with strategies for how to implement it (client-side with Apollo and server-side in Node.js)"
Another big issue is that it forces the client to understand a lot about how your application works. While an API can abstract that and conveniently offer various computed properties which output what the client needs.
The added benefit is that you can use the same schema for your client and server.
There's a nice guide to setting up a whole system here: https://www.graphile.org/postgraphile/postgresql-schema-desi...
EDIT: And "Just point Postgrest at your PostreSQL database" is rarely a good idea in my experience, I usually have (versioned) API-schemas containing views, so that I can change my underlying data schema at will without borking the API.
If it was really feasible to bind our databases directly to our APIs, we wouldn't need to hire anyone except DBAs and front-end developers. But backend business logic is a thing. You may not need it, but most people do.
In general, custom business logic can be done through stored procedures/views/computed columns.
However GraphQL resolvers can do much more beyond a simple DB query. E.g. you can call other services and combine their reponses. Or calculate the n-th digit of Pi. Or whatever you want to do.
See https://postgrest.org/en/v5.0/api.html#stored-procedures for more details.
But without seeing the content the pricing looks insane. It has to be worlds better than online resources for 289$ (!).
The more expensive versions include updates and additional features.
Just an FYI as I didn't know that before I had paid.
Tier 1: $39 - Full book when released and early access
Tier 2: $89 - Tier 1 + updates for 2 years + extra chapters
Tier 3: $289 - Tier 2 + free updates for life + more extra chapters
This is an oversimplification with only the things I care about. The actual packages include more stuff. What really annoys me is why would you call tier 1 the full book and say tier 2/3 has "extra chapters".I just want all the chapters + early access + updates (2 years is fine). And I want to pay less than $100. Am I being too entitled? Buying books used to be simpler.
Normally a technical book costs around 40-60 EUR and one gets all the chapters. Updates are called "editions" and are published when there's demand and the information has become outdated.
† limited-time treasure-chest special - unlock all pages for $500!; footnotes and references extra; internet conmection required.
It's also certainly the case that me understanding GraphQL better will easily save my employer much more than $90 of my time, so I might try to expense it and see what happens....
$39 "Upon completion The full book in ebook and HTML formats"
$89 "Extra chapters: Server-side rendering Offline data and mutations Serverless Stripe integration"
Rather misleading then.
Also there should be a dead tree option (even though content gets outdated fast). Personally I'd pay $49 for a printed full book on GraphQL by John Resig.
Right now, he's clocking in at 350+ pages with his co-author. A chapter would take me a week to write, basically, so that's about three months of effort already. That's before you've done review, editing, etc., so you're looking at raw material costs of about $40-50k just to bring the text together with code in a reasonable package.
Even on the $89 package, they're adding in interview videos, interactive exercises(!), and a bunch of extra chapters. I doubt that doubles the cost, but it's probably a chunk extra (unless the book revolves around "designing software for interactive exercises", that's more code they need to write). Then on the higher package, even more chapters and videos, plus technical support (which I think is nuts).
They're pitching it as a book which probably isn't helping, but I actually think that's decent value for what they're offering. Are they going to make a profit? Hopefully, but that's going to come down to how many people are interesting in what is really a technical niche topic.
A lot of content is free; good-quality content tends not to be, and I think the world could use more like this. The market will decide, I guess.
I'd probably pay (or expense) $100-$150 for a really good book, with videos, interactive examples, etc. But this pricing just puts me off the whole book as you can buy the "full" book, the "fuller" book, the "fuller" book with support for bugs in it, etc.
I also expect a book to be reference material that I can share with colleagues as needed (we have an office library), so team pricing per seat comes across as quite money-grabbing.
To be clear, I'm not at all criticising the quality of the content, and I'd be willing to pay good money for good technical content. I just don't think this pricing is very respectful of customers.
This last week I ordered "App Architecture", also for some $50, and I was amazed by what I got - a tiny book that fit in a small envelope...
And now $89 for a PDF?? I love books, but no thank you.
Another thing I feel is odd is the charging for technical support on the code samples. Either the code doesn't work, in which case that's a bug in the _book_ and should be fixed without paying for that, or it's a failure on the reader to set up the right environment, in which case the issue is likely to be minor and could probably be answered on Stack Overflow.
If it was support implementing the ideas in real world projects that would be worth a lot of money, but that doesn't appear to be what they are selling.
Also, I'm a sucker for having all the chapters, and interested in, for example, the chapter about Redis caching. Do I have to pay $289? Way too much...
GraphQL specs offer none to zero of the following:
- caching
- authentication, authorization and handling data access
- protections against ad-hoc arbitrarily nested and complex queries
- routing
How does this “vastly simplify the backend”? If anything, it makes the backend hideously complex (IIRC Apollo’s approach to caching is parsing requests and responses every time, do some magic, and handle caching manually).
Edit: Does anyone know if he goes over typescript?
We'll go over how to generate types or add them manually, but the rest of the book is in ecmascript.
He should be selling it as a knowledge community. Members get access to the resources, conversations, training, etc.
Add levels of membership that have to be earned through merit somehow and membership at a higher level becomes valuable on the CV.
Edit: And wasn't it cheaper earlier? I was pretty sure it was $29 for the basic version, maybe that rounding up market trick got me.
Yes, you're right, the best jQuery would be no jQuery. jQuery was basically a prototype for the next generation of browser features.
Here's the docs for jQuery 1.3 from when REST was starting to take off, with jQuery.post but no delete method: https://api.jquery.com/category/ajax/shorthand-methods/
Why is empowering the client a good thing?
Why is moving complexity from the backend to the front end a good thing?
OTOH if the complexity is offset to the client, and you have multiple clients, then there is more complexity. No?
(assuming you have multiples types of clients)
The only difference is that in a REST world it needed to make several calls to fetch all the data (often waiting for resource references in the nth response before being able to build the (n+1)th query) whereas now it can fetch them all in a single query.
So if anything it reduces the client complexity, as well as making it much easier to extend the API to support new client requirements without having to resort to REST-style versioning.
More to be economical in API design, rather than just server load and bandwidth.
Does someone have good resources on how to use vanilla GraphQL without the bloated Apollo/Relay stuff?
I'm currently working on a GraphQL server (using Graphene), and thankfully I'm able to not use Relay (with which it tightly integrates). So I'm able to implement my own pagination and filters.
That said, I agree that too much of the documentation/articles/tutorials about how to use GraphQL assumes using a particular implementation. I'm far more interested in talking about higher-level concerns like best practices and data modelling.
Is it bad form to just fetch data via GraphQL and put it in Redux (or other store)?
I'd like to buy in, but I'd like to keep my data fetching separate from my view layer if possible.
Honestly, it was a pain, but it's because we abused Redux.
We progressed by doing the HOC and bypassing Redux but it still was a pain, because HOC.
We're now at a stage where we updated Apollo versions, and started converting to the Query components. It feels and work a lot better.
When we started, we thought the same thing -- keeping data fetching separate from the view layer if possible. We realised that it didn't make that much sense. Keeping everything in React components is a lot more maintainable and easier to comprehend.
Also the subscription via websocket story there is really sweet, you basically get real-time update for nothing ;)
In short, just as John stated, it’s a huge boost of productivity on both front and backend, we verified it ruthlessly and love it.
You can use the new render prop API instead of the HOC API if you don't like wrapping.
The data fetching itself is separate from the view layer—it's all done by Apollo. From a maintenance perspective, listing data needs is great to have in the view layer, colocated with the components that use them.
You can manually fetch data via GraphQL and put in Redux, but there are a ton of benefits to having a library like Apollo manage the store for you. Automatic normalization, querying from either store or server (or both), optimistic mutation updates, etc.
If the number of views is only slightly more than the number of tables then the rewards are more a matter of taste. It will give you a nice typed interface to your data and an interactive query GUI. But other tools provide that as well.
How will it show order of magnitude efficiency?!!
It means that you will have 20-40 views towards a database that only contains 10 tables. Which will inevitably result in highly inefficient queries towards said database. Especially if a view is composed into another.
There's no magic in GraphQL that suddenly makes that go away.
Unless you develop multiple apps or data-driven application there is very little reason to use GraphQL. Personally, I am in favor of building two APIs: public/third party REST and JSON-RPC for the frontend. Getting REST right is difficult and after you create your resources your frontend needs to workaround incomplete/superfluous data.
I am interested, but as a guy working more on backend systems, frontend and mobile will not help me very much. I don't want to pay $40 for majority of content I cannot make use of.
How do you control scaling, and writing performant queries? When you make an API endpoint you have control over the queries you make and how you make them.
With GraphQL you lose that control right? Maybe its good for internal projects, where you own the client and server. But often just exposing the internal DB directly to GraphQL is probably not a good idea. Maybe writing the DataLoaders yourself is better. But then you are already close to the effort of writing a simple endpoint.
For simple API's graphql seems like overkill.
For the performance aspect, check out Apollo Engine, which allows you to track the latency and implications of using different fields within your queries and mutations over time:
GraphQL is just a schema specification like Swagger. It doesn't come with a server or a client. Those are implementation details left up to you, just like in REST.
I guess it comes down to how important schemas are to you. Which I know suggesting they might not be important sometimes is for some people a sin punishible by death. But for me that's a belief system that doesn't hold up for everyones application.
For the low price of $39 I will get the full book in ebook and HTML formats when it is done.
But for the price of $89 I will get extra chapters on Server-side rendering, Offline data and mutations, Serverless and Stripe integration.
So I am clearly not getting the full book for $39.
I just recently refused to buy a game for employing the same dishonest sales tactics, so this is an easy no thanks from me.
If you pay $39 you get 8 fewer chapters than the actual full book. And it's online only, so no paper printing or publisher overhead. For $89 you get a video and some extra chapters (that really should be in the book you paid for in the first place). If you pay $289 (which is an absolute absurd price for any book) you get exactly what you used to get with books 10 years ago: a book with all its intended chapters, a mailing list, a glorified IRC channel and a code repo. Except, again, it's still not even a physical book (so why so expensive?).
If you pay the "Training" package ($749) you supposedly get superior in-person mentoring. Except it's not really done by the authors. It all sounds like some Tai Lopez scam.
I don't want to diminish the amount of work it took to make this book, or the quality of the authors. I'm sure it's incredible and it seems a pretty massive book. But I just don't understand these sort of things when it comes to professional programmers who write books. Supposedly they want to spread this technology they care about and want people to use it. We as programmers get paid very well, we're not in need of money. Book revenue is probably not their main source of income. So why price it out of everyone's range? You're not gonna reach nearly as many people as just selling it at a reasonable price.
> it's still not even a physical book (so why so expensive?)
I have never written or published a book, but my understanding is that the cost of writing the book far outweighs the cost of actually printing it. Human time and knowledge is way more costly than some paper and the effort of a machine that spits out books by the second.
> If you pay $289 (which is an absolute absurd price for any book)
This offer and especially the in-person one seem like they are targeting businesses. A lot of places will pay orders of magnitude more to have someone work directly with their employees.
Honestly, about $93/hour is on the cheap side for in-person training. (I'm not saying it's good training or even close to worth it, just what the landscape looks like)
Edit: actually, it would be cheaper than $93/hour since I'm not taking the other things into account. Let's say the book and all the other stuff realistically make up about $150 of the price (I am guessing the $289 is just trying to get you to buy one of the surrounding tiers). That's actually $75/hour for the training.
Usually physical books are said to be expensive because publishers are the ones holding the rights to them. They pay the authors in advance and try to recoup the cost later, with prices as high as the market will bear. The publishers have some fixed overhead in payroll (for editing, typography, art), printing, marketing, etc. Add to that the risk of the book not being finished by the author and the publisher's profit margin and it goes some ways to justify their pricing (or at least it makes it understandable). The authors then get only a slim percentage of the sales (if at all).
In this case the book isn't even finished, the full proceeds go to the authors (or so it seems) and the readers are expected to advance the money themselves to offset the costs of writing it. The overhead is vastly diminished, there's no publisher, the authors incur no risk, and yet the price is much higher. Makes no sense.
Speak for yourself.
The cost of a book is in the IP, not the printing costs.
What is the maximum non-absurd price for a book?
Why do you think the authors are the only experts who can lead a useful training?
Which cost-effective GraphQL book should we buy instead?
https://www.manning.com/books/secrets-of-the-javascript-ninj...
The MEAP was released in 2008. Three years later Manning brought in a second author to finish the book. It was released in 2012.
A couple of quotes from https://johnresig.com/blog/secret-omens/:
> ...I got caught up in coding and stopped focusing on writing. I had to prioritize my time and I chose to prioritize doing more development and focusing on my personal life.
> ...I would absolutely not write a technical book again.