graphile / global-ids

[EXPERIMENTAL] Allows you to use Relay global object identifiers in more places.
MIT License
9 stars 1 forks source link

Request: option to automatically add `@deprecated` tags #3

Closed marshall007 closed 5 years ago

marshall007 commented 5 years ago

Would be nice if the plugin could be configured to automatically add @deprecated tags to non-NodeID foreign key properties in the generated schema. For example, given a text column posts.created_by with a FK to users.username:

type User implements Node {
  # `username` is the PK column, and custom PK columns usually implies that
  # meaningful (non-random) data is being stored. As a result, I think we
  # should probably not deprecate custom PK columns by default?
  username: String!
  nodeId: ID!
}

type Post implements Node {
  id: UUID! @deprecated(reason: "Prefer using the Relay global identifier property instead: `nodeId`.")
  nodeId: ID!

  createdBy: String! @deprecated(reason: "Prefer using the Relay global identifier property instead: `createdByUser.nodeId`.")
  createdByUser: User

  createdDate: Datetime!
}

This would be useful for steering consistent usage across front-end developers/clients.

benjie commented 5 years ago

Here's a starting point; maybe you'd like to tidy it up, add tests, and turn it into a PR?

module.exports = builder => {
  builder.hook("GraphQLObjectType:fields:field", (field, build, context) => {
    const {
      scope: { pgFieldIntrospection }
    } = context;
    if (!pgFieldIntrospection || pgFieldIntrospection.kind !== "attribute") {
      return field;
    }
    const attribute = pgFieldIntrospection;
    const table = pgFieldIntrospection.class;
    if (!table) {
      return field;
    }
    const attributeIsInPrimaryKey =
      table.primaryKeyConstraint && table.primaryKeyConstraint.keyAttributes.indexOf(attribute) >= 0;
    const attributeIsInForeignKeys = table.constraints.some(constraint => {
      if (constraint.type === "f") {
        return constraint.keyAttributes.indexOf(attribute) >= 0;
      }
      return false;
    });
    if (!attributeIsInPrimaryKey && !attributeIsInForeignKeys) {
      return field;
    }
    return {
      ...field,
      deprecationReason: "fish"
    };
  });
};
benjie commented 5 years ago

Screenshot 2019-04-18 08 04 50