Skip to content
Thrash metal band Overkill performing live at Party.San Open Metal 2017

Your codez is overkill

Tuesday, June 8, 2021

At 1,231 words, this article should take about 5 minutes to read.

Once upon a time, I encountered a bug.

The implementation was for a "View PDF" button: when the user clicks the button, a PDF opens in a new browser tab.

The problem

The code looked a bit like this…

const downloadDocument = (document) =>
  new Promise((resolve, reject) => {
    return axios.get(
      `${ENDPOINT}/${document.id}`, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: AUTH_TOKEN
        },
      }
    ).then(({
      status,
      statusText,
      data
    }) => {
      if (status !== 200) {
        throw new Error(statusText);
      }
      return jwt.decode(data);
    }).then((response) => {
      if (response.responseStatus !== 200) {
        throw new Error(
          response.errors ?
          response.errors[0].message :
          response.responseMessage
        );
      }
      resolve(response);
    }).catch((error) => {
      reject({
        status: 401,
        error: error.message,
      });
    });
  });

const webDownload = () => {
  downloadDocument(document)
    .then((response) => {
      if (!response || response.responseStatus !== 200)
        throw new Error(response);

      const {
        href
      } = response;

      if (!href) throw new Error("No file");

      window.location = href;
    })
    .catch(() => {
      appDispatch({
        type: "APP_ERROR",
        error: "Failed to access the file",
      });
    })
};

<button
  type="button"
  onClick={webDownload}
  className="button"
>
  <Icon name="file-download" />
</button>

The solution

The actual solution I eventually used was to fix the window.location = href line.

It worked but, later that day, I started thinking that the correct answer would be…

Use a link!

If the criteria are: I click a button and the PDF opens in a new tab.

Then the only code needed is;

<a 
  class="button"
  href="/path/to/file.pdf"
  title="View file.pdf"
  target="_blank"
  rel="nofollow noopener noreferrer"
>
  View pdf
</a>

Conclusion

Sometimes codebases are quagmires of over-engineered code that blinker us to the best solution.

It was all too easy to dive into that convoluted code to find the bug - and it was tricky to figure out what was causing the issue because there was so much code to read.

There's nothing really wrong with the code as it is — it handles errors, authenticates requests, JWT encodes traffic, abstracts the download function so it can be used elsewhere; it's just overkill for I click a button and the PDF opens in a new tab.

There are no bugs in the code you didn't write.

PS: Whatever you do, try to avoid this… 🤣

A JavaScript function that essentially does nothing

Cover image courtesy of Wikipedia.

Comments

In almost all cases, the comments section is a cesspool of Reply Guys, racists, and bots.

I don't want to have to deal with that kind of hell so I don't have a comments section.

If you want to continue the conversation, you can always hit me up on Twitter (which is, in it's own way, a vile cesspool of Reply Guys, racists, and bots).

Thomas Banks

Thomas Banks

When I'm not building things for the internet, I take photos of stuff.
Loading Invisible Visible Navigation Close Arrow Info Online Online