GraphQL for new projects looks great ... buuuut how do you use it with that old backend cobbled together in Rails over the last bazillion years?
Can you write an async function that returns some data? Great! That's all GraphQL needs. 🤘
No seriously, it's that simple.
You can connect GraphQL to your REST API instead of the database. Create a small proxy and start using GraphQL on the frontend today. No backend changes required.
We explored this idea on a stream 👇
Out came a proof of concept that took a 37KB payload from our production API at Yup and turned it into this:
37KB for one request isn't even the biggest API payload we've got. It's just the most common 👉 our entire settings object.
Nobody even knows which of those fields are still in use. Can't remove any because you might break an old client.
So forever more every client gets every setting that any client in history ever needed.
With a GraphQL proxy, each client can take just what it needs.
It works like this:
- Client sends GraphQL query
- GraphQL proxy gets query and maps it to the
- Resolver makes
fetch()request to API
- API returns full settings object
- GraphQL machinery matches object to query
- Proxy returns only the requested data
Want to combine multiple API requests into one? Now you can! Just send 2 queries in 1 request.
Users get a faster app and lower bandwidth usage.
You get an easier coding experience on the client and you empower frontend engineers to make better decisions.
Worried about the overhead of a GraphQL proxy?
Many requests can be cached and don't even have to hit your real backend.
- Create a GraphQL server
- Write query resolvers that poke your API
- Build GraphQL type definitions from your payloads
That last part is tedious, I'm sorry.
Wittern et al talk about Generating GraphQL-Wrappers for REST APIs in a 2018 paper, but I haven't found a good implementation in the wild yet. Hasura looks like a great approach, but they convert your Postgres schema into a GraphQL API, not your client-facing API.
How related are your Postgres and your REST API really? I bet you build those payloads from SQL queries, environment variables, helper methods, and all sorts of stuff.
WalmartLabs created a JSON-to-GraphQL library that works well for a first pass. I used it on the stream.
You could create a crawler that goes through your API and builds GraphQL type definitions. 🤔
After harping on and on that we need GraphQL and it will solve many of our problems, my team started getting tired of my shit. We can't do it, it's too hard, we don't want to change the backend, we ... screw you I'm building it.
here's what I found
Host on AWS Lambda so you don't have to deal with servers. Focus on the code.
sls deploy and you get a server that runs your
graphql.handler method on every GET and POST request.
Apollo is great for building GraphQL servers. Good community support, integrates well with Lambda, great developer experience. 👌
This creates a GraphQL server. Send a POST request and it maps queries to resolvers. Send a GET request and you see an Apollo playground so you can try your queries.
Schemas represent the shape of your API.
This will take some manual work. I recommend a Query for every GET endpoint in your API and a Mutation for every POST/PUT/DELETE etc.
Then use something like the walmartlabs schema generator to build type definitions for each endpoint. Some might overlap and that's okay.
To keep code organized I recommend 1 schema file per endpoint –
src/schema/Thing.ts. Like this
There's 300 lines of this crap. You don't wanna write it by hand from scratch 😅
A crawler could be a good idea. Something you point at all the different endpoints and it collects those schema definitions.
You'll have to consolidate and clean up by hand.
Get all your schemas imported and into an array, pass them into ApolloServer as type definitions.
user returns the
Settings etc. Build a mapping that makes sense for your API.
Remember that you can
extend type in any schema to extend existing types. Great for adding queries and mutations.
Resolvers are where you map queries to data. Any data from anywhere. 🤘
For my settings proof-of-concept, it looks like this:
An API wrapper helps with authentication, staying logged in as a user, and sending the right headers with each request.
API.settings() method sends a fetch request to
/api/settings and returns the payload.
Hardcoded to my dev machine because this is just a prototype. You'd want that to be a setting or environment variable of some sort.
The headers also are hardcoded and I stripped the token before sharing.
My login method also is quite ratchet. It uses a demo user's email/pass combination to fake logging into the server. 🤣
You'll need to figure this part out for yourself. Authentication depends on your backend implementation. You might not even need it for some requests.
- GraphQL server
- Turn payloads into schema
- Map queries to endpoints
Where it gets tricky is preserving end-user authentication. You'd need to get cookie/token information from the client or run the login process through your proxy.
Large POST requests could look weird too.
We have some endpoints that accept a JSON blob with tens of parameters. Several kilobytes of data. Stuffing all of that into mutation arguments feels funny.
Maybe you could have 1 parameter that accepts a JSON string 🤔
If you decide to go down this route, expect a schlep followed by "Yay we have GraphQL now" from everyone else on your team. You'll be their hero.
I think it's worth it.
Here's how it works 👇
Then get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career.
"Man, love your simple writing! Yours is the only email I open from marketers and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"
Ready to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization
Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.
Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev
By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️