File: target.go

package info (click to toggle)
deck 1.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 1,100 kB
  • sloc: makefile: 19; sh: 3
file content (72 lines) | stat: -rw-r--r-- 2,034 bytes parent folder | download
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
package solver

import (
	"github.com/kong/deck/crud"
	"github.com/kong/deck/diff"
	"github.com/kong/deck/state"
	"github.com/kong/go-kong/kong"
)

// targetCRUD implements crud.Actions interface.
type targetCRUD struct {
	client *kong.Client
}

func targetFromStuct(arg diff.Event) *state.Target {
	target, ok := arg.Obj.(*state.Target)
	if !ok {
		panic("unexpected type, expected *state.Target")
	}

	return target
}

// Create creates a Target in Kong.
// The arg should be of type diff.Event, containing the target to be created,
// else the function will panic.
// It returns a the created *state.Target.
func (s *targetCRUD) Create(arg ...crud.Arg) (crud.Arg, error) {
	event := eventFromArg(arg[0])
	target := targetFromStuct(event)
	createdTarget, err := s.client.Targets.Create(nil,
		target.Upstream.ID, &target.Target)
	if err != nil {
		return nil, err
	}
	return &state.Target{Target: *createdTarget}, nil
}

// Delete deletes a Target in Kong.
// The arg should be of type diff.Event, containing the target to be deleted,
// else the function will panic.
// It returns a the deleted *state.Target.
func (s *targetCRUD) Delete(arg ...crud.Arg) (crud.Arg, error) {
	event := eventFromArg(arg[0])
	target := targetFromStuct(event)
	err := s.client.Targets.Delete(nil, target.Upstream.ID, target.ID)
	if err != nil {
		return nil, err
	}
	return target, nil
}

// Update updates a Target in Kong.
// The arg should be of type diff.Event, containing the target to be updated,
// else the function will panic.
// It returns a the updated *state.Target.
func (s *targetCRUD) Update(arg ...crud.Arg) (crud.Arg, error) {
	event := eventFromArg(arg[0])
	target := targetFromStuct(event)
	// Targets in Kong cannot be updated
	err := s.client.Targets.Delete(nil, target.Upstream.ID, target.ID)
	if err != nil {
		return nil, err
	}
	target.ID = nil
	createdTarget, err := s.client.Targets.Create(nil,
		target.Upstream.ID, &target.Target)
	if err != nil {
		return nil, err
	}
	return &state.Target{Target: *createdTarget}, nil
}