This repository has been archived by the owner on Sep 3, 2020. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 56
/
invoke.go
107 lines (82 loc) · 1.82 KB
/
invoke.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
// Package invoke calls a Lambda function.
package invoke
import (
"encoding/json"
"errors"
"fmt"
"io"
"os"
"strings"
"github.com/mattn/go-isatty"
"github.com/spf13/cobra"
"github.com/apex/apex/cmd/apex/root"
)
// includeLogs in output.
var includeLogs bool
// name of function.
var name string
// example output.
const example = ` Invoke a function with input json
$ apex invoke foo < request.json`
// Command config.
var Command = &cobra.Command{
Use: "invoke <name>",
Short: "Invoke functions",
Example: example,
PreRunE: preRun,
RunE: run,
}
// Initialize.
func init() {
root.Register(Command)
f := Command.Flags()
f.BoolVarP(&includeLogs, "logs", "L", false, "Print logs")
}
// PreRun errors if the name argument is missing.
func preRun(c *cobra.Command, args []string) error {
if len(args) < 1 {
return errors.New("Missing name argument")
}
name = args[0]
return nil
}
// Run command.
func run(c *cobra.Command, args []string) error {
dec := json.NewDecoder(input())
if err := root.Project.LoadFunctions(name); err != nil {
return err
}
fn := root.Project.Functions[0]
for {
var v map[string]interface{}
err := dec.Decode(&v)
if err == io.EOF {
break
}
if err != nil {
return fmt.Errorf("parsing response: %s", err)
}
var reply, logs io.Reader
if e, ok := v["event"].(map[string]interface{}); ok {
reply, logs, err = fn.Invoke(e, v["context"])
} else {
reply, logs, err = fn.Invoke(v, nil)
}
if includeLogs {
io.Copy(os.Stderr, logs)
}
if err != nil {
return fmt.Errorf("function response: %s", err)
}
io.Copy(os.Stdout, reply)
fmt.Fprintf(os.Stdout, "\n")
}
return nil
}
// input from stdin or empty object by default.
func input() io.Reader {
if isatty.IsTerminal(os.Stdin.Fd()) {
return strings.NewReader("{}")
}
return os.Stdin
}