1package handlers
2
3import (
4	"encoding/json"
5	"net/http"
6	"reflect"
7
8	"github.com/gorilla/mux"
9	corev2 "github.com/sensu/sensu-go/api/core/v2"
10	"github.com/sensu/sensu-go/backend/apid/actions"
11	"github.com/sensu/sensu-go/backend/store"
12)
13
14// CreateResource creates the resource given in the request body but only if it
15// does not already exist
16func (h Handlers) CreateResource(r *http.Request) (interface{}, error) {
17	payload := reflect.New(reflect.TypeOf(h.Resource).Elem())
18	if err := json.NewDecoder(r.Body).Decode(payload.Interface()); err != nil {
19		return nil, actions.NewError(actions.InvalidArgument, err)
20	}
21
22	if err := CheckMeta(payload.Interface(), mux.Vars(r)); err != nil {
23		return nil, actions.NewError(actions.InvalidArgument, err)
24	}
25
26	resource, ok := payload.Interface().(corev2.Resource)
27	if !ok {
28		return nil, actions.NewErrorf(actions.InvalidArgument)
29	}
30
31	if err := h.Store.CreateResource(r.Context(), resource); err != nil {
32		switch err := err.(type) {
33		case *store.ErrAlreadyExists:
34			return nil, actions.NewErrorf(actions.AlreadyExistsErr)
35		case *store.ErrNotValid:
36			return nil, actions.NewErrorf(actions.InvalidArgument)
37		default:
38			return nil, actions.NewError(actions.InternalErr, err)
39		}
40	}
41
42	return nil, nil
43}
44