Skip to content

Commit

Permalink
refactor: use pointer to collection
Browse files Browse the repository at this point in the history
  • Loading branch information
fdemir committed Dec 9, 2023
1 parent 6a17366 commit 36f2d5d
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 20 deletions.
8 changes: 3 additions & 5 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ func HandleBase(w http.ResponseWriter, r *http.Request, s *Source, opt *ServeOpt

path := r.URL.Path[1:]
response := s.data[path]
collection := response.([]interface{})

if response == nil {
w.WriteHeader(http.StatusNotFound)
Expand All @@ -32,24 +31,23 @@ func HandleBase(w http.ResponseWriter, r *http.Request, s *Source, opt *ServeOpt
case http.MethodGet:
data := GetAll(
r.URL.Query(),
collection,
response,
)

json.NewEncoder(w).Encode(data)
case http.MethodPost:
Create(
r.Body,
&collection,
response,
)

w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(r.Body)
case http.MethodDelete:
id := r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:]

Delete(
id,
&collection,
response,
)

w.WriteHeader(http.StatusNoContent)
Expand Down
4 changes: 2 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
)

type Source struct {
data map[string]interface{}
data map[string]*[]interface{}
}

type ServeOptions struct {
Expand All @@ -30,7 +30,7 @@ func read(path string) *Source {

defer file.Close()

jsonMap := make(map[string]interface{})
jsonMap := make(map[string]*[]interface{})

if err = json.NewDecoder(file).Decode(&jsonMap); err != nil {
log.Fatal(err)
Expand Down
17 changes: 4 additions & 13 deletions repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package main

import (
"encoding/json"
"fmt"
"io"
"net/url"
"strconv"
Expand All @@ -11,14 +10,14 @@ import (

func GetAll(
params url.Values,
collection []interface{},
collection *[]interface{},
) []interface{} {
result := []interface{}{}
limit, _ := strconv.Atoi(params.Get("_limit"))

if len(params) > 0 {
count := 0
for _, item := range collection {
for _, item := range *collection {
hasLimitReached := limit > 0 && count >= limit

if hasLimitReached {
Expand Down Expand Up @@ -56,7 +55,7 @@ func GetAll(
count += 1
}
} else {
result = collection
result = *collection
}

return result
Expand All @@ -68,18 +67,10 @@ func Create(
) error {
var body map[string]interface{}

err := json.NewDecoder(payload).Decode(&body)
if err != nil {
if err := json.NewDecoder(payload).Decode(&body); err != nil {
return err
}

for _, item := range *collection {
item := item.(map[string]interface{})
if item["id"] == body["id"] {
return fmt.Errorf("id already exists")
}
}

*collection = append(*collection, body)

return nil
Expand Down

0 comments on commit 36f2d5d

Please sign in to comment.