Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add team API #5

Merged
merged 3 commits into from
Jun 18, 2015
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
212 changes: 212 additions & 0 deletions api_team.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
package main

import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"

"github.com/gorilla/mux"
)

type TeamsResponse struct {
Teams []Team `json:"teams,omitempty"`
Message string `json:"message"`
Error string `json:"error"`
}

// Fetches every team from the DB and returns them as JSON
func ListTeams(w http.ResponseWriter, r *http.Request) {
var res TeamsResponse

t, err := c.GetAllTeams()
if err != nil {
res.Error = err.Error()
errjson, _ := json.Marshal(res)
http.Error(w, string(errjson), http.StatusInternalServerError)
return
}

for _, v := range t {
res.Teams = append(res.Teams, *v)
}

json.NewEncoder(w).Encode(res)
}

// Fetches a single person form the DB and returns them as JSON
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Fetches a single team from the DB and returns it as JSON"

func ShowTeam(w http.ResponseWriter, r *http.Request) {
var res TeamsResponse

vars := mux.Vars(r)
name := vars["team"]

p, err := c.GetTeam(name)
if err != nil {
res.Error = err.Error()
errjson, _ := json.Marshal(res)
http.Error(w, string(errjson), http.StatusNotFound)
return
}

res.Teams = append(res.Teams, *p)

json.NewEncoder(w).Encode(res)
}

// Deletes the specified team from the database
func DeleteTeam(w http.ResponseWriter, r *http.Request) {
var res PeopleResponse

vars := mux.Vars(r)
name := vars["team"]

err := c.DeleteTeam(name)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}

res.Message = fmt.Sprint("Team ", name, " deleted")

json.NewEncoder(w).Encode(res)
}

// Creates a new person in the database
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/person/team/

func CreateTeam(w http.ResponseWriter, r *http.Request) {
var res TeamsResponse
var t Team

// We're getting the details of this new team from the POSTed JSON
// so we first need to read in the body of the POST
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1024*10))
// If something went wrong, return an error in the JSON response
if err != nil {
res.Error = err.Error()
json.NewEncoder(w).Encode(res)
return
}

err = r.Body.Close()
if err != nil {
res.Error = err.Error()
json.NewEncoder(w).Encode(res)
return
}

// Attempt to unmarshall the JSON into our Person struct
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/Person/Team/

err = json.Unmarshal(body, &t)
if err != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // unprocessable entity
res.Error = err.Error()
json.NewEncoder(w).Encode(res)
return
}

// If a name was not provided, return an error
if t.Name == "" {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // unprocessable entity
res.Error = "Must provide username and fullname"
json.NewEncoder(w).Encode(res)
return
}

// Make sure that this team doesn't already exist
fp, err := c.GetTeam(t.Name)
if fp != nil && fp.Name != "" {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // unprocessable entity
res.Error = fmt.Sprint("Team ", t.Name, " already exists. Use PUT /teams/", t.Name, "/ to update.")
json.NewEncoder(w).Encode(res)
return
}
if err != nil {
log.Println("GetTeam() failed:", err)
}

// Store our new team in the DB
err = c.StoreTeam(&t)
if err != nil {
log.Println("Error storing person:", err)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // unprocessable entity
res.Error = err.Error()
json.NewEncoder(w).Encode(res)
return
}

res.Message = fmt.Sprint("Team ", t.Name, " created")

json.NewEncoder(w).Encode(res)
}

// Updates an existing person in the database
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should be "team"

func UpdateTeam(w http.ResponseWriter, r *http.Request) {
var res TeamsResponse
var t Team

vars := mux.Vars(r)
name := vars["team"]

body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1024*10))
// If something went wrong, return an error in the JSON response
if err != nil {
res.Error = err.Error()
json.NewEncoder(w).Encode(res)
return
}

err = r.Body.Close()
if err != nil {
res.Error = err.Error()
json.NewEncoder(w).Encode(res)
return
}

err = json.Unmarshal(body, &t)

if err != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // unprocessable entity
res.Error = err.Error()
json.NewEncoder(w).Encode(res)
return
}

// Make sure the user actually exists before updating
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/user/team/

fp, err := c.GetTeam(name)
if fp != nil && fp.Name == "" {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // unprocessable entity
res.Error = fmt.Sprint("Team ", t.Name, " does not exist. Use POST to create.")
json.NewEncoder(w).Encode(res)
return
}
if err != nil {
log.Println("GetTeam() failed for", name)
}

// Now that we know our team exists in the DB, copy the username from the URI path and add it to our struct
t.Name = name

// Store the updated user in the DB
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/user/team/

err = c.StoreTeam(&t)
if err != nil {
log.Println("Error storing team", err)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // unprocessable entity
res.Error = err.Error()
json.NewEncoder(w).Encode(res)
return
}

res.Teams = append(res.Teams, t)
res.Message = fmt.Sprint("Team ", name, " updated")

json.NewEncoder(w).Encode(res)

}
15 changes: 15 additions & 0 deletions chickenlittle.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,21 @@ func main() {
apiRouter.HandleFunc("/notifications/{uuid}", StopNotification).
Methods("DELETE")

apiRouter.HandleFunc("/teams", ListTeams).
Methods("GET")

apiRouter.HandleFunc("/teams", CreateTeam).
Methods("POST")

apiRouter.HandleFunc("/teams/{team}", ShowTeam).
Methods("GET")

apiRouter.HandleFunc("/teams/{team}", DeleteTeam).
Methods("DELETE")

apiRouter.HandleFunc("/teams/{team}", UpdateTeam).
Methods("PUT")

go func() {
log.Fatal(http.ListenAndServe(c.Config.Service.APIListenAddr, apiRouter))
}()
Expand Down
161 changes: 161 additions & 0 deletions docs/TEAM_API.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
# Team API

## Get list of all teams
**Request**
```
GET /teams
```

**Example Response**
```
HTTP/1.1 200 OK
```
```json
{
"teams": [
{
"description": "Kings",
"members": [
"arthur"
],
"name": "kings",
"rotation": {
"description": "none",
"frequency": 0,
"time": "0001-01-01T00:00:00Z"
},
"steps": [
{
"method": 0,
"target": "",
"timebefore": 3600
}
]
}
],
"message": "",
"error": ""
}
```

## Fetch details for a team
**Request**
```
GET /teams/NAME
```

**Example Response**
```
HTTP/1.1 200 OK
```
```json
{
"teams": [
{
"description": "Kings",
"members": [
"arthur"
],
"name": "kings",
"rotation": {
"description": "none",
"frequency": 0,
"time": "0001-01-01T00:00:00Z"
},
"steps": [
{
"method": 0,
"target": "",
"timebefore": 3600
}
]
}
],
"message": "",
"error": ""
}
```

## Create a new team
**Request**
```
POST /teams

{
"description": "Kings",
"members": [
"arthur"
],
"name": "kings",
"rotation": {
"description": "none",
"frequenc": 0,
"time": 0
},
"steps": {
"method": 0,
"target": "",
"timebefore": 3600
}
}
```

**Example Response**
```
HTTP/1.1 200 OK
```
```json
{
"message": "Team kings created",
"error": ""
}
```

## Update a team
**Request**
```
PUT /teams/NAME

{
"description": "Kings and Queens",
"members": [
"arthur",
"lancelot"
]
}
```

**Example Response**
```
HTTP/1.1 200 OK
```
```json
{
"teams": [
{
"name": "kings",
"description": "Kings and Queens"
}
],
"message": "Team kings updated",
"error": ""
}
```

## Delete a team
**Request**
```
DELETE /teams/NAME
```

**Example Response**
```
HTTP/1.1 200 OK
```
```json
{
"message": "Team kings deleted",
"error": ""
}
```

Loading