1// Copyright 2012-present Oliver Eilhard. All rights reserved.
2// Use of this source code is governed by a MIT-license.
3// See http://olivere.mit-license.org/license.txt for details.
4
5package elastic
6
7import (
8	"context"
9	"fmt"
10	"net/url"
11)
12
13// ClearScrollService clears one or more scroll contexts by their ids.
14//
15// See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-request-scroll.html#_clear_scroll_api
16// for details.
17type ClearScrollService struct {
18	client   *Client
19	pretty   bool
20	scrollId []string
21}
22
23// NewClearScrollService creates a new ClearScrollService.
24func NewClearScrollService(client *Client) *ClearScrollService {
25	return &ClearScrollService{
26		client:   client,
27		scrollId: make([]string, 0),
28	}
29}
30
31// ScrollId is a list of scroll IDs to clear.
32// Use _all to clear all search contexts.
33func (s *ClearScrollService) ScrollId(scrollIds ...string) *ClearScrollService {
34	s.scrollId = append(s.scrollId, scrollIds...)
35	return s
36}
37
38// Pretty indicates that the JSON response be indented and human readable.
39func (s *ClearScrollService) Pretty(pretty bool) *ClearScrollService {
40	s.pretty = pretty
41	return s
42}
43
44// buildURL builds the URL for the operation.
45func (s *ClearScrollService) buildURL() (string, url.Values, error) {
46	// Build URL
47	path := "/_search/scroll/"
48
49	// Add query string parameters
50	params := url.Values{}
51	if s.pretty {
52		params.Set("pretty", "1")
53	}
54	return path, params, nil
55}
56
57// Validate checks if the operation is valid.
58func (s *ClearScrollService) Validate() error {
59	var invalid []string
60	if len(s.scrollId) == 0 {
61		invalid = append(invalid, "ScrollId")
62	}
63	if len(invalid) > 0 {
64		return fmt.Errorf("missing required fields: %v", invalid)
65	}
66	return nil
67}
68
69// Do executes the operation.
70func (s *ClearScrollService) Do(ctx context.Context) (*ClearScrollResponse, error) {
71	// Check pre-conditions
72	if err := s.Validate(); err != nil {
73		return nil, err
74	}
75
76	// Get URL for request
77	path, params, err := s.buildURL()
78	if err != nil {
79		return nil, err
80	}
81
82	// Setup HTTP request body
83	body := map[string][]string{
84		"scroll_id": s.scrollId,
85	}
86
87	// Get HTTP response
88	res, err := s.client.PerformRequest(ctx, "DELETE", path, params, body)
89	if err != nil {
90		return nil, err
91	}
92
93	// Return operation response
94	ret := new(ClearScrollResponse)
95	if err := s.client.decoder.Decode(res.Body, ret); err != nil {
96		return nil, err
97	}
98	return ret, nil
99}
100
101// ClearScrollResponse is the response of ClearScrollService.Do.
102type ClearScrollResponse struct {
103}
104