X Tutup
Skip to content

Commit 9dff05b

Browse files
committed
Add api --cache flag
Cache API responses on disk for a specified duration.
1 parent 04dcb32 commit 9dff05b

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

pkg/cmd/api/api.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,10 @@ import (
1414
"strconv"
1515
"strings"
1616
"syscall"
17+
"time"
1718

1819
"github.com/MakeNowJust/heredoc"
20+
"github.com/cli/cli/api"
1921
"github.com/cli/cli/internal/ghinstance"
2022
"github.com/cli/cli/internal/ghrepo"
2123
"github.com/cli/cli/pkg/cmdutil"
@@ -38,6 +40,7 @@ type ApiOptions struct {
3840
ShowResponseHeaders bool
3941
Paginate bool
4042
Silent bool
43+
CacheTTL time.Duration
4144

4245
HttpClient func() (*http.Client, error)
4346
BaseRepo func() (ghrepo.Interface, error)
@@ -52,6 +55,8 @@ func NewCmdApi(f *cmdutil.Factory, runF func(*ApiOptions) error) *cobra.Command
5255
Branch: f.Branch,
5356
}
5457

58+
var cacheDuration string
59+
5560
cmd := &cobra.Command{
5661
Use: "api <endpoint>",
5762
Short: "Make an authenticated GitHub API request",
@@ -160,6 +165,14 @@ func NewCmdApi(f *cmdutil.Factory, runF func(*ApiOptions) error) *cobra.Command
160165
return &cmdutil.FlagError{Err: errors.New(`the '--paginate' option is not supported with '--input'`)}
161166
}
162167

168+
if cacheDuration != "" {
169+
cacheTTL, err := time.ParseDuration(cacheDuration)
170+
if err != nil {
171+
return fmt.Errorf("error parsing `--cache` value: %w", err)
172+
}
173+
opts.CacheTTL = cacheTTL
174+
}
175+
163176
if runF != nil {
164177
return runF(&opts)
165178
}
@@ -176,6 +189,7 @@ func NewCmdApi(f *cmdutil.Factory, runF func(*ApiOptions) error) *cobra.Command
176189
cmd.Flags().BoolVar(&opts.Paginate, "paginate", false, "Make additional HTTP requests to fetch all pages of results")
177190
cmd.Flags().StringVar(&opts.RequestInputFile, "input", "", "The `file` to use as body for the HTTP request")
178191
cmd.Flags().BoolVar(&opts.Silent, "silent", false, "Do not print the response body")
192+
cmd.Flags().StringVar(&cacheDuration, "cache", "", "Cache the response for the specified duration")
179193
return cmd
180194
}
181195

@@ -219,6 +233,9 @@ func apiRun(opts *ApiOptions) error {
219233
if err != nil {
220234
return err
221235
}
236+
if opts.CacheTTL > 0 {
237+
httpClient = api.NewCachedClient(httpClient, opts.CacheTTL)
238+
}
222239

223240
headersOutputStream := opts.IO.Out
224241
if opts.Silent {

0 commit comments

Comments
 (0)
X Tutup