Skip to content

Instantly share code, notes, and snippets.

@numbata
Created April 4, 2023 20:59
Show Gist options
  • Save numbata/36e60cdd48f7f581abdd9875a85e8b6d to your computer and use it in GitHub Desktop.
Save numbata/36e60cdd48f7f581abdd9875a85e8b6d to your computer and use it in GitHub Desktop.

Revisions

  1. numbata created this gist Apr 4, 2023.
    19 changes: 19 additions & 0 deletions hashid.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    # frozen_string_literal: true

    module Types
    class Hashid < GraphQL::Schema::Scalar
    graphql_name "UID"
    default_scalar true
    description "Unique identifer"

    def self.coerce_input(value, _ctx)
    HashidHelper.decode(value)
    rescue StandardError
    raise GraphQL::CoercionError, "#{value.inspect} is not a valid UID"
    end

    def self.coerce_result(value, _ctx)
    HashidHelper.encode(value)
    end
    end
    end
    22 changes: 22 additions & 0 deletions hashid_helper.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    # frozen_string_literal: true

    require "hashids"

    module HashidHelper
    class << self
    delegate :encode, to: :hashid

    def decode(value)
    hashid.decode(value).first
    end

    private

    def hashid
    @hashid ||= Hashids.new(
    ENV["HASHID_SALT"] || "",
    ENV["HASHID_MIN_LENGTH"] || 10
    )
    end
    end
    end