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

feature: WEOS-1342 As a developer I should be able have a datetime field automatically update on update #127

Merged
merged 23 commits into from
Mar 17, 2022
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
e244c5d
feature/WEOS-1359 Update time values by flag on route
atoniaw Feb 24, 2022
f5589b8
feature:WEOS-1116
RandyDeo Feb 25, 2022
e1bfa48
Changes by User
RandyDeo Feb 25, 2022
090e694
WEOS-1359 fixed possible model panic
atoniaw Feb 28, 2022
90bc8f7
WEOS-1359 Delete binary
atoniaw Feb 28, 2022
87e0388
Merge pull request #125 from wepala/WEOS-1359
atoniaw Feb 28, 2022
aaf46b3
Merge remote-tracking branch 'origin/feature/WEOS-1342' into feature/…
shaniah868 Feb 28, 2022
790ed0c
Merge branch 'dev' into feature/WEOS-1342
RandyDeo Mar 2, 2022
dd0b206
Merge branch 'dev' into feature/WEOS-1342
RandyDeo Mar 4, 2022
0d6ff00
Merge branch 'dev' into feature/WEOS-1342
shaniah868 Mar 8, 2022
33fe13c
doc: WEOS-1342 Added scenarios to cover using the x-update extension …
akeemphilbert Mar 9, 2022
8323b48
feature: WEOS-1342
RandyDeo Mar 10, 2022
d372af2
feature: WEOS-1342
RandyDeo Mar 10, 2022
e3e6893
feature: WEOS-1342
RandyDeo Mar 11, 2022
6680d05
feature: WEOS-1342
RandyDeo Mar 11, 2022
75b1fe9
feature: WEOS-1342
RandyDeo Mar 11, 2022
feeece6
Merge branch 'dev' into feature/WEOS-1342
RandyDeo Mar 11, 2022
6eb36e3
Merge branch 'dev' into feature/WEOS-1342
RandyDeo Mar 15, 2022
9176aa6
feature: WEOS-1342
RandyDeo Mar 15, 2022
0bd06ce
Merge branch 'dev' into feature/WEOS-1342
RandyDeo Mar 16, 2022
cf388bb
Merge branch 'dev' into feature/WEOS-1342
shaniah868 Mar 16, 2022
70c9aaf
feature: WEOS-1342 As a developer I should be able have a datetime fi…
shaniah868 Mar 16, 2022
d082973
Merge remote-tracking branch 'origin/feature/WEOS-1342' into feature/…
shaniah868 Mar 16, 2022
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
5 changes: 5 additions & 0 deletions api.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,14 @@ components:
lastUpdated:
type: string
format: date-time
x-update:
- Add Blog
- Update Blog
created:
type: string
format: date-time
x-update:
- Add Blog
required:
- title
- url
Expand Down
1 change: 1 addition & 0 deletions context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const HeaderXLogLevel = "X-LOG-LEVEL"

//add more keys here if needed
const ACCOUNT_ID ContextKey = "ACCOUNT_ID"
const OPERATION_ID = "OPERATION_ID"
const USER_ID ContextKey = "USER_ID"
const LOG_LEVEL ContextKey = "LOG_LEVEL"
const REQUEST_ID ContextKey = "REQUEST_ID"
Expand Down
44 changes: 44 additions & 0 deletions controllers/rest/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package rest_test
import (
"bytes"
"encoding/json"
"github.com/labstack/echo/v4"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
Expand Down Expand Up @@ -457,3 +459,45 @@ func TestRESTAPI_Initialize_DefaultResponseMiddlware(t *testing.T) {
os.Remove("test.db")
time.Sleep(1 * time.Second)
}

func TestRESTAPI_Integration_AutomaticallyUpdateDateTime(t *testing.T) {
tapi, err := api.New("./fixtures/blog.yaml")
if err != nil {
t.Fatalf("un expected error loading spec '%s'", err)
}
err = tapi.Initialize(nil)
if err != nil {
t.Fatalf("un expected error loading spec '%s'", err)
}
e := tapi.EchoInstance()
t.Run("automatically updating create", func(t *testing.T) {
mockBlog := map[string]interface{}{"title": "Test Blog", "url": "www.testBlog.com"}
reqBytes, err := json.Marshal(mockBlog)
if err != nil {
t.Fatalf("error setting up request %s", err)
}
body := bytes.NewReader(reqBytes)
resp := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/blogs", body)
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
e.ServeHTTP(resp, req)
if resp.Result().StatusCode != http.StatusCreated {
t.Errorf("expected the response code to be %d, got %d", http.StatusCreated, resp.Result().StatusCode)
}
defer resp.Result().Body.Close()
tResults, err := ioutil.ReadAll(resp.Result().Body)
if err != nil {
t.Errorf("unexpect error: %s", err)
}
results := map[string]interface{}{}
err = json.Unmarshal(tResults, &results)
if err != nil {
t.Errorf("unexpect error: %s", err)
}
if results["created"] == nil || results["lastUpdated"] == nil {
t.Errorf("unexpect error expected to find created and lastUpdated")
}

})

}
5 changes: 5 additions & 0 deletions controllers/rest/fixtures/blog.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,14 @@ components:
lastUpdated:
type: string
format: date-time
x-update:
- Add Blog
- Update Blog
created:
type: string
format: date-time
x-update:
- Add Blog
required:
- title
- url
Expand Down
3 changes: 3 additions & 0 deletions controllers/rest/middleware_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ func Context(api *RESTAPI, projection projections.Projection, commandDispatcher

cc, err = parseResponses(c, cc, operation)

//add OperationID to context
cc = context.WithValue(cc, weosContext.OPERATION_ID, operation.OperationID)

//parse request body based on content type
var payload []byte
ct := c.Request().Header.Get("Content-Type")
Expand Down
22 changes: 22 additions & 0 deletions controllers/rest/middleware_context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -509,4 +509,26 @@ func TestContext(t *testing.T) {
e.GET("/blogs", handler)
e.ServeHTTP(resp, req)
})

t.Run("add operationId to context", func(t *testing.T) {
path := swagger.Paths.Find("/blogs")
mw := rest.Context(restApi, nil, nil, nil, entityFactory, path, path.Get)
handler := mw(func(ctxt echo.Context) error {
//check that certain parameters are in the context
cc := ctxt.Request().Context()
value := cc.Value(context.OPERATION_ID)
if value == nil {
t.Fatalf("expected the operation id to have a value")
}
if value.(string) != "Get Blogs" {
t.Fatalf("expected the operation id to be Get Blogs")
}
return nil
})
e := echo.New()
resp := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/blogs", nil)
e.GET("/blogs", handler)
e.ServeHTTP(resp, req)
})
}
25 changes: 25 additions & 0 deletions model/content_entity.go
Original file line number Diff line number Diff line change
Expand Up @@ -749,3 +749,28 @@ func (w *ContentEntity) UnmarshalJSON(data []byte) error {
err = json.Unmarshal(data, &w.Property)
return err
}

//UpdateTime updates auto update time values on the payload
func (w *ContentEntity) UpdateTime(operationID string, data []byte) ([]byte, error) {
scheme := w.Schema
RandyDeo marked this conversation as resolved.
Show resolved Hide resolved
payload := map[string]interface{}{}
json.Unmarshal(data, &payload)
for key, p := range scheme.Properties {
routes := []string{}
routeBytes, _ := json.Marshal(p.Value.Extensions["x-update"])
json.Unmarshal(routeBytes, &routes)
for _, r := range routes {
if r == operationID {
if p.Value.Format == "date-time" {
payload[key] = time.Now()
}
}
}
}
newPayload, err := json.Marshal(payload)
if err != nil {
return nil, err
}

return newPayload, nil
}
33 changes: 33 additions & 0 deletions model/content_entity_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -848,3 +848,36 @@ func TestContentEntity_EnumerationFloat(t *testing.T) {
}
})
}

func TestContentEntity_UpdateTime(t *testing.T) {
//load open api spec
api, err := rest.New("../controllers/rest/fixtures/blog.yaml")
schemas := rest.CreateSchema(context.TODO(), api.EchoInstance(), api.Swagger)
contentType := "Blog"
entityFactory := new(model.DefaultEntityFactory).FromSchemaAndBuilder(contentType, api.Swagger.Components.Schemas[contentType].Value, schemas[contentType])
if err != nil {
t.Fatalf("error setting up entity factory")
}
entity, err := entityFactory.NewEntity(context.TODO())
if err != nil {
t.Fatalf("error generating entity '%s'", err)
}

mapPayload := map[string]interface{}{"title": "update time", "description": "new time", "url": "www.MyBlog.com"}
newPayload, errr := json.Marshal(mapPayload)
if errr != nil {
t.Fatalf("error marshalling Payload '%s'", err)
}

updatedTimePayload, errrr := entity.UpdateTime("Update Blog", newPayload)
if errrr != nil {
t.Fatalf("error updating time payload '%s'", err)
}

tempPayload := map[string]interface{}{}
json.Unmarshal(updatedTimePayload, &tempPayload)

if tempPayload["lastUpdated"] == "" {
t.Fatalf("expected the lastupdated field to not be blank")
}
}
38 changes: 37 additions & 1 deletion model/domain_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ func (s *DomainService) Update(ctx context.Context, payload json.RawMessage, ent
seqNo = seq
}

existingEntity, err := s.GetContentEntity(ctx, entityFactory, weosID)
existingEntity, err = s.GetContentEntity(ctx, entityFactory, weosID)
if err != nil {
return nil, NewDomainError("invalid: unexpected error fetching existing entity", entityType, weosID, err)
}
Expand Down Expand Up @@ -192,6 +192,15 @@ func (s *DomainService) Update(ctx context.Context, payload json.RawMessage, ent
}
}

//update default time update values based on routes
operation, ok := ctx.Value(weosContext.OPERATION_ID).(string)
if ok {
newPayload, err = existingEntity.UpdateTime(operation, newPayload)
}
if err != nil {
return nil, err
}

updatedEntity, err = existingEntity.Update(ctx, newPayload)
if err != nil {
return nil, err
Expand Down Expand Up @@ -235,6 +244,15 @@ func (s *DomainService) Update(ctx context.Context, payload json.RawMessage, ent
return nil, err
}

//update default time update values based on routes
operation, ok := ctx.Value(weosContext.OPERATION_ID).(string)
if ok {
newPayload, err = existingEntity.UpdateTime(operation, newPayload)
if err != nil {
return nil, err
}
}

updatedEntity, err = existingEntity.Update(ctx, newPayload)
if err != nil {
s.logger.Errorf("error updating entity", err)
Expand Down Expand Up @@ -314,6 +332,15 @@ func (s *DomainService) Delete(ctx context.Context, entityID string, entityType
return nil, err
}

//update default time update values based on routes
operation, ok := ctx.Value(weosContext.OPERATION_ID).(string)
if ok {
existingEntityPayload, err = existingEntity.UpdateTime(operation, existingEntityPayload)
if err != nil {
return nil, err
}
}

deletedEntity, err = existingEntity.Delete(existingEntityPayload)
if err != nil {
return nil, err
Expand All @@ -340,6 +367,15 @@ func (s *DomainService) Delete(ctx context.Context, entityID string, entityType
return nil, err
}

//update default time update values based on routes
operation, ok := ctx.Value(weosContext.OPERATION_ID).(string)
if ok {
data, err = existingEntity.UpdateTime(operation, data)
if err != nil {
return nil, err
}
}

deletedEntity, err = existingEntity.Delete(data)
if err != nil {
return nil, err
Expand Down
10 changes: 10 additions & 0 deletions model/receiver.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"

weosContext "github.com/wepala/weos/context"
"golang.org/x/net/context"
)

Expand Down Expand Up @@ -37,6 +38,15 @@ func CreateHandler(ctx context.Context, command *Command, eventStore EventReposi
return err
}

//update default time update values based on routes
operation, ok := ctx.Value(weosContext.OPERATION_ID).(string)
if ok {
payload, err = newEntity.UpdateTime(operation, payload)
if err != nil {
return err
}
}

//use the entity id that was passed with the command
newEntity.ID = command.Metadata.EntityID
//add create event
Expand Down