Skip to content

Commit

Permalink
Merge pull request #15 from nekochans/feature/issue10
Browse files Browse the repository at this point in the history
存在しないpostalCodeが指定された際に適切なエラーを返すように修正
  • Loading branch information
keitakn committed Jul 17, 2021
2 parents 4ced52d + b69b73f commit 2082e1b
Show file tree
Hide file tree
Showing 6 changed files with 139 additions and 14 deletions.
76 changes: 75 additions & 1 deletion application/address_scenario_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func TestMain(m *testing.M) {
type mockResponse struct {
Body string
StatusCode int
Result *repository.FindAddressesResponse
Result interface{}
Error error
}

Expand Down Expand Up @@ -53,6 +53,28 @@ func createSuccessMockClient(mockAddress *repository.Address) *successMockClient
return &successMockClient{MockAddress: mockAddress}
}

type errorMockClient struct {
StatusCode int
MockResBody interface{}
}

func (c *errorMockClient) Do(req *http.Request) (*http.Response, error) {
bodyJson, _ := json.Marshal(c.MockResBody)

mockRes := &mockResponse{
Body: string(bodyJson),
StatusCode: c.StatusCode,
Result: c.MockResBody,
}

return &http.Response{StatusCode: mockRes.StatusCode, Body: io.NopCloser(strings.NewReader(mockRes.Body))}, nil
}

func createErrorMockClient(statusCode int, mockResBody interface{}) *errorMockClient {
return &errorMockClient{StatusCode: statusCode, MockResBody: mockResBody}
}

// nolint:funlen
func TestHandler(t *testing.T) {
t.Run("Successful FindByPostalCode", func(t *testing.T) {
mockAddress := &repository.Address{
Expand Down Expand Up @@ -86,4 +108,56 @@ func TestHandler(t *testing.T) {
t.Error("\nActually: ", res, "\nExpected: ", expected)
}
})

t.Run("Error FindByPostalCode Address is not found", func(t *testing.T) {
mockResBody := &repository.Address{}

client := createErrorMockClient(404, mockResBody)

repo := &repository.KenallAddressRepository{HttpClient: client}

scenario := AddressScenario{
AddressRepository: repo,
}

req := &FindByPostalCodeRequest{PostalCode: "4040000"}
res, err := scenario.FindByPostalCode(req)

expected := "Address is not found"
if res != nil {
t.Error("\nActually: ", res, "\nExpected: ", expected)
}

if err != nil {
if err.Error() != expected {
t.Error("\nActually: ", err, "\nExpected: ", expected)
}
}
})

t.Run("Error FindByPostalCode Unexpected error", func(t *testing.T) {
mockResBody := &repository.Address{}

client := createErrorMockClient(500, mockResBody)

repo := &repository.KenallAddressRepository{HttpClient: client}

scenario := AddressScenario{
AddressRepository: repo,
}

req := &FindByPostalCodeRequest{PostalCode: "1000000"}
res, err := scenario.FindByPostalCode(req)

expected := "Unexpected error"
if res != nil {
t.Error("\nActually: ", res, "\nExpected: ", expected)
}

if err != nil {
if err.Error() != expected {
t.Error("\nActually: ", err, "\nExpected: ", expected)
}
}
})
}
50 changes: 38 additions & 12 deletions cmd/lambda/findbypostalcode/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"net/http"
"time"

"github.com/nekochans/address-search-apis/domain"

"github.com/nekochans/address-search-apis/application"
"github.com/nekochans/address-search-apis/infrastructure/repository"

Expand All @@ -17,9 +19,8 @@ const timeout = 10

var client *http.Client

type ResponseOkBody struct {
Prefecture string `json:"prefecture"`
Locality string `json:"locality"`
type ResponseErrorBody struct {
Message string `json:"message"`
}

//nolint:gochecknoinits
Expand All @@ -40,6 +41,22 @@ func createApiGatewayV2Response(statusCode int, resBodyJson []byte) events.APIGa
return res
}

func createErrorResponse(statusCode int, message string) events.APIGatewayV2HTTPResponse {
resBody := &ResponseErrorBody{Message: message}
resBodyJson, _ := json.Marshal(resBody)

res := events.APIGatewayV2HTTPResponse{
StatusCode: statusCode,
Headers: map[string]string{
"Content-Type": "application/json",
},
Body: string(resBodyJson),
IsBase64Encoded: false,
}

return res
}

func Handler(ctx context.Context, req events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error) {
if val, ok := req.PathParameters["postalCode"]; ok {
repo := &repository.KenallAddressRepository{HttpClient: client}
Expand All @@ -51,22 +68,31 @@ func Handler(ctx context.Context, req events.APIGatewayV2HTTPRequest) (events.AP
PostalCode: val,
}

// TODO 後でエラー処理を行う
resBody, _ := scenario.FindByPostalCode(request)
resBody, err := scenario.FindByPostalCode(request)
if err != nil {
var statusCode int
var message string

switch err.Error() {
case domain.ErrAddressRepositoryNotFound.Error():
statusCode = http.StatusNotFound
message = "住所が見つかりませんでした"
default:
statusCode = http.StatusInternalServerError
message = "予期せぬエラーが発生しました"
}

return createErrorResponse(statusCode, message), nil
}

resBodyJson, _ := json.Marshal(resBody)

res := createApiGatewayV2Response(http.StatusOK, resBodyJson)

return res, nil
}

// TODO ここに入ってきたらエラーで返すようにする
resBody := &ResponseOkBody{Prefecture: "東京都", Locality: "新宿区"}
resBodyJson, _ := json.Marshal(resBody)

res := createApiGatewayV2Response(http.StatusOK, resBodyJson)

return res, nil
return createErrorResponse(http.StatusInternalServerError, "予期せぬエラーが発生しました"), nil
}

func main() {
Expand Down
7 changes: 7 additions & 0 deletions domain/address_repository.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
package domain

import "github.com/pkg/errors"

type AddressRepository interface {
FindByPostalCode(postalCode string) (*Address, error)
}

var (
ErrAddressRepositoryNotFound = errors.New("Address is not found")
ErrAddressRepositoryUnexpected = errors.New("Unexpected error")
)
5 changes: 4 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@ module github.com/nekochans/address-search-apis

go 1.16

require github.com/aws/aws-lambda-go v1.24.0
require (
github.com/aws/aws-lambda-go v1.24.0
github.com/pkg/errors v0.9.1
)
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsr
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
Expand Down
13 changes: 13 additions & 0 deletions infrastructure/repository/kenall_address_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (

"github.com/nekochans/address-search-apis/domain"
"github.com/nekochans/address-search-apis/infrastructure"
"github.com/pkg/errors"
)

type KenallAddressRepository struct {
Expand Down Expand Up @@ -66,6 +67,18 @@ func (r *KenallAddressRepository) FindByPostalCode(postalCode string) (*domain.A
}
}()

if resp.StatusCode != http.StatusOK {
var err error

switch resp.StatusCode {
case http.StatusNotFound:
err = domain.ErrAddressRepositoryNotFound
default:
err = domain.ErrAddressRepositoryUnexpected
}
return nil, errors.WithStack(err)
}

var resBody FindAddressesResponse
if err := json.NewDecoder(resp.Body).Decode(&resBody); err != nil {
return nil, err
Expand Down

0 comments on commit 2082e1b

Please sign in to comment.