Class: HaveAPI::ClientExamples::JsClient

Inherits:
HaveAPI::ClientExample show all
Defined in:
lib/haveapi/client_examples/js_client.rb

Instance Attribute Summary

Attributes inherited from HaveAPI::ClientExample

#action, #action_name, #base_url, #host, #resource, #resource_path, #version

Instance Method Summary collapse

Methods inherited from HaveAPI::ClientExample

auth, clients, code, example, init, #initialize, label, order, register, #version_url

Constructor Details

This class inherits a constructor from HaveAPI::ClientExample

Instance Method Details

#auth(method, desc) ⇒ Object



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
# File 'lib/haveapi/client_examples/js_client.rb', line 17

def auth(method, desc)
  case method
  when :basic
    <<~END
      #{init}

      api.authenticate("basic", {
        user: "user",
        password: "secret"
      }, function (client, status) {
        console.log("Authenticated?", status);
      });
    END

  when :token
    <<~END
      #{init}

      // Request a new token
      api.authenticate("token", {
        #{auth_token_credentials(desc).map { |k, v| "#{k}: \"#{v}\"" }.join(",\n  ")}
      }, function (client, status) {
        console.log("Authenticated?", status);

        if (status)
          console.log("Token is", client.authProvider.token);
      });

      // Use an existing token
      api.authenticate("token", {
        token: "qwertyuiop..."
      }, function (client, status) {
        console.log("Authenticated?", status);
      });
    END

  when :oauth2
    <<~END
      #{init}
      // The JavaScript client must be configured with OAuth2 access token, it does not
      // support the authorization procedure to obtain a new access token.
      var accessToken = {
        access_token: "the access token"
      };

      // The client is authenticated immediately, no need for a callback
      api.authenticate("oauth2", {access_token: accessToken});
    END
  end
end

#error(sample) ⇒ Object



154
155
156
157
158
159
160
# File 'lib/haveapi/client_examples/js_client.rb', line 154

def error(sample)
  out = ''
  out << "  // reply.isOk() returns false\n"
  out << "  // reply.message() returns the error message\n"
  out << "  // reply.envelope.errors contains parameter errors\n"
  out
end

#example(sample) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/haveapi/client_examples/js_client.rb', line 68

def example(sample)
  args = []

  args.concat(sample[:path_params]) if sample[:path_params]

  if sample[:request] && !sample[:request].empty?
    args << JSON.pretty_generate(sample[:request])
  end

  out = "#{init}\n"
  out << "api.#{resource_path.join('.')}.#{action_name}"
  out << '('
  out << "#{args.join(', ')}, " unless args.empty?

  callback = "function (client, reply) {\n"
  callback << "  console.log('Response', reply);\n"

  callback << if sample[:status]
                response(sample)

              else
                error(sample)
              end

  callback << '}'

  out << callback.strip
  out << ');'
  out
end

#initObject



9
10
11
12
13
14
15
# File 'lib/haveapi/client_examples/js_client.rb', line 9

def init
  <<~END
    import HaveAPI from 'haveapi-client'

    var api = new HaveAPI.Client("#{base_url}", {version: "#{version}"});
  END
end

#response(sample) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/haveapi/client_examples/js_client.rb', line 99

def response(sample)
  out = ''

  case action[:output][:layout]
  when :hash
    out << "# reply is an instance of HaveAPI.Client.Response\n"
    out << "# reply.response() returns an object with output parameters:\n"
    out << JSON.pretty_generate(sample[:response] || {}).split("\n").map do |v|
      "  // #{v}"
    end.join("\n")

  when :hash_list
    out << "# reply is an instance of HaveAPI.Client.Response\n"
    out << "# reply.response() returns an array of objects:\n"
    out << JSON.pretty_generate(sample[:response] || []).split("\n").map do |v|
      "  // #{v}"
    end.join("\n")

  when :object
    out << "  // reply is an instance of HaveAPI.Client.ResourceInstance\n"

    (sample[:response] || {}).each do |pn, pv|
      param = action[:output][:parameters][pn]

      if param[:type] == 'Resource'
        out << "  // reply.#{pn} = HaveAPI.Client.ResourceInstance("
        out << "resource: #{param[:resource].join('.')}, "

        out << if pv.is_a?(::Hash)
                 pv.map { |k, v| "#{k}: #{PP.pp(v, '').strip}" }.join(', ')
               else
                 "id: #{pv}"
               end

        out << ")\n"

      elsif param[:type] == 'Custom' && (pv.is_a?(::Hash) || pv.is_a?(::Array))
        json = JSON.pretty_generate(pv).split("\n").map do |v|
          "  // #{v}"
        end.join("\n")

        out << "  // reply.#{pn} = #{json}"

      else
        out << "  // reply.#{pn} = #{PP.pp(pv, '')}"
      end
    end

  when :object_list
    out << "  // reply is an instance of HaveAPI.Client.ResourceInstanceList\n"
  end

  out
end