diff options
author | Bob Van Landuyt <bob@vanlanduyt.co> | 2018-05-21 10:52:24 +0300 |
---|---|---|
committer | Bob Van Landuyt <bob@vanlanduyt.co> | 2018-06-05 21:47:42 +0300 |
commit | aa4b1ae71260720b47695b8a256134f20280f61a (patch) | |
tree | 81020f291d634e76fe0a31d906ed73639f634b7d /lib/gitlab/graphql | |
parent | 287c34ca1f9af4e395493c99623af8437f82d919 (diff) |
Add `present_using` to types
By specifying a presenter for the object type, we can keep the logic
out of `GitlabSchema`.
The presenter gets initialized using the object being presented, and
the context (including the `current_user`).
Diffstat (limited to 'lib/gitlab/graphql')
-rw-r--r-- | lib/gitlab/graphql/present.rb | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/lib/gitlab/graphql/present.rb b/lib/gitlab/graphql/present.rb new file mode 100644 index 00000000000..b060692b334 --- /dev/null +++ b/lib/gitlab/graphql/present.rb @@ -0,0 +1,34 @@ +module Gitlab + module Graphql + class Present + PRESENT_USING = -> (type, presenter_class, *args) do + type.metadata[:presenter_class] = presenter_class + end + + INSTRUMENT_PROC = -> (schema) do + schema.instrument(:field, new) + end + + def self.register! + GraphQL::Schema.accepts_definitions(enable_presenting: INSTRUMENT_PROC) + GraphQL::ObjectType.accepts_definitions(present_using: PRESENT_USING) + end + + def instrument(type, field) + return field unless type.metadata[:presenter_class] + + old_resolver = field.resolve_proc + + resolve_with_presenter = -> (obj, args, context) do + presenter = type.metadata[:presenter_class].new(obj, **context.to_h) + + old_resolver.call(presenter, args, context) + end + + field.redefine do + resolve(resolve_with_presenter) + end + end + end + end +end |