forked from redpanda-data/connect
-
Notifications
You must be signed in to change notification settings - Fork 1
/
methods_structured.go
1674 lines (1558 loc) · 50 KB
/
methods_structured.go
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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
153
154
155
156
157
158
159
160
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
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
281
282
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package query
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"sort"
"strings"
"github.com/Jeffail/gabs/v2"
jsonschema "github.com/xeipuuv/gojsonschema"
)
var _ = registerSimpleMethod(
NewMethodSpec(
"all",
"Checks each element of an array against a query and returns true if all elements passed. An error occurs if the target is not an array, or if any element results in the provided query returning a non-boolean result. Returns false if the target array is empty.",
).InCategory(
MethodCategoryObjectAndArray,
"",
NewExampleSpec("",
`root.all_over_21 = this.patrons.all(patron -> patron.age >= 21)`,
`{"patrons":[{"id":"1","age":18},{"id":"2","age":23}]}`,
`{"all_over_21":false}`,
`{"patrons":[{"id":"1","age":45},{"id":"2","age":23}]}`,
`{"all_over_21":true}`,
),
).Param(ParamQuery("test", "A test query to apply to each element.", false)),
func(args *ParsedParams) (simpleMethod, error) {
queryFn, err := args.FieldQuery("test")
if err != nil {
return nil, err
}
return func(res any, ctx FunctionContext) (any, error) {
arr, ok := res.([]any)
if !ok {
return nil, NewTypeError(res, ValueArray)
}
if len(arr) == 0 {
return false, nil
}
for i, v := range arr {
res, err := queryFn.Exec(ctx.WithValue(v))
if err != nil {
return nil, fmt.Errorf("element %v: %w", i, err)
}
b, ok := res.(bool)
if !ok {
return nil, fmt.Errorf("element %v: %w", i, NewTypeError(res, ValueBool))
}
if !b {
return false, nil
}
}
return true, nil
}, nil
},
)
var _ = registerSimpleMethod(
NewMethodSpec(
"any",
"Checks the elements of an array against a query and returns true if any element passes. An error occurs if the target is not an array, or if an element results in the provided query returning a non-boolean result. Returns false if the target array is empty.",
).InCategory(
MethodCategoryObjectAndArray,
"",
NewExampleSpec("",
`root.any_over_21 = this.patrons.any(patron -> patron.age >= 21)`,
`{"patrons":[{"id":"1","age":18},{"id":"2","age":23}]}`,
`{"any_over_21":true}`,
`{"patrons":[{"id":"1","age":10},{"id":"2","age":12}]}`,
`{"any_over_21":false}`,
),
).Param(ParamQuery("test", "A test query to apply to each element.", false)),
func(args *ParsedParams) (simpleMethod, error) {
queryFn, err := args.FieldQuery("test")
if err != nil {
return nil, err
}
return func(res any, ctx FunctionContext) (any, error) {
arr, ok := res.([]any)
if !ok {
return nil, NewTypeError(res, ValueArray)
}
if len(arr) == 0 {
return false, nil
}
for i, v := range arr {
res, err := queryFn.Exec(ctx.WithValue(v))
if err != nil {
return nil, fmt.Errorf("element %v: %w", i, err)
}
b, ok := res.(bool)
if !ok {
return nil, fmt.Errorf("element %v: %w", i, NewTypeError(res, ValueBool))
}
if b {
return true, nil
}
}
return false, nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"append",
"Returns an array with new elements appended to the end.",
).InCategory(
MethodCategoryObjectAndArray,
"",
NewExampleSpec("",
`root.foo = this.foo.append("and", "this")`,
`{"foo":["bar","baz"]}`,
`{"foo":["bar","baz","and","this"]}`,
),
).VariadicParams(),
func(args *ParsedParams) (simpleMethod, error) {
argsList := args.Raw()
return func(res any, ctx FunctionContext) (any, error) {
arr, ok := res.([]any)
if !ok {
return nil, NewTypeError(res, ValueArray)
}
copied := make([]any, 0, len(arr)+len(argsList))
copied = append(copied, arr...)
return append(copied, argsList...), nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"collapse", "",
).InCategory(
MethodCategoryObjectAndArray,
"Collapse an array or object into an object of key/value pairs for each field, where the key is the full path of the structured field in dot path notation. Empty arrays an objects are ignored by default.",
NewExampleSpec("",
`root.result = this.collapse()`,
`{"foo":[{"bar":"1"},{"bar":{}},{"bar":"2"},{"bar":[]}]}`,
`{"result":{"foo.0.bar":"1","foo.2.bar":"2"}}`,
),
NewExampleSpec(
"An optional boolean parameter can be set to true in order to include empty objects and arrays.",
`root.result = this.collapse(include_empty: true)`,
`{"foo":[{"bar":"1"},{"bar":{}},{"bar":"2"},{"bar":[]}]}`,
`{"result":{"foo.0.bar":"1","foo.1.bar":{},"foo.2.bar":"2","foo.3.bar":[]}}`,
),
).Param(ParamBool("include_empty", "Whether to include empty objects and arrays in the resulting object.").Default(false)),
func(args *ParsedParams) (simpleMethod, error) {
includeEmpty, err := args.FieldBool("include_empty")
if err != nil {
return nil, err
}
return func(v any, ctx FunctionContext) (any, error) {
gObj := gabs.Wrap(v)
if includeEmpty {
return gObj.FlattenIncludeEmpty()
}
return gObj.Flatten()
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"contains", "",
).InCategory(
MethodCategoryObjectAndArray,
"Checks whether an array contains an element matching the argument, or an object contains a value matching the argument, and returns a boolean result. Numerical comparisons are made irrespective of the representation type (float versus integer).",
NewExampleSpec("",
`root.has_foo = this.thing.contains("foo")`,
`{"thing":["this","foo","that"]}`,
`{"has_foo":true}`,
`{"thing":["this","bar","that"]}`,
`{"has_foo":false}`,
),
NewExampleSpec("",
`root.has_bar = this.thing.contains(20)`,
`{"thing":[10.3,20.0,"huh",3]}`,
`{"has_bar":true}`,
`{"thing":[2,3,40,67]}`,
`{"has_bar":false}`,
),
).InCategory(
MethodCategoryStrings,
"Checks whether a string contains a substring and returns a boolean result.",
NewExampleSpec("",
`root.has_foo = this.thing.contains("foo")`,
`{"thing":"this foo that"}`,
`{"has_foo":true}`,
`{"thing":"this bar that"}`,
`{"has_foo":false}`,
),
).Param(ParamAny("value", "A value to test against elements of the target.")),
func(args *ParsedParams) (simpleMethod, error) {
compareRight, err := args.Field("value")
if err != nil {
return nil, err
}
sub := IToString(compareRight)
bsub := IToBytes(compareRight)
return func(v any, ctx FunctionContext) (any, error) {
switch t := v.(type) {
case string:
return strings.Contains(t, sub), nil
case []byte:
return bytes.Contains(t, bsub), nil
case []any:
for _, compareLeft := range t {
if ICompare(compareRight, compareLeft) {
return true, nil
}
}
case map[string]any:
for _, compareLeft := range t {
if ICompare(compareRight, compareLeft) {
return true, nil
}
}
default:
return nil, NewTypeError(v, ValueString, ValueArray, ValueObject)
}
return false, nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"enumerated",
"Converts an array into a new array of objects, where each object has a field index containing the `index` of the element and a field `value` containing the original value of the element.",
).InCategory(
MethodCategoryObjectAndArray, "",
NewExampleSpec("",
`root.foo = this.foo.enumerated()`,
`{"foo":["bar","baz"]}`,
`{"foo":[{"index":0,"value":"bar"},{"index":1,"value":"baz"}]}`,
),
),
func(*ParsedParams) (simpleMethod, error) {
return func(v any, ctx FunctionContext) (any, error) {
arr, ok := v.([]any)
if !ok {
return nil, NewTypeError(v, ValueArray)
}
enumerated := make([]any, 0, len(arr))
for i, ele := range arr {
enumerated = append(enumerated, map[string]any{
"index": int64(i),
"value": ele,
})
}
return enumerated, nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"exists",
"Checks that a field, identified via a [dot path][field_paths], exists in an object.",
NewExampleSpec("",
`root.result = this.foo.exists("bar.baz")`,
`{"foo":{"bar":{"baz":"yep, I exist"}}}`,
`{"result":true}`,
`{"foo":{"bar":{}}}`,
`{"result":false}`,
`{"foo":{}}`,
`{"result":false}`,
),
).Param(ParamString("path", "A [dot path][field_paths] to a field.")),
func(args *ParsedParams) (simpleMethod, error) {
pathStr, err := args.FieldString("path")
if err != nil {
return nil, err
}
path := gabs.DotPathToSlice(pathStr)
return func(v any, ctx FunctionContext) (any, error) {
return gabs.Wrap(v).Exists(path...), nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"explode", "",
).InCategory(
MethodCategoryObjectAndArray,
"Explodes an array or object at a [field path][field_paths].",
NewExampleSpec(`##### On arrays
Exploding arrays results in an array containing elements matching the original document, where the target field of each element is an element of the exploded array:`,
`root = this.explode("value")`,
`{"id":1,"value":["foo","bar","baz"]}`,
`[{"id":1,"value":"foo"},{"id":1,"value":"bar"},{"id":1,"value":"baz"}]`,
),
NewExampleSpec(`##### On objects
Exploding objects results in an object where the keys match the target object, and the values match the original document but with the target field replaced by the exploded value:`,
`root = this.explode("value")`,
`{"id":1,"value":{"foo":2,"bar":[3,4],"baz":{"bev":5}}}`,
`{"bar":{"id":1,"value":[3,4]},"baz":{"id":1,"value":{"bev":5}},"foo":{"id":1,"value":2}}`,
),
).Param(ParamString("path", "A [dot path][field_paths] to a field to explode.")),
func(args *ParsedParams) (simpleMethod, error) {
pathRaw, err := args.FieldString("path")
if err != nil {
return nil, err
}
path := gabs.DotPathToSlice(pathRaw)
return func(v any, ctx FunctionContext) (any, error) {
rootMap, ok := v.(map[string]any)
if !ok {
return nil, NewTypeError(v, ValueObject)
}
target := gabs.Wrap(v).Search(path...)
copyFrom := mapWithout(rootMap, [][]string{path})
switch t := target.Data().(type) {
case []any:
result := make([]any, len(t))
for i, ele := range t {
gExploded := gabs.Wrap(IClone(copyFrom))
_, _ = gExploded.Set(ele, path...)
result[i] = gExploded.Data()
}
return result, nil
case map[string]any:
result := make(map[string]any, len(t))
for key, ele := range t {
gExploded := gabs.Wrap(IClone(copyFrom))
_, _ = gExploded.Set(ele, path...)
result[key] = gExploded.Data()
}
return result, nil
}
return nil, fmt.Errorf("expected array or object value at path '%v', found: %v", pathRaw, ITypeOf(target.Data()))
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"filter", "",
).InCategory(
MethodCategoryObjectAndArray,
"Executes a mapping query argument for each element of an array or key/value pair of an object. If the query returns `false` the item is removed from the resulting array or object. The item will also be removed if the query returns any non-boolean value.",
NewExampleSpec(``,
`root.new_nums = this.nums.filter(num -> num > 10)`,
`{"nums":[3,11,4,17]}`,
`{"new_nums":[11,17]}`,
),
NewExampleSpec(`##### On objects
When filtering objects the mapping query argument is provided a context with a field `+"`key`"+` containing the value key, and a field `+"`value`"+` containing the value.`,
`root.new_dict = this.dict.filter(item -> item.value.contains("foo"))`,
`{"dict":{"first":"hello foo","second":"world","third":"this foo is great"}}`,
`{"new_dict":{"first":"hello foo","third":"this foo is great"}}`,
),
).Param(ParamQuery("test", "A query to apply to each element, if this query resolves to any value other than a boolean `true` the element will be removed from the result.", false)),
func(args *ParsedParams) (simpleMethod, error) {
mapFn, err := args.FieldQuery("test")
if err != nil {
return nil, err
}
return func(res any, ctx FunctionContext) (any, error) {
var resValue any
switch t := res.(type) {
case []any:
newSlice := make([]any, 0, len(t))
for _, v := range t {
f, err := mapFn.Exec(ctx.WithValue(v))
if err != nil {
return nil, err
}
if b, _ := f.(bool); b {
newSlice = append(newSlice, v)
}
}
resValue = newSlice
case map[string]any:
newMap := make(map[string]any, len(t))
for k, v := range t {
var ctxMap any = map[string]any{
"key": k,
"value": v,
}
f, err := mapFn.Exec(ctx.WithValue(ctxMap))
if err != nil {
return nil, err
}
if b, _ := f.(bool); b {
newMap[k] = v
}
}
resValue = newMap
default:
return nil, NewTypeError(res, ValueArray, ValueObject)
}
return resValue, nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"find",
"Returns the index of the first occurrence of a value or query in an array. `-1` is returned if there are no matches. Numerical comparisons are made irrespective of the representation type (float versus integer).",
).InCategory(
MethodCategoryObjectAndArray, "",
NewExampleSpec("",
`root.index = this.find("bar")`,
`["foo", "bar", "baz"]`,
`{"index":1}`,
),
NewExampleSpec("",
`root.index = this.find(v -> v != "bar")`,
`["foo", "bar", "baz"]`,
`{"index":0}`,
),
NewExampleSpec("",
`root.index = this.find(v -> v != "foo")`,
`["foo"]`,
`{"index":-1}`,
),
).Beta().Param(ParamQuery("value", "A value to find. If a query is provided it will only be resolved once during the lifetime of the mapping.", false)),
func(args *ParsedParams) (simpleMethod, error) {
val, err := args.Field("value")
if err != nil {
return nil, err
}
return func(v any, ctx FunctionContext) (any, error) {
array, ok := v.([]any)
if !ok {
return nil, NewTypeError(v, ValueArray)
}
for i, elem := range array {
if found, err := findMethodICompare(ctx, val, elem); err != nil {
return nil, err
} else if found {
return i, nil
}
}
return -1, nil
}, nil
},
)
func findMethodICompare(ctx FunctionContext, compareLeft, compareRight any) (bool, error) {
switch compareLeftTyped := compareLeft.(type) {
case *Literal:
return ICompare(compareLeftTyped.Value, compareRight), nil
case Function:
if value, err := compareLeftTyped.Exec(ctx.WithValue(compareRight)); err != nil {
return false, fmt.Errorf("failed to execute query: %w", err)
} else if v, ok := value.(bool); ok {
return v, nil
}
return false, errors.New("query did not return a boolean value")
}
return false, fmt.Errorf("wrong argument type, expected literal or query, got %v", ITypeOf(compareLeft))
}
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"find_all",
"Returns an array containing the indexes of all occurrences of a value or query in an array. An empty array is returned if there are no matches. Numerical comparisons are made irrespective of the representation type (float versus integer).",
).InCategory(
MethodCategoryObjectAndArray, "",
NewExampleSpec("",
`root.index = this.find_all("bar")`,
`["foo", "bar", "baz", "bar"]`,
`{"index":[1,3]}`,
),
NewExampleSpec("",
`root.index = this.find_all(v -> v != "bar")`,
`["foo", "bar", "baz"]`,
`{"index":[0,2]}`,
),
NewExampleSpec("",
`root.index = this.find_all(v -> v != "foo")`,
`["foo"]`,
`{"index":[]}`,
),
).Beta().Param(ParamQuery("value", "A value to find. If a query is provided it will only be resolved once during the lifetime of the mapping.", false)),
func(args *ParsedParams) (simpleMethod, error) {
val, err := args.Field("value")
if err != nil {
return nil, err
}
return func(v any, ctx FunctionContext) (any, error) {
array, ok := v.([]any)
if !ok {
return nil, NewTypeError(v, ValueArray)
}
output := []int{}
for i, elem := range array {
if found, err := findMethodICompare(ctx, val, elem); err != nil {
return nil, err
} else if found {
output = append(output, i)
}
}
return output, nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"flatten",
"Iterates an array and any element that is itself an array is removed and has its elements inserted directly in the resulting array.",
).InCategory(
MethodCategoryObjectAndArray, "",
NewExampleSpec(``,
`root.result = this.flatten()`,
`["foo",["bar","baz"],"buz"]`,
`{"result":["foo","bar","baz","buz"]}`,
),
),
func(*ParsedParams) (simpleMethod, error) {
return func(v any, ctx FunctionContext) (any, error) {
array, isArray := v.([]any)
if !isArray {
return nil, NewTypeError(v, ValueArray)
}
result := make([]any, 0, len(array))
for _, child := range array {
switch t := child.(type) {
case []any:
result = append(result, t...)
default:
result = append(result, t)
}
}
return result, nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"fold",
"Takes two arguments: an initial value, and a mapping query. For each element of an array the mapping context is an object with two fields `tally` and `value`, where `tally` contains the current accumulated value and `value` is the value of the current element. The mapping must return the result of adding the value to the tally.\n\nThe first argument is the value that `tally` will have on the first call.",
).InCategory(
MethodCategoryObjectAndArray, "",
NewExampleSpec(``,
`root.sum = this.foo.fold(0, item -> item.tally + item.value)`,
`{"foo":[3,8,11]}`,
`{"sum":22}`,
),
NewExampleSpec(``,
`root.result = this.foo.fold("", item -> "%v%v".format(item.tally, item.value))`,
`{"foo":["hello ", "world"]}`,
`{"result":"hello world"}`,
),
NewExampleSpec(`You can use fold to merge an array of objects together:`,
`root.smoothie = this.fruits.fold({}, item -> item.tally.merge(item.value))`,
`{"fruits":[{"apple":5},{"banana":3},{"orange":8}]}`,
`{"smoothie":{"apple":5,"banana":3,"orange":8}}`,
),
).
Param(ParamAny("initial", "The initial value to start the fold with. For example, an empty object `{}`, a zero count `0`, or an empty string `\"\"`.")).
Param(ParamQuery("query", "A query to apply for each element. The query is provided an object with two fields; `tally` containing the current tally, and `value` containing the value of the current element. The query should result in a new tally to be passed to the next element query.", false)),
func(args *ParsedParams) (simpleMethod, error) {
foldTallyStart, err := args.Field("initial")
if err != nil {
return nil, err
}
foldFn, err := args.FieldQuery("query")
if err != nil {
return nil, err
}
return func(res any, ctx FunctionContext) (any, error) {
resArray, ok := res.([]any)
if !ok {
return nil, NewTypeError(res, ValueArray)
}
tally := IClone(foldTallyStart)
for _, v := range resArray {
newV, mapErr := foldFn.Exec(ctx.WithValue(map[string]any{
"tally": tally,
"value": v,
}))
if mapErr != nil {
return nil, mapErr
}
tally = newV
}
return tally, nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"index",
"Extract an element from an array by an index. The index can be negative, and if so the element will be selected from the end counting backwards starting from -1. E.g. an index of -1 returns the last element, an index of -2 returns the element before the last, and so on.",
).InCategory(
MethodCategoryObjectAndArray, "",
NewExampleSpec("",
`root.last_name = this.names.index(-1)`,
`{"names":["rachel","stevens"]}`,
`{"last_name":"stevens"}`,
),
NewExampleSpec("It is also possible to use this method on byte arrays, in which case the selected element will be returned as an integer.",
`root.last_byte = this.name.bytes().index(-1)`,
`{"name":"foobar bazson"}`,
`{"last_byte":110}`,
),
).Param(ParamInt64("index", "The index to obtain from an array.")),
func(args *ParsedParams) (simpleMethod, error) {
index, err := args.FieldInt64("index")
if err != nil {
return nil, err
}
return func(v any, ctx FunctionContext) (any, error) {
switch array := v.(type) {
case []any:
i := int(index)
if i < 0 {
i = len(array) + i
}
if i < 0 || i >= len(array) {
return nil, fmt.Errorf("index '%v' was out of bounds for array size: %v", i, len(array))
}
return array[i], nil
case []byte:
i := int(index)
if i < 0 {
i = len(array) + i
}
if i < 0 || i >= len(array) {
return nil, fmt.Errorf("index '%v' was out of bounds for array size: %v", i, len(array))
}
return int64(array[i]), nil
default:
return nil, NewTypeError(v, ValueArray)
}
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"json_schema",
"Checks a [JSON schema](https://json-schema.org/) against a value and returns the value if it matches or throws and error if it does not.",
).InCategory(
MethodCategoryObjectAndArray,
"",
NewExampleSpec("",
`root = this.json_schema("""{
"type":"object",
"properties":{
"foo":{
"type":"string"
}
}
}""")`,
`{"foo":"bar"}`,
`{"foo":"bar"}`,
`{"foo":5}`,
`Error("failed assignment (line 1): field `+"`this`"+`: foo invalid type. expected: string, given: integer")`,
),
NewExampleSpec(
"In order to load a schema from a file use the `file` function.",
`root = this.json_schema(file(var("BENTHOS_TEST_BLOBLANG_SCHEMA_FILE")))`,
),
).Beta().Param(ParamString("schema", "The schema to check values against.")),
func(args *ParsedParams) (simpleMethod, error) {
schemaStr, err := args.FieldString("schema")
if err != nil {
return nil, err
}
schema, err := jsonschema.NewSchema(jsonschema.NewStringLoader(schemaStr))
if err != nil {
return nil, fmt.Errorf("failed to parse json schema definition: %w", err)
}
return func(res any, ctx FunctionContext) (any, error) {
result, err := schema.Validate(jsonschema.NewGoLoader(res))
if err != nil {
return nil, err
}
if !result.Valid() {
var errStr string
for i, desc := range result.Errors() {
if i > 0 {
errStr += "\n"
}
description := strings.ToLower(desc.Description())
if property := desc.Details()["property"]; property != nil {
description = property.(string) + strings.TrimPrefix(description, strings.ToLower(property.(string)))
}
errStr = errStr + desc.Field() + " " + description
}
return nil, errors.New(errStr)
}
return res, nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"keys",
"Returns the keys of an object as an array.",
).InCategory(
MethodCategoryObjectAndArray, "",
NewExampleSpec("",
`root.foo_keys = this.foo.keys()`,
`{"foo":{"bar":1,"baz":2}}`,
`{"foo_keys":["bar","baz"]}`,
),
),
func(*ParsedParams) (simpleMethod, error) {
return func(v any, ctx FunctionContext) (any, error) {
if m, ok := v.(map[string]any); ok {
keys := make([]any, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool {
return keys[i].(string) < keys[j].(string)
})
return keys, nil
}
return nil, NewTypeError(v, ValueObject)
}, nil
},
)
var _ = registerSimpleMethod(
NewMethodSpec(
"key_values",
"Returns the key/value pairs of an object as an array, where each element is an object with a `key` field and a `value` field. The order of the resulting array will be random.",
).InCategory(
MethodCategoryObjectAndArray, "",
NewExampleSpec("",
`root.foo_key_values = this.foo.key_values().sort_by(pair -> pair.key)`,
`{"foo":{"bar":1,"baz":2}}`,
`{"foo_key_values":[{"key":"bar","value":1},{"key":"baz","value":2}]}`,
),
),
func(*ParsedParams) (simpleMethod, error) {
return func(v any, ctx FunctionContext) (any, error) {
if m, ok := v.(map[string]any); ok {
keyValues := make([]any, 0, len(m))
for k, v := range m {
keyValues = append(keyValues, map[string]any{
"key": k,
"value": v,
})
}
return keyValues, nil
}
return nil, NewTypeError(v, ValueObject)
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"length", "",
).InCategory(
MethodCategoryStrings, "Returns the length of a string.",
NewExampleSpec("",
`root.foo_len = this.foo.length()`,
`{"foo":"hello world"}`,
`{"foo_len":11}`,
),
).InCategory(
MethodCategoryObjectAndArray, "Returns the length of an array or object (number of keys).",
NewExampleSpec("",
`root.foo_len = this.foo.length()`,
`{"foo":["first","second"]}`,
`{"foo_len":2}`,
`{"foo":{"first":"bar","second":"baz"}}`,
`{"foo_len":2}`,
),
),
func(*ParsedParams) (simpleMethod, error) {
return func(v any, ctx FunctionContext) (any, error) {
var length int64
switch t := v.(type) {
case string:
length = int64(len(t))
case []byte:
length = int64(len(t))
case []any:
length = int64(len(t))
case map[string]any:
length = int64(len(t))
default:
return nil, NewTypeError(v, ValueString, ValueArray, ValueObject)
}
return length, nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"map_each", "",
).InCategory(
MethodCategoryObjectAndArray, "",
NewExampleSpec(`##### On arrays
Apply a mapping to each element of an array and replace the element with the result. Within the argument mapping the context is the value of the element being mapped.`,
`root.new_nums = this.nums.map_each(num -> if num < 10 {
deleted()
} else {
num - 10
})`,
`{"nums":[3,11,4,17]}`,
`{"new_nums":[1,7]}`,
),
NewExampleSpec(`##### On objects
Apply a mapping to each value of an object and replace the value with the result. Within the argument mapping the context is an object with a field `+"`key`"+` containing the value key, and a field `+"`value`"+`.`,
`root.new_dict = this.dict.map_each(item -> item.value.uppercase())`,
`{"dict":{"foo":"hello","bar":"world"}}`,
`{"new_dict":{"bar":"WORLD","foo":"HELLO"}}`,
),
).Param(ParamQuery("query", "A query that will be used to map each element.", false)),
func(args *ParsedParams) (simpleMethod, error) {
mapFn, err := args.FieldQuery("query")
if err != nil {
return nil, err
}
return func(res any, ctx FunctionContext) (any, error) {
var resValue any
var err error
switch t := res.(type) {
case []any:
newSlice := make([]any, 0, len(t))
for i, v := range t {
newV, mapErr := mapFn.Exec(ctx.WithValue(v))
if mapErr != nil {
return nil, fmt.Errorf("failed to process element %v: %w", i, ErrFrom(mapErr, mapFn))
}
switch newV.(type) {
case Delete:
case Nothing:
newSlice = append(newSlice, v)
default:
newSlice = append(newSlice, newV)
}
}
resValue = newSlice
case map[string]any:
newMap := make(map[string]any, len(t))
for k, v := range t {
var ctxMap any = map[string]any{
"key": k,
"value": v,
}
newV, mapErr := mapFn.Exec(ctx.WithValue(ctxMap))
if mapErr != nil {
return nil, fmt.Errorf("failed to process element %v: %w", k, ErrFrom(mapErr, mapFn))
}
switch newV.(type) {
case Delete:
case Nothing:
newMap[k] = v
default:
newMap[k] = newV
}
}
resValue = newMap
default:
return nil, NewTypeError(res, ValueArray)
}
if err != nil {
return nil, err
}
return resValue, nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"map_each_key", "",
).InCategory(
MethodCategoryObjectAndArray, `Apply a mapping to each key of an object, and replace the key with the result, which must be a string.`,
NewExampleSpec(``,
`root.new_dict = this.dict.map_each_key(key -> key.uppercase())`,
`{"dict":{"keya":"hello","keyb":"world"}}`,
`{"new_dict":{"KEYA":"hello","KEYB":"world"}}`,
),
NewExampleSpec(``,
`root = this.map_each_key(key -> if key.contains("kafka") { "_" + key })`,
`{"amqp_key":"foo","kafka_key":"bar","kafka_topic":"baz"}`,
`{"_kafka_key":"bar","_kafka_topic":"baz","amqp_key":"foo"}`,
),
).Param(ParamQuery("query", "A query that will be used to map each key.", false)),
func(args *ParsedParams) (simpleMethod, error) {
mapFn, err := args.FieldQuery("query")
if err != nil {
return nil, err
}
return func(res any, ctx FunctionContext) (any, error) {
obj, ok := res.(map[string]any)
if !ok {
return nil, NewTypeError(res, ValueObject)
}
newMap := make(map[string]any, len(obj))
for k, v := range obj {
var ctxVal any = k
newKey, mapErr := mapFn.Exec(ctx.WithValue(ctxVal))
if mapErr != nil {
return nil, mapErr
}
switch t := newKey.(type) {
// TODO: Revise whether we want this.
// case Delete:
case Nothing:
newMap[k] = v
case string:
newMap[t] = v
default:
return nil, fmt.Errorf("unexpected result from key mapping: %w", NewTypeError(newKey, ValueString))
}
}
return newMap, nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerMethod(
NewMethodSpec(
"merge", "Merge a source object into an existing destination object. When a collision is found within the merged structures (both a source and destination object contain the same non-object keys) the result will be an array containing both values, where values that are already arrays will be expanded into the resulting array. In order to simply override destination fields on collision use the [`assign`](#assign) method.",
).InCategory(
MethodCategoryObjectAndArray, "",
NewExampleSpec(``,
`root = this.foo.merge(this.bar)`,
`{"foo":{"first_name":"fooer","likes":"bars"},"bar":{"second_name":"barer","likes":"foos"}}`,
`{"first_name":"fooer","likes":["bars","foos"],"second_name":"barer"}`,
),
).Param(ParamAny("with", "A value to merge the target value with.")),
mergeMethod,
)
func mergeMethod(target Function, args *ParsedParams) (Function, error) {
mergeFromSource, err := args.Field("with")