/
functions.go
781 lines (708 loc) · 23.4 KB
/
functions.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
package query
import (
"context"
"errors"
"fmt"
"math/rand"
"sync"
"time"
"github.com/Jeffail/gabs/v2"
"github.com/gofrs/uuid"
gonanoid "github.com/matoous/go-nanoid/v2"
"github.com/segmentio/ksuid"
)
type fieldFunction struct {
namedContext string
fromRoot bool
path []string
}
func (f *fieldFunction) expand(path ...string) *fieldFunction {
newFn := *f
newPath := make([]string, 0, len(f.path)+len(path))
newPath = append(newPath, f.path...)
newPath = append(newPath, path...)
newFn.path = newPath
return &newFn
}
func (f *fieldFunction) Annotation() string {
path := f.namedContext
if f.fromRoot {
path = "root"
} else if path == "" {
path = "this"
}
if len(f.path) > 0 {
path = path + "." + SliceToDotPath(f.path...)
}
return "field `" + path + "`"
}
func (f *fieldFunction) Exec(ctx FunctionContext) (interface{}, error) {
var target interface{}
if f.fromRoot {
if ctx.NewValue == nil {
return nil, errors.New("unable to reference `root` from this context")
}
target = *ctx.NewValue
} else if f.namedContext == "" {
v := ctx.Value()
if v == nil {
var fieldName string
if len(f.path) > 0 {
fieldName = SliceToDotPath(f.path...)
}
return nil, &ErrRecoverable{
Recovered: nil,
Err: ErrNoContext{
FieldName: fieldName,
},
}
}
target = *v
} else {
var ok bool
if target, ok = ctx.NamedValue(f.namedContext); !ok {
return ctx, fmt.Errorf("named context %v was not found", f.namedContext)
}
}
if len(f.path) == 0 {
return target, nil
}
return gabs.Wrap(target).S(f.path...).Data(), nil
}
func (f *fieldFunction) QueryTargets(ctx TargetsContext) (TargetsContext, []TargetPath) {
var basePaths []TargetPath
if f.fromRoot {
basePaths = []TargetPath{NewTargetPath(TargetRoot)}
} else if f.namedContext == "" {
if basePaths = ctx.MainContext(); len(basePaths) == 0 {
basePaths = []TargetPath{NewTargetPath(TargetValue)}
}
} else {
basePaths = ctx.NamedContext(f.namedContext)
}
paths := make([]TargetPath, len(basePaths))
for i, p := range basePaths {
paths[i] = p
paths[i].Path = append(paths[i].Path, f.path...)
}
ctx = ctx.WithValues(paths)
return ctx, paths
}
func (f *fieldFunction) Close(ctx context.Context) error {
return nil
}
// NewNamedContextFieldFunction creates a query function that attempts to
// return a field from a named context.
func NewNamedContextFieldFunction(namedContext, pathStr string) Function {
var path []string
if len(pathStr) > 0 {
path = gabs.DotPathToSlice(pathStr)
}
return &fieldFunction{namedContext, false, path}
}
// NewFieldFunction creates a query function that returns a field from the
// current context.
func NewFieldFunction(pathStr string) Function {
var path []string
if len(pathStr) > 0 {
path = gabs.DotPathToSlice(pathStr)
}
return &fieldFunction{
path: path,
}
}
// NewRootFieldFunction creates a query function that returns a field from the
// root context.
func NewRootFieldFunction(pathStr string) Function {
var path []string
if len(pathStr) > 0 {
path = gabs.DotPathToSlice(pathStr)
}
return &fieldFunction{
fromRoot: true,
path: path,
}
}
//------------------------------------------------------------------------------
// Literal wraps a static value and returns it for each invocation of the
// function.
type Literal struct {
annotation string
Value interface{}
}
// Annotation returns a token identifier of the function.
func (l *Literal) Annotation() string {
if l.annotation == "" {
return string(ITypeOf(l.Value)) + " literal"
}
return l.annotation
}
// Exec returns a literal value.
func (l *Literal) Exec(ctx FunctionContext) (interface{}, error) {
return l.Value, nil
}
// QueryTargets returns nothing.
func (l *Literal) QueryTargets(ctx TargetsContext) (TargetsContext, []TargetPath) {
return ctx, nil
}
// Close does nothing.
func (l *Literal) Close(ctx context.Context) error {
return nil
}
// String returns a string representation of the literal function.
func (l *Literal) String() string {
return fmt.Sprintf("%v", l.Value)
}
// NewLiteralFunction creates a query function that returns a static, literal
// value.
func NewLiteralFunction(annotation string, v interface{}) *Literal {
return &Literal{annotation, v}
}
//------------------------------------------------------------------------------
var _ = registerSimpleFunction(
NewFunctionSpec(
FunctionCategoryMessage, "batch_index",
"Returns the index of the mapped message within a batch. This is useful for applying maps only on certain messages of a batch.",
NewExampleSpec("",
`root = if batch_index() > 0 { deleted() }`,
),
),
func(ctx FunctionContext) (interface{}, error) {
return int64(ctx.Index), nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleFunction(
NewFunctionSpec(
FunctionCategoryMessage, "batch_size",
"Returns the size of the message batch.",
NewExampleSpec("",
`root.foo = batch_size()`,
),
),
func(ctx FunctionContext) (interface{}, error) {
return int64(ctx.MsgBatch.Len()), nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleFunction(
NewFunctionSpec(
FunctionCategoryMessage, "content",
"Returns the full raw contents of the mapping target message as a byte array. When mapping to a JSON field the value should be encoded using the method [`encode`][methods.encode], or cast to a string directly using the method [`string`][methods.string], otherwise it will be base64 encoded by default.",
NewExampleSpec("",
`root.doc = content().string()`,
`{"foo":"bar"}`,
`{"doc":"{\"foo\":\"bar\"}"}`,
),
),
func(ctx FunctionContext) (interface{}, error) {
return ctx.MsgBatch.Get(ctx.Index).Get(), nil
},
)
//------------------------------------------------------------------------------
var _ = registerFunction(
NewFunctionSpec(
FunctionCategoryGeneral, "count",
"The `count` function is a counter starting at 1 which increments after each time it is called. Count takes an argument which is an identifier for the counter, allowing you to specify multiple unique counters in your configuration.",
NewExampleSpec("",
`root = this
root.id = count("bloblang_function_example")`,
`{"message":"foo"}`,
`{"id":1,"message":"foo"}`,
`{"message":"bar"}`,
`{"id":2,"message":"bar"}`,
),
).Param(ParamString("name", "An identifier for the counter.")).MarkImpure(),
countFunction,
)
var counters = map[string]int64{}
var countersMux = &sync.Mutex{}
func countFunction(args *ParsedParams) (Function, error) {
name, err := args.FieldString("name")
if err != nil {
return nil, err
}
return ClosureFunction("function count", func(ctx FunctionContext) (interface{}, error) {
countersMux.Lock()
defer countersMux.Unlock()
var count int64
var exists bool
if count, exists = counters[name]; exists {
count++
} else {
count = 1
}
counters[name] = count
return count, nil
}, nil), nil
}
//------------------------------------------------------------------------------
var _ = registerFunction(
NewFunctionSpec(
FunctionCategoryGeneral, "deleted",
"A function that returns a result indicating that the mapping target should be deleted. Deleting, also known as dropping, messages will result in them being acknowledged as successfully processed to inputs in a Benthos pipeline. For more information about error handling patterns read [here][error_handling].",
NewExampleSpec("",
`root = this
root.bar = deleted()`,
`{"bar":"bar_value","baz":"baz_value","foo":"foo value"}`,
`{"baz":"baz_value","foo":"foo value"}`,
),
NewExampleSpec(
"Since the result is a value it can be used to do things like remove elements of an array within `map_each`.",
`root.new_nums = this.nums.map_each(num -> if num < 10 { deleted() } else { num - 10 })`,
`{"nums":[3,11,4,17]}`,
`{"new_nums":[1,7]}`,
),
),
func(*ParsedParams) (Function, error) {
return NewLiteralFunction("delete", Delete(nil)), nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleFunction(
NewFunctionSpec(
FunctionCategoryMessage, "error",
"If an error has occurred during the processing of a message this function returns the reported cause of the error as a string, otherwise `null`. For more information about error handling patterns read [here][error_handling].",
NewExampleSpec("",
`root.doc.error = error()`,
),
),
func(ctx FunctionContext) (interface{}, error) {
v := ctx.MsgBatch.Get(ctx.Index).ErrorGet()
if v != nil {
return v.Error(), nil
}
return nil, nil
},
)
var _ = registerSimpleFunction(
NewFunctionSpec(
FunctionCategoryMessage, "errored",
"Returns a boolean value indicating whether an error has occurred during the processing of a message. For more information about error handling patterns read [here][error_handling].",
NewExampleSpec("",
`root.doc.status = if errored() { 400 } else { 200 }`,
),
),
func(ctx FunctionContext) (interface{}, error) {
return ctx.MsgBatch.Get(ctx.Index).ErrorGet() != nil, nil
},
)
//------------------------------------------------------------------------------
var _ = registerFunction(
NewFunctionSpec(
FunctionCategoryGeneral, "range",
"The `range` function creates an array of integers following a range between a start, stop and optional step integer argument. If the step argument is omitted then it defaults to 1. A negative step can be provided as long as stop < start.",
NewExampleSpec("",
`root.a = range(0, 10)
root.b = range(start: 0, stop: this.max, step: 2) # Using named params
root.c = range(0, -this.max, -2)`,
`{"max":10}`,
`{"a":[0,1,2,3,4,5,6,7,8,9],"b":[0,2,4,6,8],"c":[0,-2,-4,-6,-8]}`,
),
).
Param(ParamInt64("start", "The start value.")).
Param(ParamInt64("stop", "The stop value.")).
Param(ParamInt64("step", "The step value.").Default(1)),
rangeFunction,
)
func rangeFunction(args *ParsedParams) (Function, error) {
start, err := args.FieldInt64("start")
if err != nil {
return nil, err
}
stop, err := args.FieldInt64("stop")
if err != nil {
return nil, err
}
step, err := args.FieldInt64("step")
if err != nil {
return nil, err
}
if step == 0 {
return nil, errors.New("step must be greater than or less than 0")
}
if step < 0 {
if stop > start {
return nil, fmt.Errorf("with negative step arg stop (%v) must be <= start (%v)", stop, start)
}
} else if start >= stop {
return nil, fmt.Errorf("with positive step arg start (%v) must be < stop (%v)", start, stop)
}
r := make([]interface{}, (stop-start)/step)
for i := 0; i < len(r); i++ {
r[i] = start + step*int64(i)
}
return ClosureFunction("function range", func(ctx FunctionContext) (interface{}, error) {
return r, nil
}, nil), nil
}
var _ = registerFunction(
NewFunctionSpec(
FunctionCategoryMessage, "json",
"Returns the value of a field within a JSON message located by a [dot path][field_paths] argument. This function always targets the entire source JSON document regardless of the mapping context.",
NewExampleSpec("",
`root.mapped = json("foo.bar")`,
`{"foo":{"bar":"hello world"}}`,
`{"mapped":"hello world"}`,
),
NewExampleSpec(
"The path argument is optional and if omitted the entire JSON payload is returned.",
`root.doc = json()`,
`{"foo":{"bar":"hello world"}}`,
`{"doc":{"foo":{"bar":"hello world"}}}`,
),
).Param(ParamString("path", "An optional [dot path][field_paths] identifying a field to obtain.").Default("")),
jsonFunction,
)
func jsonFunction(args *ParsedParams) (Function, error) {
path, err := args.FieldString("path")
if err != nil {
return nil, err
}
var argPath []string
if len(path) > 0 {
argPath = gabs.DotPathToSlice(path)
}
return ClosureFunction("json path `"+SliceToDotPath(argPath...)+"`", func(ctx FunctionContext) (interface{}, error) {
jPart, err := ctx.MsgBatch.Get(ctx.Index).JSON()
if err != nil {
return nil, &ErrRecoverable{
Recovered: nil,
Err: err,
}
}
gPart := gabs.Wrap(jPart)
if len(argPath) > 0 {
gPart = gPart.Search(argPath...)
}
return ISanitize(gPart.Data()), nil
}, func(ctx TargetsContext) (TargetsContext, []TargetPath) {
paths := []TargetPath{
NewTargetPath(TargetValue, argPath...),
}
ctx = ctx.WithValues(paths)
return ctx, paths
}), nil
}
//------------------------------------------------------------------------------
var _ = registerFunction(
NewFunctionSpec(
FunctionCategoryMessage, "meta",
"Returns the value of a metadata key from the input message, or `null` if the key does not exist. Since values are extracted from the read-only input message they do NOT reflect changes made from within the map. In order to query metadata mutations made within a mapping use the [`root_meta` function](#root_meta). This function supports extracting metadata from other messages of a batch with the `from` method.",
NewExampleSpec("",
`root.topic = meta("kafka_topic")`,
`root.topic = meta("nope") | meta("also nope") | "default"`,
),
NewExampleSpec(
"The key parameter is optional and if omitted the entire metadata contents are returned as an object.",
`root.all_metadata = meta()`,
),
).Param(ParamString("key", "An optional key of a metadata value to obtain.").Default("")),
func(args *ParsedParams) (Function, error) {
key, err := args.FieldString("key")
if err != nil {
return nil, err
}
if len(key) > 0 {
return ClosureFunction("meta field "+key, func(ctx FunctionContext) (interface{}, error) {
v := ctx.MsgBatch.Get(ctx.Index).MetaGet(key)
if v == "" {
return nil, nil
}
return v, nil
}, func(ctx TargetsContext) (TargetsContext, []TargetPath) {
paths := []TargetPath{
NewTargetPath(TargetMetadata, key),
}
ctx = ctx.WithValues(paths)
return ctx, paths
}), nil
}
return ClosureFunction("meta object", func(ctx FunctionContext) (interface{}, error) {
kvs := map[string]interface{}{}
_ = ctx.MsgBatch.Get(ctx.Index).MetaIter(func(k, v string) error {
if len(v) > 0 {
kvs[k] = v
}
return nil
})
return kvs, nil
}, func(ctx TargetsContext) (TargetsContext, []TargetPath) {
paths := []TargetPath{
NewTargetPath(TargetMetadata),
}
ctx = ctx.WithValues(paths)
return ctx, paths
}), nil
},
)
//------------------------------------------------------------------------------
var _ = registerFunction(
NewFunctionSpec(
FunctionCategoryMessage, "root_meta",
"Returns the value of a metadata key from the new message being created, or `null` if the key does not exist. Changes made to metadata during a mapping will be reflected by this function.",
NewExampleSpec("",
`root.topic = root_meta("kafka_topic")`,
`root.topic = root_meta("nope") | root_meta("also nope") | "default"`,
),
NewExampleSpec(
"The key parameter is optional and if omitted the entire metadata contents are returned as an object.",
`root.all_metadata = root_meta()`,
),
).Beta().Param(ParamString("key", "An optional key of a metadata value to obtain.").Default("")),
func(args *ParsedParams) (Function, error) {
key, err := args.FieldString("key")
if err != nil {
return nil, err
}
if len(key) > 0 {
return ClosureFunction("root_meta field "+key, func(ctx FunctionContext) (interface{}, error) {
if ctx.NewMeta == nil {
return nil, errors.New("root metadata cannot be queried in this context")
}
v := ctx.NewMeta.MetaGet(key)
if v == "" {
return nil, nil
}
return v, nil
}, func(ctx TargetsContext) (TargetsContext, []TargetPath) {
paths := []TargetPath{
NewTargetPath(TargetMetadata, key),
}
ctx = ctx.WithValues(paths)
return ctx, paths
}), nil
}
return ClosureFunction("root_meta object", func(ctx FunctionContext) (interface{}, error) {
if ctx.NewMeta == nil {
return nil, errors.New("root metadata cannot be queried in this context")
}
kvs := map[string]interface{}{}
_ = ctx.NewMeta.MetaIter(func(k, v string) error {
if len(v) > 0 {
kvs[k] = v
}
return nil
})
return kvs, nil
}, func(ctx TargetsContext) (TargetsContext, []TargetPath) {
paths := []TargetPath{
NewTargetPath(TargetMetadata),
}
ctx = ctx.WithValues(paths)
return ctx, paths
}), nil
},
)
//------------------------------------------------------------------------------
var _ = registerFunction(
NewHiddenFunctionSpec("nothing"),
func(*ParsedParams) (Function, error) {
return NewLiteralFunction("nothing", Nothing(nil)), nil
},
)
//------------------------------------------------------------------------------
var _ = registerFunction(
NewFunctionSpec(
FunctionCategoryGeneral, "random_int",
"Generates a non-negative pseudo-random 64-bit integer. An optional integer argument can be provided in order to seed the random number generator.",
NewExampleSpec("",
`root.first = random_int()
root.second = random_int(1)`,
),
NewExampleSpec("It is possible to specify a dynamic seed argument, in which case the argument will only be resolved once during the lifetime of the mapping.",
`root.first = random_int(timestamp_unix_nano())`,
),
).
Param(ParamQuery(
"seed",
"A seed to use, if a query is provided it will only be resolved once during the lifetime of the mapping.",
true,
).Default(NewLiteralFunction("", 0))),
randomIntFunction,
)
func randomIntFunction(args *ParsedParams) (Function, error) {
seedFn, err := args.FieldQuery("seed")
if err != nil {
return nil, err
}
var randMut sync.Mutex
var r *rand.Rand
return ClosureFunction("function random_int", func(ctx FunctionContext) (interface{}, error) {
randMut.Lock()
defer randMut.Unlock()
if r == nil {
seedI, err := seedFn.Exec(ctx)
if err != nil {
return nil, fmt.Errorf("failed to seed random number generator: %v", err)
}
seed, err := IToInt(seedI)
if err != nil {
return nil, fmt.Errorf("failed to seed random number generator: %v", err)
}
r = rand.New(rand.NewSource(seed))
}
v := int64(r.Int())
return v, nil
}, nil), nil
}
//------------------------------------------------------------------------------
var _ = registerFunction(
NewFunctionSpec(
FunctionCategoryEnvironment, "now",
"Returns the current timestamp as a string in RFC 3339 format with the local timezone. Use the method `ts_format` in order to change the format and timezone.",
NewExampleSpec("",
`root.received_at = now()`,
),
NewExampleSpec("",
`root.received_at = now().ts_format("Mon Jan 2 15:04:05 -0700 MST 2006", "UTC")`,
),
),
func(args *ParsedParams) (Function, error) {
return ClosureFunction("function now", func(_ FunctionContext) (interface{}, error) {
return time.Now().Format(time.RFC3339Nano), nil
}, nil), nil
},
)
var _ = registerSimpleFunction(
NewFunctionSpec(
FunctionCategoryEnvironment, "timestamp_unix",
"Returns the current unix timestamp in seconds.",
NewExampleSpec("",
`root.received_at = timestamp_unix()`,
),
),
func(_ FunctionContext) (interface{}, error) {
return time.Now().Unix(), nil
},
)
var _ = registerSimpleFunction(
NewFunctionSpec(
FunctionCategoryEnvironment, "timestamp_unix_nano",
"Returns the current unix timestamp in nanoseconds.",
NewExampleSpec("",
`root.received_at = timestamp_unix_nano()`,
),
),
func(_ FunctionContext) (interface{}, error) {
return time.Now().UnixNano(), nil
},
)
//------------------------------------------------------------------------------
var _ = registerFunction(
NewFunctionSpec(
FunctionCategoryGeneral, "throw",
"Throws an error similar to a regular mapping error. This is useful for abandoning a mapping entirely given certain conditions.",
NewExampleSpec("",
`root.doc.type = match {
this.exists("header.id") => "foo"
this.exists("body.data") => "bar"
_ => throw("unknown type")
}
root.doc.contents = (this.body.content | this.thing.body)`,
`{"header":{"id":"first"},"thing":{"body":"hello world"}}`,
`{"doc":{"contents":"hello world","type":"foo"}}`,
`{"nothing":"matches"}`,
`Error("failed assignment (line 1): unknown type")`,
),
).Param(ParamString("why", "A string explanation for why an error was thrown, this will be added to the resulting error message.")),
func(args *ParsedParams) (Function, error) {
msg, err := args.FieldString("why")
if err != nil {
return nil, err
}
return ClosureFunction("function throw", func(_ FunctionContext) (interface{}, error) {
return nil, errors.New(msg)
}, nil), nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleFunction(
NewFunctionSpec(
FunctionCategoryGeneral, "uuid_v4",
"Generates a new RFC-4122 UUID each time it is invoked and prints a string representation.",
NewExampleSpec("", `root.id = uuid_v4()`),
),
func(_ FunctionContext) (interface{}, error) {
u4, err := uuid.NewV4()
if err != nil {
panic(err)
}
return u4.String(), nil
},
)
//------------------------------------------------------------------------------
var _ = registerFunction(
NewFunctionSpec(
FunctionCategoryGeneral, "nanoid",
"Generates a new nanoid each time it is invoked and prints a string representation.",
NewExampleSpec("", `root.id = nanoid()`),
NewExampleSpec("It is possible to specify an optional length parameter.", `root.id = nanoid(54)`),
NewExampleSpec("It is also possible to specify an optional custom alphabet after the length parameter.", `root.id = nanoid(54, "abcde")`),
).
Param(ParamInt64("length", "An optional length.").Optional()).
Param(ParamString("alphabet", "An optional custom alphabet to use for generating IDs. When specified the field `length` must also be present.").Optional()),
nanoidFunction,
)
func nanoidFunction(args *ParsedParams) (Function, error) {
lenArg, err := args.FieldOptionalInt64("length")
if err != nil {
return nil, err
}
alphabetArg, err := args.FieldOptionalString("alphabet")
if err != nil {
return nil, err
}
if alphabetArg != nil && lenArg == nil {
return nil, errors.New("field length must be specified when an alphabet is specified")
}
return ClosureFunction("function nanoid", func(ctx FunctionContext) (interface{}, error) {
if alphabetArg != nil {
return gonanoid.Generate(*alphabetArg, int(*lenArg))
}
if lenArg != nil {
return gonanoid.New(int(*lenArg))
}
return gonanoid.New()
}, nil), nil
}
//------------------------------------------------------------------------------
var _ = registerSimpleFunction(
NewFunctionSpec(
FunctionCategoryGeneral, "ksuid",
"Generates a new ksuid each time it is invoked and prints a string representation.",
NewExampleSpec("", `root.id = ksuid()`),
),
func(_ FunctionContext) (interface{}, error) {
return ksuid.New().String(), nil
},
)
//------------------------------------------------------------------------------
var _ = registerFunction(
NewHiddenFunctionSpec("var").Param(ParamString("name", "The name of the target variable.")),
func(args *ParsedParams) (Function, error) {
name, err := args.FieldString("name")
if err != nil {
return nil, err
}
return NewVarFunction(name), nil
},
)
// NewVarFunction creates a new variable function.
func NewVarFunction(name string) Function {
return ClosureFunction("variable "+name, func(ctx FunctionContext) (interface{}, error) {
if ctx.Vars == nil {
return nil, errors.New("variables were undefined")
}
if res, ok := ctx.Vars[name]; ok {
return res, nil
}
return nil, fmt.Errorf("variable '%v' undefined", name)
}, func(ctx TargetsContext) (TargetsContext, []TargetPath) {
paths := []TargetPath{
NewTargetPath(TargetVariable, name),
}
ctx = ctx.WithValues(paths)
return ctx, paths
})
}