summaryrefslogtreecommitdiff
path: root/external/evcli/api.go
blob: 40fe38c2c8b79b943ed2604526d34a881c0e2745 (plain)
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
package evcli

import (
	"encoding/json"
	"errors"
	"fmt"

	"github.com/exograd/eventline/pkg/eventline"
	"github.com/exograd/go-daemon/check"
)

type APIError struct {
	Message string          `json:"error"`
	Code    string          `json:"code,omitempty"`
	RawData json.RawMessage `json:"data,omitempty"`
	Data    interface{}     `json:"-"`
}

type InvalidRequestBodyError struct {
	ValidationErrors check.ValidationErrors `json:"validation_errors"`
}

func (err APIError) Error() string {
	return err.Message
}

func (err *APIError) UnmarshalJSON(data []byte) error {
	type APIError2 APIError

	err2 := APIError2(*err)
	if jsonErr := json.Unmarshal(data, &err2); jsonErr != nil {
		return jsonErr
	}

	switch err2.Code {
	case "invalid_request_body":
		var errData InvalidRequestBodyError

		if err2.RawData != nil {
			if err := json.Unmarshal(err2.RawData, &errData); err != nil {
				return fmt.Errorf("invalid jsv errors: %w", err)
			}

			err2.Data = &errData
		}
	}

	*err = APIError(err2)
	return nil
}

func IsInvalidRequestBodyError(err error) (bool, check.ValidationErrors) {
	var apiError *APIError

	if !errors.As(err, &apiError) {
		return false, nil
	}

	requestBodyErr, ok := apiError.Data.(*InvalidRequestBodyError)
	if !ok {
		return false, nil
	}

	return true, requestBodyErr.ValidationErrors
}

type ProjectPage struct {
	Elements eventline.Projects `json:"elements"`
	Previous *eventline.Cursor  `json:"previous,omitempty"`
	Next     *eventline.Cursor  `json:"next,omitempty"`
}

type Parameter struct {
	Name        string      `json:"name"`
	Type        string      `json:"type"`
	Default     interface{} `json:"default"`
	Description string      `json:"description"`
}

type Parameters []*Parameter

type JobPage struct {
	Elements eventline.Jobs    `json:"elements"`
	Previous *eventline.Cursor `json:"previous,omitempty"`
	Next     *eventline.Cursor `json:"next,omitempty"`
}