Skip to content

Commit

Permalink
Refactor listclients in things service
Browse files Browse the repository at this point in the history
Signed-off-by: nyagamunene <[email protected]>
  • Loading branch information
nyagamunene committed Jul 2, 2024
1 parent a259358 commit 3affcca
Show file tree
Hide file tree
Showing 19 changed files with 39 additions and 757 deletions.
28 changes: 0 additions & 28 deletions api/openapi/things.yml
Original file line number Diff line number Diff line change
Expand Up @@ -401,34 +401,6 @@ paths:
"500":
$ref: "#/components/responses/ServiceError"

/things/search:
get:
operationId: searchThings
summary: Searches for things
description: |
Searches for things based on the provided query parameters i.e name, id and tags.
tags:
- Things
parameters:
- $ref: "#/components/parameters/ThingName"
- $ref: "#/components/parameters/ThingID"
- $ref: "#/components/parameters/Tags"
- $ref: "#/components/parameters/Offset"
- $ref: "#/components/parameters/Limit"
responses:
"200":
$ref: "#/components/responses/ThingPageRes"
"400":
description: Failed due to malformed query parameters.
"401":
description: Missing or invalid access token provided.
"403":
description: Failed to perform authorization over the entity.
"422":
description: Database can't process request.
"500":
$ref: "#/components/responses/ServiceError"

/channels/{chanID}/things:
get:
operationId: listThingsInaChannel
Expand Down
43 changes: 0 additions & 43 deletions cli/things.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@ package cli

import (
"encoding/json"
"fmt"
"net/url"
"strconv"

mgclients "github.com/absmach/magistrala/pkg/clients"
mgxsdk "github.com/absmach/magistrala/pkg/sdk/go"
Expand Down Expand Up @@ -365,46 +362,6 @@ var cmdThings = []cobra.Command{
logJSON(ul)
},
},
{
Use: "search <query> <user_auth_token>",
Short: "Search things",
Long: "Search things by name, id or tags\n" +
"Usage:\n" +
"\tmagistrala-cli things search <query> <user_auth_token>\n",
Run: func(cmd *cobra.Command, args []string) {
if len(args) != 2 {
logUsage(cmd.Use)
return
}

values, err := url.ParseQuery(args[0])
if err != nil {
logError(fmt.Errorf("Failed to parse query: %s", err))
}

pm := mgxsdk.PageMetadata{
Name: values.Get("name"),
ID: values.Get("id"),
Tag: values.Get("tag"),
}

if off, err := strconv.Atoi(values.Get("offset")); err == nil {
pm.Offset = uint64(off)
}

if lim, err := strconv.Atoi(values.Get("limit")); err == nil {
pm.Limit = uint64(lim)
}

things, err := sdk.SearchThings(pm, args[1])
if err != nil {
logError(err)
return
}

logJSON(things)
},
},
}

// NewThingsCmd returns things command.
Expand Down
6 changes: 0 additions & 6 deletions pkg/apiutil/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,10 +179,4 @@ var (

// ErrInvalidTimeFormat indicates invalid time format i.e not unix time.
ErrInvalidTimeFormat = errors.New("invalid time format use unix time")

// ErrEmptySearchQuery indicates empty search query.
ErrEmptySearchQuery = errors.New("search query must not be empty")

// ErrLenSearchQuery indicates search query length.
ErrLenSearchQuery = errors.New("search query must be at least 3 characters")
)
4 changes: 2 additions & 2 deletions pkg/clients/clients.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ type Repository interface {
// RetrieveAll retrieves all clients.
RetrieveAll(ctx context.Context, pm Page) (ClientsPage, error)

// RetrieveAllBasicInfo list all clients only with basic information.
RetrieveAllBasicInfo(ctx context.Context, pm Page) (ClientsPage, error)
// SearchBasicInfo retrieves clients based on search criteria.
SearchBasicInfo(ctx context.Context, pm Page) (ClientsPage, error)

// RetrieveAllByIDs retrieves for given client IDs .
RetrieveAllByIDs(ctx context.Context, pm Page) (ClientsPage, error)
Expand Down
56 changes: 5 additions & 51 deletions pkg/clients/postgres/clients.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ func (repo *Repository) RetrieveAll(ctx context.Context, pm clients.Page) (clien
}

func (repo *Repository) SearchBasicInfo(ctx context.Context, pm clients.Page) (clients.ClientsPage, error) {
sq, tq := ConstructSearchQuery(pm)
sq, tq := constructSearchQuery(pm)

q := fmt.Sprintf(`SELECT c.id, c.name, c.created_at, c.updated_at FROM clients c %s LIMIT :limit OFFSET :offset;`, sq)

Expand Down Expand Up @@ -334,24 +334,6 @@ func (repo *Repository) Delete(ctx context.Context, id string) error {
return nil
}

func (repo *Repository) CheckSuperAdmin(ctx context.Context, adminID string) error {
q := "SELECT 1 FROM clients WHERE id = $1 AND role = $2"
rows, err := repo.DB.QueryContext(ctx, q, adminID, clients.AdminRole)
if err != nil {
return postgres.HandleError(repoerr.ErrViewEntity, err)
}
defer rows.Close()

if rows.Next() {
if err := rows.Err(); err != nil {
return postgres.HandleError(repoerr.ErrViewEntity, err)
}
return nil
}

return repoerr.ErrNotFound
}

type DBClient struct {
ID string `db:"id"`
Name string `db:"name,omitempty"`
Expand Down Expand Up @@ -523,11 +505,11 @@ func PageQuery(pm clients.Page) (string, error) {
return emq, nil
}

func ConstructSearchQuery(pm clients.Page) (string, string) {
func constructSearchQuery(pm clients.Page) (string, string) {
var query []string
var emq string
var tq string

fmt.Printf("PM: %+v\n", pm)
if pm.Name != "" {
query = append(query, "name ILIKE '%' || :name || '%'")
}
Expand All @@ -537,35 +519,6 @@ func ConstructSearchQuery(pm clients.Page) (string, string) {
if pm.Id != "" {
query = append(query, "id ILIKE '%' || :id || '%'")
}

if len(query) > 0 {
emq = fmt.Sprintf("WHERE %s", strings.Join(query, " AND "))
}

tq = emq

switch pm.Order {
case "name", "identity", "created_at", "updated_at":
emq = fmt.Sprintf("%s ORDER BY %s", emq, pm.Order)
if pm.Dir == api.AscDir || pm.Dir == api.DescDir {
emq = fmt.Sprintf("%s %s", emq, pm.Dir)
}
}

return emq, tq
}

func ConstructThingSearchQuery(pm clients.Page) (string, string) {
var query []string
var emq string
var tq string

if pm.Name != "" {
query = append(query, "name ILIKE '%' || :name || '%'")
}
if pm.Id != "" {
query = append(query, "id ILIKE '%' || :id || '%'")
}
if pm.Tag != "" {
query = append(query, "EXISTS (SELECT 1 FROM unnest(tags) AS tag WHERE tag ILIKE '%' || :tag || '%')")
}
Expand All @@ -580,11 +533,12 @@ func ConstructThingSearchQuery(pm clients.Page) (string, string) {
tq = emq

switch pm.Order {
case "name", "tag", "created_at", "updated_at":
case "name", "identity", "created_at", "updated_at":
emq = fmt.Sprintf("%s ORDER BY %s", emq, pm.Order)
if pm.Dir == api.AscDir || pm.Dir == api.DescDir {
emq = fmt.Sprintf("%s %s", emq, pm.Dir)
}
}

return emq, tq
}
4 changes: 2 additions & 2 deletions pkg/clients/postgres/clients_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -927,7 +927,7 @@ func TestRetrieveByIDs(t *testing.T) {
}
}

func TestRetrieveAllBasicInfo(t *testing.T) {
func TestSearchBasicInfo(t *testing.T) {
t.Cleanup(func() {
_, err := db.Exec("DELETE FROM clients")
require.Nil(t, err, fmt.Sprintf("clean clients unexpected error: %s", err))
Expand Down Expand Up @@ -1289,7 +1289,7 @@ func TestRetrieveAllBasicInfo(t *testing.T) {
}
for _, c := range cases {
t.Run(c.desc, func(t *testing.T) {
switch response, err := repo.RetrieveAllBasicInfo(context.Background(), c.page); {
switch response, err := repo.SearchBasicInfo(context.Background(), c.page); {
case err == nil:
if c.page.Order != "" && c.page.Dir != "" {
c.response = response
Expand Down
12 changes: 0 additions & 12 deletions pkg/sdk/go/sdk.go
Original file line number Diff line number Diff line change
Expand Up @@ -484,18 +484,6 @@ type SDK interface {
// fmt.Println(users)
ListThingUsers(thingID string, pm PageMetadata, token string) (UsersPage, errors.SDKError)

// SearchThings returns page of things based on the search criteria.
//
// example:
// pm := sdk.PageMetadata{
// Offset: 0,
// Limit: 10,
// Name: "My Thing",
// }
// things, _ := sdk.SearchThings(pm, "token")
// fmt.Println(things)
SearchThings(pm PageMetadata, token string) (ThingsPage, errors.SDKError)

// DeleteThing deletes a thing with the given id.
//
// example:
Expand Down
19 changes: 0 additions & 19 deletions pkg/sdk/go/things.go
Original file line number Diff line number Diff line change
Expand Up @@ -295,25 +295,6 @@ func (sdk mgSDK) ListThingUsers(thingID string, pm PageMetadata, token string) (
return up, nil
}

func (sdk mgSDK) SearchThings(pm PageMetadata, token string) (ThingsPage, errors.SDKError) {
url, err := sdk.withQueryParams(sdk.thingsURL, fmt.Sprintf("%s/search", thingsEndpoint), pm)
if err != nil {
return ThingsPage{}, errors.NewSDKError(err)
}

_, body, sdkerr := sdk.processRequest(http.MethodGet, url, token, nil, nil, http.StatusOK)
if sdkerr != nil {
return ThingsPage{}, sdkerr
}

var tp ThingsPage
if err := json.Unmarshal(body, &tp); err != nil {
return ThingsPage{}, errors.NewSDKError(err)
}

return tp, nil
}

func (sdk mgSDK) DeleteThing(id, token string) errors.SDKError {
url := fmt.Sprintf("%s/%s/%s", sdk.thingsURL, thingsEndpoint, id)
_, _, sdkerr := sdk.processRequest(http.MethodDelete, url, token, nil, nil, http.StatusNoContent)
Expand Down
Loading

0 comments on commit 3affcca

Please sign in to comment.