summaryrefslogtreecommitdiff
path: root/lib/api/helpers/packages/npm.rb
blob: 34e126c73fcb1ced55b3d5d98368de1e51753298 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# frozen_string_literal: true

module API
  module Helpers
    module Packages
      module Npm
        include Gitlab::Utils::StrongMemoize
        include ::API::Helpers::PackagesHelpers

        NPM_ENDPOINT_REQUIREMENTS = {
          package_name: API::NO_SLASH_URL_PART_REGEX
        }.freeze

        def endpoint_scope
          params[:id].present? ? :project : :instance
        end

        def project
          strong_memoize(:project) do
            case endpoint_scope
            when :project
              user_project
            when :instance
              # Simulate the same behavior as #user_project by re-using #find_project!
              # but take care if the project_id is nil as #find_project! is not designed
              # to handle it.
              project_id = project_id_or_nil

              not_found!('Project') unless project_id

              find_project!(project_id)
            end
          end
        end

        def project_or_nil
          # mainly used by the metadata endpoint where we need to get a project
          # and return nil if not found (no errors should be raised)
          strong_memoize(:project_or_nil) do
            next unless project_id_or_nil

            find_project(project_id_or_nil)
          end
        end

        def project_id_or_nil
          strong_memoize(:project_id_or_nil) do
            case endpoint_scope
            when :project
              params[:id]
            when :instance
              package_name = params[:package_name]
              namespace_path = ::Packages::Npm.scope_of(package_name)
              next unless namespace_path

              namespace = Namespace.top_most
                                   .by_path(namespace_path)
              next unless namespace

              finder = ::Packages::Npm::PackageFinder.new(
                package_name,
                namespace: namespace,
                last_of_each_version: false
              )

              finder.last&.project_id
            end
          end
        end
      end
    end
  end
end