Skip to content

Commit

Permalink
add Url.Update
Browse files Browse the repository at this point in the history
  • Loading branch information
asim committed Jul 21, 2022
1 parent 1ea66cc commit f74432f
Show file tree
Hide file tree
Showing 5 changed files with 262 additions and 49 deletions.
9 changes: 9 additions & 0 deletions url/examples.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,15 @@
}]
}
}],
"update": [{
"title": "Update a short URL",
"run_check": false,
"request": {
"shortURL": "https://m3o.one/u/f8f3f83f3f83g",
"destinationURL": "https://mynewsite.com/this-is-a-rather-long-web-address"
},
"response": {}
}],
"shorten": [{
"title": "Shorten a long URL",
"run_check": false,
Expand Down
41 changes: 41 additions & 0 deletions url/handler/url.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,47 @@ func (e *Url) Delete(ctx context.Context, req *url.DeleteRequest, rsp *url.Delet
return nil
}

func (e *Url) Update(ctx context.Context, req *url.UpdateRequest, rsp *url.UpdateResponse) error {
tenantId, ok := tenant.FromContext(ctx)
if !ok {
return errors.Unauthorized("url.shorten", "not authorized")
}

id := strings.Replace(req.ShortURL, e.hostPrefix, "", -1)

// check the owner has this short url
records, err := store.Read("urlOwner/" + tenantId + "/" + id)
if err != nil {
return err
}

if len(records) == 0 {
return errors.NotFound("url.update", "not found")
}

uri := new(url.URLPair)
if err := records[0].Decode(uri); err != nil {
return err
}

// set the destination url
uri.DestinationURL = req.DestinationURL

// write a global key
key := "url/" + id
if err := store.Write(store.NewRecord(key, uri)); err != nil {
return err
}

// write per owner key
key = "urlOwner/" + tenantId + "/" + id
if err := store.Write(store.NewRecord(key, uri)); err != nil {
return err
}

return nil
}

func (e *Url) Shorten(ctx context.Context, req *url.ShortenRequest, rsp *url.ShortenResponse) error {
tenantId, ok := tenant.FromContext(ctx)
if !ok {
Expand Down

0 comments on commit f74432f

Please sign in to comment.