Created
April 4, 2023 20:59
-
-
Save numbata/36e60cdd48f7f581abdd9875a85e8b6d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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