DEV Community

Cover image for Leveraging AI and GitHub Copilot in Shopify App Development
Josh Boddy
Josh Boddy

Posted on

Leveraging AI and GitHub Copilot in Shopify App Development

AI is very quickly becoming an integral part of the development experience. We’re seeing new innovations every day and each one finds a new way to shake up the programming space irreversibly. ChatGPT and Copilot are the main culprits and since their respective launches, most developers know when they’re beat and try to leverage these tools to write code not only more efficiently, but also much faster. You can use these tools to 10X your development flow within any context but if you know Flare, then you know we’re about to show you how to use it to write quick and effective Shopify Applications.

With tools like Devin being released, slowly developers are becoming less and less necessary for the development of commercial applications as a whole. Learning to use these tools effectively as they appear will ensure career longevity in a world where programming skills are becoming less valuable.

Note: Copilot is a paid service from GitHub, you will have to pay a monthly fee for the service if you have already used your free trial. ChatGPT is free up to a point, however, in order to use their newest models, you will have to pay a fee for that as well.

What can AI do for me?

This is where all developers start, the real question is “if I’m a good enough developer, do I really need to use AI tools?” the simple answer is yes. The more complex answer is that AI does what we humans do (it trained off the back of what we’ve achieved in the last 50 or so years of computing) and leverages the ability to access all that knowledge and apply it context. Think of AI as a seasoned, 70 year old developer standing over your desk and telling you exactly what to type… but without the frustrated and disappointed scowls. GitHub Copilot’s code generation inline will help with contextual development on a small scale, you can quickly write a comment for a function that you can’t be bothered to write and copilot will go ahead and do the heavy lifting. Alternatively if you want a larger snippet then head to ChatGPT (or a GPT alternative like Bard) and watch the magic as you describe intricate functionality and it supplies you with a well formatted article-esque response containing code files you can just copy and paste to build your project. If you think something is going to take a long time, try a GPT model first and give yourself at the very least a starting point to get going from.

The drawbacks

As much as it’s nice having a nice seasoned developer on your shoulder to guide you through your project / bug fix, ChatGPT and Copilot are definitely not flawless and have a few quirks that you need to understand and get to know before being able to leverage them to their fullest extent.

Code clarity is key

This one is specifically for Copilot. It’s a really useful tool but struggles a lot with messy codebases. It takes the code that you’ve already written and tries to intelligently suggest auto-completions to help make the development experience easier, but as is always the problem with machines, it struggles to manage human error and messiness. If it can’t read your code and figure out what you’re trying to do, then it can’t help you do things. It’s simple. You’ve got to imagine showing your code to a senior developer and asking for help. If they can’t read your code how can they help you? They can’t. This means that code clarity and good organisation, as well as clarity in naming variables and functions are important to ensuring Copilot suggestions are relevant and helpful.

That’s so 2010…

ChatGPT and Copilot are trained on historical data. As in, the data on the internet up until September 2021 (Jan 2022 in newer models) but still outdated all the same. Should you choose to use Agents on ChatGPT you can have them scrape custom documents and the internet for more info, but it will always be outdated just slightly, and as such cannot always be relied upon entirely. Take for instance Shopify’s Polaris components. The team behind Polaris are constantly updating the library and as such you can run into components that are deprecated or even removed outright when asking a GPT to generate code with the Polaris component library, because it’s referencing a version of Polaris that is no longer the latest version. As such you have to maintain a bit of caution or just feed in the newest version of the docs as text into ChatGPT but that becomes more tedious that just writing the code yourself. However, you can get around this by getting it to generate scripts using the older library version and feeding in the relevant pieces of info to help update it.

Don’t be too reliant

While these tools are all great they make for very bad programmers. If you rely too heavily on ChatGPT or Copilot and it generates a piece of code that you don’t understand or can’t understand, then you need to tread with care. If that piece of code either throws an error or generates a logic error then you are going to spend even longer cleaning up those repercussions than you would’ve spent writing that code from scratch. Make sure that when you generate code you understand what each line is doing in detail in order to rectify any mistakes that it could make down the line. You can ask Copilot or your GPT model to explain the code it gives you in order to help increase your understanding of what’s going on to avoid this situation entirely.

Usage in Shopify App Development

All of the points above hold strong in any development environment, but we’re here to talk about Shopify App development, so let’s do that. Within your app you can apply AI tools to a few different areas and in a few different ways to acquire an incredible amount of power in your projects. Here are a few places that I see these tools really shine for Shopify App development in particular.

GraphQL Response Structure Inference

GraphQL is powerful but a little confusing to work with for some. Especially if you are used to non-document based DB interactions like SQL. Copilot is incredibly useful for understanding the structure of responses from GraphQL queries if formatted correctly. Supply a GraphQL string query such as the one below.

const GET_ORDER_FULFILLMENT_ID_QUERY = `
    query getOrderFulfillmentId($id: ID!) {
        order(id: $id) {
            displayFulfillmentStatus
            fulfillmentOrders(first: 50) {
                edges {
                    node {
                        id
                        status
                        deliveryMethod {
                            methodType
                        }
                        lineItems(first: 100) {
                          edges {
                            node {
                              id
                              sku
                              totalQuantity
                            }
                          }
                        }
                    }
                }
            }
        }
    }
`;
Enter fullscreen mode Exit fullscreen mode

Queries like this can be quite difficult to read, understand and handle the response of. With Copilot, once this query is called it can infer the response of the query as well as generate code to handle errors, helping deal with those long nested objects that allow you to access the data.

Repeated calls to a Database or GraphQL

If you wish to repeat a similar query with some slight adjustments then Copilot can very easily substitute those values for you through what I’m calling a “smart, enriched copy and paste” where in it will infer the value you wish to retrieve or modify and adjust the snippet you’ve already written just slightly to address the correct location.

export async function setShopPlanActive(shop) {
  const command = new UpdateCommand({
    TableName: "shopifyPaymentPlans",
    Key: {
      shop,
    },
    UpdateExpression: "set planStatus = :s",
    ExpressionAttributeValues: {
      ":s": "ACTIVE",
    },
    ReturnValues: "ALL_NEW",
  });
  try {
    await dbClient.send(command);
    return true;
  } catch (err) {
    console.error(err);
    return false;
  }
}
Enter fullscreen mode Exit fullscreen mode

The above function runs an update command on a DynamoDB table to change the value of a shop’s payment plan to active. We can simply write the function name for setShopPlanInactive and watch as Copilot takes the function above and adjusts all the relevant values to generate the rest of the function without us having to manually sift through and change that data.

export async function setShopPlanInactive(shop) {
  const command = new UpdateCommand({
    TableName: "shopifyPaymentPlans",
    Key: {
      shop,
    },
    UpdateExpression: "set planStatus = :s",
    ExpressionAttributeValues: {
      ":s": "INACTIVE",
    },
    ReturnValues: "ALL_NEW",
  });
  try {
    await dbClient.send(command);
    return true;
  } catch (err) {
    console.error(err);
    return false;
  }
}
Enter fullscreen mode Exit fullscreen mode

This is one of my favourite features of Copilot as boilerplate code is always a hassle to repeat, and this means you can focus more time on the interesting problem solving of programming rather than re-writing the same function but slightly differently.

GraphQL Query Generation with Efficiency

Because GraphQL is a bit of a complex query structure language, it can sometimes be hard to tell if you are pulling the optimal amount of data with the least number of queries. We can leverage a GPT model to help us generate GraphQL queries (watch out for the API version) and allow it to do the heavy lifting in terms of query structure for us. This is as simple as asking your model to generate a query that pulls in all orders and their respective users from the last 12 months, and watching it spit out a nice GQL structure for you to copy and paste. The power of converting human readable language to code should never be underestimated.

Vanilla JS in seconds

We’ve talked before about leveraging Vanilla JS in your app blocks and app embeds to enhance your app’s functionality, but sadly not many people are used to using Vanilla JS anymore as frameworks like React and Svelte have become increasingly popular. As such, you may find yourself not knowing how to implement some functionality in your frontend. Copilot and GPT models can do this work for you as well, however be cautious that it doesn’t know the code will be injected in the page with the app block. You can use this to generate functions and efficient code snippets to implement frontend functionality without the hassle of having to relearn what a DOM is.

Summary

Leveraging AI is not without it’s risks and caveats, but if understood and used correctly it can 10X your development workflow and skyrocket productivity. These tools can be applied to any area of your Shopify Apps (frontend, backend, App Bridge, etc.) and when paired with a consistent and tidy codebase can be used to do half the development work for you. Make sure you understand the risks before implementing but spending time on this new wave of tech is definitely not a waste.

Happy coding,

~ Josh

Top comments (0)