/
company.go
56 lines (43 loc) · 1.37 KB
/
company.go
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
package controllers
import (
"encoding/json"
"errors"
"net/http"
"golang.org/x/net/context"
"google.golang.org/appengine/datastore"
"github.com/coduno/api/model"
)
func init() {
router.Handle("/companies", ContextHandlerFunc(PostCompany))
router.Handle("/companies/{key}/challenges", ContextHandlerFunc(GetChallengesForCompany))
router.Handle("/companies/{key}/users", ContextHandlerFunc(GetUsersByCompany))
}
// PostCompany creates a new company after validating by key.
func PostCompany(ctx context.Context, w http.ResponseWriter, r *http.Request) (status int, err error) {
if r.Method != "POST" {
return http.StatusMethodNotAllowed, nil
}
var company model.Company
if err = json.NewDecoder(r.Body).Decode(&company); err != nil {
return http.StatusBadRequest, err
}
var companies model.Companys
_, err = model.NewQueryForCompany().
Filter("Address =", company.Address.Address).
Limit(1).
GetAll(ctx, &companies)
if err != nil {
return http.StatusInternalServerError, err
}
if len(companies) > 0 {
return http.StatusConflict, errors.New("already registered")
}
var key *datastore.Key
if key, err = company.Put(ctx, nil); err != nil {
return http.StatusInternalServerError, err
}
// TODO(flowlo): Respond with HTTP 201 and include a
// location header and caching information.
json.NewEncoder(w).Encode(company.Key(key))
return http.StatusOK, nil
}