DEV Community

Cover image for because copy & paste is tough
Matthew Foley
Matthew Foley

Posted on

because copy & paste is tough

copy and paste is tough
Following up on my post last week about the first aspect of a PR contribution to explore.opensauced.pizza, I'm going to talk about the second aspect of that PR - joyfully implemented as an HTML <select> element (I really like these).

So as I mentioned in the post before:

We also wanted to let users quickly reproduce the queries we use in Open Sauced... this way, when its time to iterate on an existing feature, there's very little friction to finding that starting point.

About a week before this, I had been working on a PR for tabulating the GraphQL API calls in the Open Sauced docs, so a lot of the details about API calls were pretty fresh.

Side note, if you want line breaks inside a table in markdown, you'll need to use a <br/> element, but don't forget to use a self closing tag in the event your markdown file is parsed and used by a tool like Docusaurus, :cough, cough:. Shout out to @0vortex for cleaning up my messes!

Anywho, after looking around at GraphiQL implementations, I came to the belief that most define a fetcher with the correct API endpoint/headers and otherwise things just work out of the box. Once the introspection query is run and the schema parsed and validated, the combination of the Explorer pane and the Query Editor pane make it really easy to build up and run valid queries. There's also a common pattern of using a default query so when the client first loads up, the query is pre-populated. What these two don't help with is reproducing and working with multiple queries.

The approach I wound up taking was to store all of the dynamic queries in an object, and then generate a <select> element in the toolbar, which updates the query contents and query name with the onchange event. Here's the piece of code that does the job...

<GraphiQL.Toolbar>
    <select
        defaultValue={""}
        onChange={(e)=>{
            const key = e.target.value;
            this.handleEditQuery(Queries[key]);
            this.handleEditOperationName(key);
        }}
    >
        <option value="">Choose a Query</option>
        {Object.keys(Queries).filter(key => key !== 'ALL').map(key => {
            const isMutation = Queries[key].trim().indexOf('mutation') === 0;
            return <option key={key} value={key}>{isMutation?"(Mutation) ":""}{key}</option>
        })}
    </select>
    // ...
</GraphiQL.Toolbar>
Enter fullscreen mode Exit fullscreen mode

And here's a screenshot of what it does.
graphiql screenshot

The thing I still want to see work for this repo is supporting persisted queries - really just for the sake of completeness. I have some ideas on how to do it, but perhaps someone reading has done this before?

Top comments (0)