|
| 1 | +package client |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + |
| 6 | + "github.com/machinebox/graphql" |
| 7 | +) |
| 8 | + |
| 9 | +type VMClient interface { |
| 10 | + ListVMs(ctx context.Context) (*ListVMsModel, error) |
| 11 | + Start(ctx context.Context, id string) (*StartVMModel, error) |
| 12 | + Stop(ctx context.Context, id string) (*StopVMModel, error) |
| 13 | +} |
| 14 | + |
| 15 | +type RealVMClient struct { |
| 16 | + ApiKey string |
| 17 | + GraphQLClient *graphql.Client |
| 18 | +} |
| 19 | + |
| 20 | +var _ VMClient = (*RealVMClient)(nil) |
| 21 | + |
| 22 | +func NewVMClient(apiKey string, graphqlClient *graphql.Client) VMClient { |
| 23 | + return &RealVMClient{ |
| 24 | + ApiKey: apiKey, |
| 25 | + GraphQLClient: graphqlClient, |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +type ListVMsModel struct { |
| 30 | + VMs struct { |
| 31 | + ID string `json:"id"` |
| 32 | + Domains []struct { |
| 33 | + Name string `json:"name"` |
| 34 | + State string `json:"state"` |
| 35 | + Id string `json:"id"` |
| 36 | + } `json:"domains"` |
| 37 | + } `json:"vms"` |
| 38 | +} |
| 39 | + |
| 40 | +func (c *RealVMClient) ListVMs(ctx context.Context) (*ListVMsModel, error) { |
| 41 | + qglQuery := ` |
| 42 | + query Query { |
| 43 | + vms { |
| 44 | + id |
| 45 | + domains { |
| 46 | + id |
| 47 | + name |
| 48 | + state |
| 49 | + } |
| 50 | + } |
| 51 | + }` |
| 52 | + |
| 53 | + req := graphql.NewRequest(qglQuery) |
| 54 | + auth(req, c.ApiKey) |
| 55 | + |
| 56 | + return query[ListVMsModel](ctx, c.GraphQLClient, req) |
| 57 | +} |
| 58 | + |
| 59 | +type StartVMModel struct { |
| 60 | + Id string `json:"id"` |
| 61 | +} |
| 62 | + |
| 63 | +func (c *RealVMClient) Start(ctx context.Context, id string) (*StartVMModel, error) { |
| 64 | + qglQuery := ` |
| 65 | + mutation Start($startId: PrefixedID!) { |
| 66 | + vm { |
| 67 | + start(id: $startId) |
| 68 | + } |
| 69 | + }` |
| 70 | + |
| 71 | + req := graphql.NewRequest(qglQuery) |
| 72 | + auth(req, c.ApiKey) |
| 73 | + req.Var("startId", id) |
| 74 | + |
| 75 | + return query[StartVMModel](ctx, c.GraphQLClient, req) |
| 76 | +} |
| 77 | + |
| 78 | +type StopVMModel struct { |
| 79 | + Id string `json:"id"` |
| 80 | +} |
| 81 | + |
| 82 | +func (c *RealVMClient) Stop(ctx context.Context, id string) (*StopVMModel, error) { |
| 83 | + qglQuery := ` |
| 84 | + mutation Stop($stopId: PrefixedID!) { |
| 85 | + vm { |
| 86 | + stop(id: $stopId) |
| 87 | + } |
| 88 | + }` |
| 89 | + |
| 90 | + req := graphql.NewRequest(qglQuery) |
| 91 | + auth(req, c.ApiKey) |
| 92 | + req.Var("stopId", id) |
| 93 | + |
| 94 | + return ignoreNotFound(query[StopVMModel](ctx, c.GraphQLClient, req)) |
| 95 | +} |
0 commit comments