Module: DingSDK::Utils

Extended by:
T::Sig
Defined in:
lib/ding_sdk/utils/utils.rb

Defined Under Namespace

Classes: FieldAugmented

Constant Summary collapse

SERIALIZATION_METHOD_TO_CONTENT_TYPE =
{
  'json': 'application/json',
  'form': 'application/x-www-form-urlencoded',
  'multipart': 'multipart/form-data',
  'raw': 'application/octet-stream',
  'string': 'text/plain'
}.freeze

Class Method Summary collapse

Class Method Details

._get_deep_object_query_params(metadata, field_name, obj) ⇒ Object



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/ding_sdk/utils/utils.rb', line 161

def self._get_deep_object_query_params(, field_name, obj)
  params = {}

  return params if obj.nil?

  if obj.respond_to? :fields
    obj_fields = obj.fields
    obj_fields.each do |obj_field|
       = obj_field.[:query_param]
      next if .nil?

      val = obj.send(obj_field.name)
      next if val.nil?

      key = "#{.fetch(:field_name, field_name)}[#{.fetch(:field_name, obj_field.name)}]"
      if val.is_a? Array
        val.each do |v|
          next if v.nil?

          params[key] = [] if !params.include? key

          params[key] << val_to_string(v)
        end
      else
        params[key] = [val_to_string(val)]
      end
    end
  elsif obj.is_a? Hash
    obj.each do |key, value|
      next if value.nil?

      param_key = "#{.fetch(:field_name, field_name)}[#{key}]"
      if value.is_a? Array
        value.each do |val|
          next if val.nil?

          params[param_key] = [] if !params.include? param_key

          params[param_key].append(val_to_string(val))
        end
      else
        params[param_key] = [val_to_string(value)]
      end
    end
  end
  params
end

._get_delimited_query_params(metadata, field_name, obj, delimiter) ⇒ Object



226
227
228
229
230
231
232
233
234
235
236
# File 'lib/ding_sdk/utils/utils.rb', line 226

def self._get_delimited_query_params(, field_name, obj, delimiter)
  get_query_param_field_name = lambda do |obj_field|
     = obj_field.[:query_param]

    return '' if .nil?

    return .fetch(:field_name, obj_field.name)
  end

  _populate_form(field_name, .fetch(:explode, true), obj, delimiter, &get_query_param_field_name)
end

._get_serialized_params(metadata, field_name, obj) ⇒ Object



213
214
215
216
217
218
219
220
# File 'lib/ding_sdk/utils/utils.rb', line 213

def self._get_serialized_params(, field_name, obj)
  params = {}

  serialization = .fetch(:serialization, '')
  params[.fetch(:field_name, field_name)] = obj.marshal_json if serialization == 'json'

  params
end

._parse_basic_auth_scheme(req, scheme) ⇒ Object



466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# File 'lib/ding_sdk/utils/utils.rb', line 466

def self._parse_basic_auth_scheme(req, scheme)
  username, password = ''

  scheme_fields = scheme.fields
  scheme_fields.each do |scheme_field|
     = scheme_field.[:security]
    next if .nil? || !.include?(:field_name)

    field_name = [:field_name]
    value = scheme.send(scheme_field.name)

    username = value if field_name == 'username'
    password = value if field_name == 'password'
  end

  data = "#{username}:#{password}".encode
  # Use strict_encode, because encode adds newlines after 60 chars
  # https://docs.ruby-lang.org/en/3.0/Base64.html#method-i-encode64
  req.headers['Authorization'] = "Basic #{Base64.strict_encode64(data)}"
end

._parse_security_option(req, option) ⇒ Object



394
395
396
397
398
399
400
401
402
# File 'lib/ding_sdk/utils/utils.rb', line 394

def self._parse_security_option(req, option)
  opt_fields = option.fields
  opt_fields.each do |opt_field|
     = opt_field.[:security]
    next if .nil? || !.include?(:scheme)

    _parse_security_scheme(req, , option.send(opt_field.name))
  end
end

._parse_security_scheme(req, scheme_metadata, scheme) ⇒ Object



405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# File 'lib/ding_sdk/utils/utils.rb', line 405

def self._parse_security_scheme(req, , scheme)
  scheme_type = [:type]
  sub_type = [:sub_type]

  if scheme.respond_to? :fields
    if scheme_type == 'http' && sub_type == 'basic'
      _parse_basic_auth_scheme(req, scheme)
      return
    end

    scheme_fields = scheme.fields
    scheme_fields.each do |field|
       = field.[:security]
      next if .nil? || [:field_name].nil?

      value = scheme.send(field.name)
      _parse_security_scheme_value(req, , , value)
    end
  else
    _parse_security_scheme_value(req, , , scheme)
  end
end

._parse_security_scheme_value(req, scheme_metadata, security_metadata, value) ⇒ Object



432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
# File 'lib/ding_sdk/utils/utils.rb', line 432

def self._parse_security_scheme_value(req, , , value)
  scheme_type = [:type]
  sub_type = [:sub_type]

  header_name = [:field_name]

  case scheme_type
  when 'apiKey'
    case sub_type
    when 'header'
      req.headers[header_name] = value
    when 'query'
      req.params[header_name] = value
    when 'cookie'
      req.cookies[header_name] = value
    else
      raise StandardError, 'not supported'
    end
  when 'openIdConnect'
    req.headers[header_name] = value.downcase.start_with?('bearer ') ? value : "Bearer #{value}"
  when 'oauth2'
    req.headers[header_name] = value.downcase.start_with?('bearer ') ? value : "Bearer #{value}"
  when 'http'
    if sub_type == 'bearer'
      req.headers[header_name] = value.downcase.start_with?('bearer ') ? value : "Bearer #{value}"
    else
      raise StandardError, 'not supported'
    end
  else
    raise StandardError, 'not supported'
  end
end

._populate_form(field_name, explode, obj, delimiter, &get_field_name_lambda) ⇒ Object



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
153
154
155
# File 'lib/ding_sdk/utils/utils.rb', line 100

def self._populate_form(field_name, explode, obj, delimiter, &get_field_name_lambda)
  params = {}

  return params if obj.nil?

  if obj.respond_to? :fields
    items = []
    obj_fields = obj.fields
    obj_fields.each do |obj_field|
      obj_field_name = get_field_name_lambda.call(obj_field)
      next if obj_field_name == ''

      val = obj.send(obj_field.name.to_sym)
      next if val.nil?

      if explode
        params[obj_field_name] = [val_to_string(val)]
      else
        items.append("#{obj_field_name}#{delimiter}#{val_to_string(val)}")
      end
    end

    params[field_name] = [items.join(delimiter)] if !items.empty?
  elsif obj.is_a? Hash
    items = []
    obj.each do |key, value|
      next if value.nil?

      if explode
        params[key] = val_to_string(value)
      else
        items.append("#{key}#{delimiter}#{val_to_string(value)}")
      end
    end
    params[field_name] = [items.join(delimiter)] if !items.empty?

  elsif obj.is_a? Array
    items = []
    obj.each do |value|
      next if value.nil?

      if explode
        params[field_name] = [] if !params.key? field_name

        params[field_name].append(val_to_string(value))
      else
        items.append(val_to_string(value))
      end
    end
    params[field_name] = items.map(&:to_s).join(delimiter) if !items.empty?

  else
    params[field_name] = val_to_string(obj)
  end
  params
end

._populate_from_globals(param_name, value, param_type, gbls) ⇒ Object



724
725
726
727
728
729
730
# File 'lib/ding_sdk/utils/utils.rb', line 724

def self._populate_from_globals(param_name, value, param_type, gbls)
  if value.nil? && !gbls.nil?
    global_value = gbls.dig(:parameters, param_type.to_sym, param_name.to_sym)
    value = global_value if !global_value.nil?
  end
  value
end

._serialize_header(explode, obj) ⇒ Object



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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/ding_sdk/utils/utils.rb', line 49

def self._serialize_header(explode, obj)
  return '' if obj.nil?

  if obj.respond_to? :fields
    items = []
    obj_fields = obj.fields
    obj_fields.each do |obj_field|
       = obj_field.[:header]
      next if .nil?

      obj_field_name = .fetch(:field_name, obj_field.name)
      next if obj_field_name == ''

      val = obj.send(obj_field.name)
      next if val.nil?

      if explode
        items.append("#{obj_field_name}=#{val_to_string(val)}")
      else
        items.append(obj_field_name)
        items.append(val_to_string(val))
      end
    end

    items.join(',') if !items.empty?
  elsif obj.is_a? Hash
    items = []
    obj.each do |key, value|
      next if value.nil?

      if explode
        items.append("#{key}=#{val_to_string(value)}")
      else
        items.append(key)
        items.append(val_to_string(value))
      end
    end

    items.join(',') if !items.empty?
  elsif obj.is_a? Array
    items = obj.filter { |v| !v.nil? }.map { |v| val_to_string(v) }.join(',')
  else
    val_to_string(obj)
  end
end

.configure_request_security(req, security) ⇒ Object



371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# File 'lib/ding_sdk/utils/utils.rb', line 371

def self.configure_request_security(req, security)
  sec_fields = security.fields
  sec_fields.each do |sec_field|
    value = security.send(sec_field.name)
    next if value.nil?

     = sec_field.[:security]
    next if .nil?

    _parse_security_option(req, value) if [:option]

    if [:scheme]
      # Special case for basic auth which could be a flattened struct
      if [:sub_type] == 'basic' && !value.respond_to?(:fields)
        _parse_security_scheme(req, , security)
      else
        _parse_security_scheme(req, , value)
      end
    end
  end
end

.date_from_iso_format(optional) ⇒ Object



497
498
499
500
501
502
503
# File 'lib/ding_sdk/utils/utils.rb', line 497

def self.date_from_iso_format(optional)
  lambda do |s|
    return nil if optional && s.nil?

    return Date.iso8601(s)
  end
end

.datetime_from_iso_format(optional) ⇒ Object



488
489
490
491
492
493
494
# File 'lib/ding_sdk/utils/utils.rb', line 488

def self.datetime_from_iso_format(optional)
  lambda do |s|
    return nil if optional && s.nil?

    return DateTime.strptime(s, '%Y-%m-%dT%H:%M:%S.%NZ')
  end
end

.encode_form(form) ⇒ Object



643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
# File 'lib/ding_sdk/utils/utils.rb', line 643

def self.encode_form(form)
  payload = {}
  form.each do |field_name, field|
    if field.length == 2
      if field[0].nil?
        payload[field_name] = field[1]
      else
        payload[field_name] = Faraday::Multipart::FilePart.new(field[0], '', field[1])
      end
    elsif field.length == 3
      payload[field_name] = Faraday::Multipart::ParamPart.new(field[1].to_json, field[2])
    end
  end
  payload
end

.enum_from_string(enum_type, optional) ⇒ Object



509
510
511
512
513
514
515
# File 'lib/ding_sdk/utils/utils.rb', line 509

def self.enum_from_string(enum_type, optional)
  lambda do |s|
    return nil if optional && s.nil?

    return enum_type.deserialize(s)
  end
end

.field_name(name) ⇒ Object



518
519
520
# File 'lib/ding_sdk/utils/utils.rb', line 518

def self.field_name(name)
  proc { |_, field_name = name| field_name }
end

.generate_url(clazz, server_url, path, path_params, gbls = nil) ⇒ Object



283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'lib/ding_sdk/utils/utils.rb', line 283

def self.generate_url(clazz, server_url, path, path_params, gbls = nil)
  clazz.fields.each do |f|
     = f.[:path_param]
    next if .nil?

    if .fetch(:style, 'simple') == 'simple'
      param = path_params.send(f.name) if !path_params.nil?
      param = _populate_from_globals(f.name, param, 'pathParam', gbls)
    end

    f_name = .fetch(:field_name, f.name)
    serialization = .fetch(:serialization, '')
    if serialization != ''
      serialized_params = _get_serialized_params(, f_name, param)
      serialized_params.each do |k, v|
        path = path.sub("{#{k}}", v)
      end
    else
      if param.is_a? Array
        pp_vals = []
        param.each do |pp_val|
          pp_vals.append(pp_val.to_s)
        end
        path = path.sub("{#{.fetch(:field_name, f.name)}}", pp_vals.join(','))
      elsif param.is_a? Hash
        pp_vals = []
        param.each do |pp_key, pp_val|
          value = val_to_string(pp_val)

          if .fetch(:explode, false)
            pp_vals.append("#{pp_key}=#{value}")
          else
            pp_vals.append("#{pp_key},#{value}")
          end
        end
        path = path.sub("{#{.fetch(:field_name, f.name)}}", pp_vals.join(','))
      elsif !(param.is_a?(String) || param.is_a?(Integer) ||
        param.is_a?(Float) || param.is_a?(Complex) || param.is_a?(TrueClass) ||
        param.is_a?(FalseClass))
        pp_vals = []
        attrs = param.fields.filter { |field| field.name && param.respond_to?(field.name.to_sym) }.map(&:name)
        attrs.each do |attr|
          field = param.field(attr)

           = field.[:path_param]

          next if .nil?

          parm_name = .fetch(:field_name, f.name)

          param_field_val = param.send(attr)

          if param_field_val.is_a? T::Enum
            param_field_val = param_field_val.serialize
          elsif param_field_val.is_a? DateTime
            param_field_val = param_field_val.strftime('%Y-%m-%dT%H:%M:%S.%NZ')
          end
          if !field.nil? && T::Utils::Nilable.is_union_with_nilclass(field.type) && param_field_val.nil?
            next
          elsif .fetch(:explode, false)
            pp_vals.append("#{parm_name}=#{param_field_val}")
          else
            pp_vals.append("#{parm_name},#{param_field_val}")
          end
        end
        path = path.sub("{#{.fetch(:field_name, f.name)}}", pp_vals.join(','))
      else
        path = path.sub("{#{.fetch(:field_name, f.name)}}", param.to_s)
      end
    end
  end

  server_url.delete_suffix('/') + path
end

.get_headers(headers_params) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/ding_sdk/utils/utils.rb', line 33

def self.get_headers(headers_params)
  return {} if headers_params.nil?

  headers = {}
  param_fields = headers_params.fields
  param_fields.each do |f|
     = f.[:header]
    next if .nil?

    value = _serialize_header(.fetch(:explode, false), headers_params.send(f.name))
    headers[.fetch(:field_name, f.name)] = value if !value.empty?
  end
  headers
end

.get_query_params(clazz, query_params, gbls = nil) ⇒ Object



239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/ding_sdk/utils/utils.rb', line 239

def self.get_query_params(clazz, query_params, gbls = nil)
  params = {}
  param_fields = clazz.fields
  param_fields.each do |f|
     = f.[:request]
    next if !.nil?

     = f.[:query_param]
    next if .nil?

    param_name = f.name
    value = query_params&.send(param_name.to_sym)
    value = _populate_from_globals(param_name, value, 'queryParam', gbls)

    f_name = [:field_name]
    serialization = .fetch(:serialization, '')
    if serialization != ''
      params = params.merge _get_serialized_params(
        , f_name, value
      )
    else
      style = .fetch(:style, 'form')
      case style
      when 'deepObject'
        params = params.merge _get_deep_object_query_params(
          , f_name, value
        )
      when 'form'
        params = params.merge _get_delimited_query_params(
          , f_name, value, ','
        )
      when 'pipeDelimited'
        params = params.merge _get_delimited_query_params(
          , f_name, value, '|'
        )
      else
        raise StandardError, 'not yet implemented'
      end
    end
  end
  params
end

.marshal_json_complex(complex) ⇒ Object



733
734
735
736
737
738
739
740
741
742
743
# File 'lib/ding_sdk/utils/utils.rb', line 733

def self.marshal_json_complex(complex)
  if complex.is_a? Array
    complex.map { |v| Utils.marshal_json_complex(v) }.to_json
  elsif complex.is_a? Hash
    complex.transform_values { |v| Utils.marshal_json_complex(v) }.to_json
  elsif complex.respond_to? :marshal_json
    complex.marshal_json
  else
    complex.to_json
  end
end

.match_content_type(content_type, pattern) ⇒ Object



359
360
361
362
363
364
365
366
367
368
# File 'lib/ding_sdk/utils/utils.rb', line 359

def self.match_content_type(content_type, pattern)
  return true if content_type == pattern || pattern == '*' || pattern == '*/*'

  pieces = content_type.split(';')
  pieces.each do |piece|
    return true if pattern == piece.strip
  end

  false
end

.parse_field(field, data_class) ⇒ Object



570
571
572
573
574
575
576
577
578
# File 'lib/ding_sdk/utils/utils.rb', line 570

def self.parse_field(field, data_class)
   = field.[:metadata_string]
  return nil if .nil?

  field_value = data_class.send(field.name)
  return nil if field_value.nil?

  field_value
end

.serialize_content_type(field_name, media_type, request) ⇒ Object

Raises:

  • (StandardError)


560
561
562
563
564
565
566
567
# File 'lib/ding_sdk/utils/utils.rb', line 560

def self.serialize_content_type(field_name, media_type, request)
  return media_type, marshal_json_complex(request), nil if media_type.match('(application|text)\/.*?\+*json.*')
  return serialize_multipart_form(media_type, request) if media_type.match('multipart\/.*')
  return media_type, serialize_form_data(field_name, request), nil if media_type.match('application\/x-www-form-urlencoded.*')
  return media_type, request, nil if request.is_a?(String) || request.is_a?(Array)

  raise StandardError, "invalid request body type #{type(request)} for mediaType {metadata['media_type']}"
end

.serialize_form_data(field_name, data) ⇒ Object



663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
# File 'lib/ding_sdk/utils/utils.rb', line 663

def self.serialize_form_data(field_name, data)
  get_form_field_name = lambda do |obj_field|
     = obj_field.[:form]

    return '' if .nil?

    return .fetch(:field_name, obj_field.name)
  end

  form = {}
  if data.respond_to? :fields
    data.fields.each do |field|
      val = data.send(field.name)
      next if val.nil?

       = field.[:form]

      next if .nil?

      field_name = .fetch(:field_name, field.name)

      if [:json]
        form[field_name] = marshal_json_complex(val)
      else
        if .fetch(:style, 'form') == 'form'
          form = form.merge(
            _populate_form(
              field_name, .fetch(:explode, true), val, ',', &get_form_field_name
            )
          )
        else
          raise StandardError, "Invalid form style for field #{field.name}"
        end
      end
    end
  elsif data.is_a? Hash
    data.each do |key, value|
      form[key] = [val_to_string(value)]
    end
  else
    raise StandardError, "Invalid request body type for field #{field_name}"
  end

  form
end

.serialize_multipart_form(media_type, request) ⇒ Object



581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
# File 'lib/ding_sdk/utils/utils.rb', line 581

def self.serialize_multipart_form(media_type, request)
  form = []
  request_fields = request.fields
  request_fields.each do |field|
    val = request.send(field.name)
    next if val.nil?

     = field.[:multipart_form]
    next if .nil?

    if [:file] == true
      file_fields = val.fields

      file_name = ''
      field_name = ''
      content = nil

      file_fields.each do |file_field|
         = file_field.[:multipart_form]
        next if .nil?

        if [:content] == true
          content = val.send(file_field.name)
        else
          field_name = .fetch(:field_name, file_field.name)
          file_name = val.send(file_field.name)
        end
      end
      raise StandardError, 'invalid multipart/form-data file' if field_name == '' || file_name == '' || content == nil?

      form.append([field_name, [file_name, content]])
    elsif [:json] == true
      to_append = [
        .fetch(:field_name, field.name), [
          nil, marshal_json_complex(val), 'application/json'
        ]
      ]
      form.append(to_append)
    else
      field_name = .fetch(
        :field_name, field.name
      )
      if val.is_a? Array
        val.each do |value|
          next if value.nil?

          form.append(
            ["#{field_name}[]", [nil, val_to_string(value)]]
          )
        end
      else
        form.append([field_name, [nil, val_to_string(val)]])
      end
    end
  end
  [media_type, nil, form]
end

.serialize_request_body(request, request_field_name, serialization_method) ⇒ Object

Raises:

  • (StandardError)


534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
# File 'lib/ding_sdk/utils/utils.rb', line 534

def self.serialize_request_body(request, request_field_name, serialization_method)
  return ['', nil, nil] if request.nil?

  return serialize_content_type(request_field_name, SERIALIZATION_METHOD_TO_CONTENT_TYPE[serialization_method], request) if !request.respond_to?(:fields) || !request.respond_to?(request_field_name)

  request_val = request.send(request_field_name)

  request_fields = request.fields
   = nil
  request_fields.each do |f|
    if f.name == request_field_name
       = f.[:request]
      break
    end
  end
  raise StandardError, 'invalid request type' if .nil?

  serialize_content_type(
    :request, .fetch(:media_type, 'application/octet-stream'), request_val
  )
end

.template_url(url_with_params, params) ⇒ Object



710
711
712
713
714
715
716
717
718
719
720
721
# File 'lib/ding_sdk/utils/utils.rb', line 710

def self.template_url(url_with_params, params)
  params.each do |key, value|
    if value.respond_to? :serialize
      val_str = value.serialize
    else
      val_str = value
    end
    url_with_params = url_with_params.gsub("{#{key}}", val_str)
  end

  url_with_params
end

.unmarshal_complex(data, type) ⇒ Object



746
747
748
749
750
751
752
753
# File 'lib/ding_sdk/utils/utils.rb', line 746

def self.unmarshal_complex(data, type)
  begin
    value = unmarshal_json(JSON.parse(data), type)
  rescue TypeError, JSON::ParserError
    value = unmarshal_json(data, type)
  end
  value
end

.unmarshal_json(data, type) ⇒ Object



756
757
758
759
760
761
762
763
764
765
766
767
768
769
# File 'lib/ding_sdk/utils/utils.rb', line 756

def self.unmarshal_json(data, type)
  if T.simplifiable? type
    type = T.simplify_type type
  end
  if type.respond_to? :unmarshal_json
    type.unmarshal_json(data)
  elsif T.arr? type
    data.map { |v| Utils.unmarshal_complex(v, T.arr_of(type)) }
  elsif T.hash? type
    data.transform_values { |v| Utils.unmarshal_complex(v, T.hash_of(type)) }
  else
    data
  end
end

.val_to_string(val, primitives: true) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/ding_sdk/utils/utils.rb', line 20

def self.val_to_string(val, primitives: true)
  if val.is_a? T::Enum
    val.serialize
  elsif val.is_a? DateTime
    val.strftime('%Y-%m-%dT%H:%M:%S.%NZ')
  elsif primitives
    val.to_s
  else
    val
  end
end