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.
# 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
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment