Search code examples
javascriptapolloes6-classlit-html

Dealing with class method name conflicts in JavaScript


tl;dr:

My class' method name conflicts with the same name on the class it extends from. I could just rename my class, but I'd prefer a solution which doesn't require a breaking change.

Background

I publish a library called lit-apollo, which exports a class that extends from LitElement. Users are meant to define their own customElements with my class, those elements then can use apollo graphql for data, and render using lit-html. See README for a simple example.

The Problem

LitElement's latest version exposes an instance method called update, which implementations can optionally override to control how and when the element renders. My library also has an update property, which corresponds the the update option of Apollo mutation constructors.

import gql from 'graphql-tag'
import { ApolloMutation, html } from 'lit-apollo/apollo-mutation'

const mutation = gql`
    mutation($id: ID!) {
      MyMutation(id: $id) {
        myResponse
      }
    }
`

const updateFunc = (cache, response) => 
  cache.writeData(doSomethingWith(cache, response))

class MutatingElement extends ApolloMutation {
  constructor() {
      this.mutation = mutation;
      this.variables = {id: "foo"};
      // here's where we break the LitElement contract
      this.update = updateFunc;
  }

  render() {
    return html`<div>${this.data.myResponse}</div>`
  }
}

customElements.define('mutating-element', MutatingElement)

These two methods, clearly are conflicting.

The Question

I know I could just issue a breaking change to lit-apollo which renames it's own update method to onUpdate or some similar, but how might I address this problem without breaking my classes' APIs and thus requiring a major version?

I've though of checking the first argument to see if it's an instance of ApolloCache, then routing the args to super.update as needed, but I think that would break the LitElement contract, preventing users from implementing their own version of LitElement's update

How would you deal with this situation?


Solution

  • I know I could just issue a breaking change to lit-apollo, but how might I address this problem without breaking my classes' APIs?

    You cannot, really. But it's not your fault:

    LitElement's latest version exposes an instance method called update

    That was the breaking change. So if you update your lit-element dependency to the latest version, you have to make a major version as well. Renaming your update method for that is natural. Alternatively, keep your API and continue using the old lit-element version.