corbel

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 13, 2016 License: Apache-2.0, BSD-3-Clause Imports: 12 Imported by: 0

README

Build Status GoDoc Go Walker Coverage Status

Corbel-Go

corbel-go is an API library for work with corbel. It currently supports:

  • Creation of a new Client
  • Token workflow
  • Basic Authentication (username/password)
  • Resources (get/create/update/delete/search)

Note: Library in active development; requires >= Go 1.3


Usage/Sample Code

Creating a client

The client is the key to use the platform. All information here is custom for each client since its generated for every application that needs to use it.

Instancing the client allow to use it everywhere. Since Authorization can be for the application itself or its users on dynamic applications will be necessary to have several clients with several authorizations (one for each user) because you will have specific scopes based on your own permissions.

See the Authorization part to get all the possible variations.

// NewClient(http.Client, endpoints, clientId, clientName, clientSecret,
// clientScopes, clientDomain, JWTSigningMethod, tokenExpirationTime)
endpoints := map[string]string{"iam": "https://localhost", "resources": "https://localhost"}
client, _ = NewClient(nil, endpoints, "someID", "", "someSecret", "", "", "HS256", 3000)
Authorization

Getting token for client app

When you will use the client for application purposes you must ask for a OauthToken to get the specific permissions, that normally are wide open than users.

err = client.IAM.OauthToken()

Getting token for user using basic auth

If the client will be used for operations as user you need validate and get the proper user token. User token will have all the permissions applied to that user that are custom for her.

err = client.IAM.OauthTokenBasicAuth("username", "password")
User Administration

All actions over users on the domain can be done if the application/user have the required permissions. All user interactions are done using the IAM (Identity and Authorization Management) endpoint.

IAM User definition

All operations for an user must be done using the IAMUser struct.

type IAMUser struct {
	ID          string                 `json:"id,omitempty"`
	Domain      string                 `json:"domain,omitempty"`
	Username    string                 `json:"username,omitempty"`
	Email       string                 `json:"email,omitempty"`
	FirstName   string                 `json:"firstName,omitempty"`
	LastName    string                 `json:"lastName,omitempty"`
	ProfileURL  string                 `json:"profileUrl,omitempty"`
	PhoneNumber string                 `json:"phoneNumber,omitempty"`
	Scopes      []string               `json:"scopes,omitempty"`
	Properties  map[string]interface{} `json:"properties,omitempty"`
	Country     string                 `json:"country,omitempty"`
	CreatedDate int                    `json:"createdDate,omitempty"`
	CreatedBy   string                 `json:"createdBy,omitempty"`
}

NOTES:

  • User properties is a map that allow to add arbitrary information of that user. All JSON serializable types are allowed. Beware of those properties that can be empty, 0, false or nil, since it won't be exported if omitempty are used.
  • Scopes can be an empty array if are defined default scopes for users on the domain definition.
  • CreatedDate and CreatedBy are managed by the platform itself, so any change there will be ignored.
User Creation
anUserProperties := make(map[string]interface{})
anUserProperties["string"] = "test string"
anUserProperties["integer"] = 123456
anUserProperties["float"] = 1.23
anUserProperties["date"] = now

anUser := IAMUser{
  Domain:      "corbel-qa",
  Username:    "corbel-go",
  Email:       "corbel-go@corbel.org",
  FirstName:   "Corbel",
  LastName:    "Go",
  ProfileURL:  "http://corbel.org/corbel-go",
  PhoneNumber: "555-555-555",
  Scopes:      []string{},
  Properties:  anUserProperties,
  Country:     "Somewhere",
}

err = client.IAM.Add(&anUser)
User Get by ID
anUser2 := IAMUser{}
err = client.IAM.Get("sampleId", &anUser2)
User Get Current User
currentUser := IAMUser{}
err = client.IAM.GetMe(&currentUser)
User Update
anUser.Country = "Internet"
err = client.IAM.Update("sampleId", &anUser)
User Deletion
err = client.IAM.Delete("sampleId")
search := client.IAM.Search()
search.Query.Eq["username"] = "corbel-go"

var arrUsers []IAMUser

err = search.Page(0, &arrUsers)

NOTE: Searching uses the same interface defined in detail on the Resources documentation part.

Resources

Adding resource

Adds a resource of a defined type. Definitions are JSON parseable structs.

Important Note: Avoid using omitempty in the JSON definition if you think you could have a value that could turn false, 0, empty strings or nil. In those cases json.Marshal won't export the data. So value won't be updated in the backend. Important Note 2: Is recommended to define the ID on the structs to be able to update them correctly without workarounds.

type ResourceForTest struct {
  ID   string  `json:"id,omitempty"`
  Key1 string  `json:"key1"`
  Key2 int     `json:"key2"`
  Key3 float64 `json:"key3"`
  Key4 bool    `json:"key4"`
}

test1 := ResourceForTest{
  Key1: "test string",
  Key2: 123456,
  Key3: 1.123456,
  Key4: true,
}

err = client.Resources.AddToCollection("test:GoTestResource", &test1)
Search for Resources

Search allow to browse for the required resources using a simple interface. All Search conditions are shared in all modules of corbel, so it's the same for users, for example.

Per Page

var arrResourceForTest []ResourceForTest

search = client.Resources.SearchCollection("test:GoTestResource")

err = search.Page(0, &arrResourceForTest)

Conditions

Searching resources by specifying conditions.

search = client.Resources.SearchCollection("test:GoTestResource")

// all items where firstName == "testName"
search.Query.Eq["firstName"] = "testName"

// sort by firstName
search.Sort.Asc = []string{"firstName"}

// list 20 resources por search page
search.PerPage = 20

err = search.Page(0, &arrResourceForTest)

All allowed search conditions

	Eq   map[string]string     // Equal to
	Gt   map[string]int        // Greater than
	Gte  map[string]int        // Greater than or equal
	Lt   map[string]int        // Less than
	Lte  map[string]int        // Less than or equal
	Ne   map[string]string     // Not Equal
	In   map[string][]string   // One of this array
	All  map[string][]string   // All of this array
	Like map[string]string     // Like

Sort conditions

  Asc  []string   // Ascendent
  Desc []string   // Descendent

Aggregations

func (s *Search) Count(field string) (int, error) {}
func (s *Search) CountAll() (int, error) {}
func (s *Search) Average(field string) (float64, error) {}
func (s *Search) Sum(field string) (float64, error) {}
Get resource
test2 := ResourceForTest{}

err = client.Resources.GetFromCollection("test:GoTestResource",
                                         "1234567890abcdef", &test2)
Updating resource
test2.Key1 = "new string"
err = client.Resources.UpdateInCollection("test:GoTestResource",
                                         "1234567890abcdef", &test2)
Delete resource
err = client.Resources.DeleteFromCollection("test:GoTestResource",
                                            "1234567890abcdef")
Relations between Resources

Resources can have related resources using collections. As sample think in a Music Group resource that have several Album resources.

Adding a resource to a Collection automatically creates the Colection, so you don't need to be worried on Collection creation. All relations allow to add custom metadata. To query that metadata is posible to create custom metadata structs to use it later.

// Sample without metadata
err = client.Resources.AddRelation("test:MusicGroup", "12345",
                                   "test:Albums",
                                   "test:Album", "23456",
                                   nil)

// Sample with custom metadata
type groupAlbumRelation struct {
  RecordLabel string `json:"recordLabel"`
}
metadata := groupAlbumRelation{
  RecordLabel: "Sample Record Label",
}
err = client.Resources.AddRelation("test:MusicGroup", "12345",
                                   "test:Albums",
                                   "test:Album", "23456",
                                   metadata)
Move/Reorder target Resources in a Relation

Resources relation allows to reorder the items to be able to get them in the desired order in searches.

Sample: Items: ["1", "2", "3"] MoveRelation "3", 1 Items: ["3", "1", "2"]

// Move the Item "2" to the first position.
err = client.Resources.MoveRelation("test:ToDoList", "12345",
                                    "test:ToDoListItems",
                                    "test:ToDoItem", "2",
                                    1)

To get relations you can use the RelationData struct if you don't added metadata or extend RelationData with your own data.

// RelationData definition.
type RelationData struct {
	Order float64                  `json:"_order,omitempty"`
	ID    string                   `json:"id,omitempty"`
	Links []map[string]interface{} `json:"links, omitempty"`
}

Sample with standard metadata.

var arrRelationData []corbel.RelationData

search = client.Resources.SearchRelation("test:Group", "12345",
                                         "test:Albums")
err = search.Page(0, &arrRelationData)

Sample with custom metadata.

type customRelationData struct {
	Order       float64                  `json:"_order,omitempty"`
	ID          string                   `json:"id,omitempty"`
	Links       []map[string]interface{} `json:"links, omitempty"`
  RecordLabel string                   `json:"recordLabel"`
}
var arrRelationData []customRelationData

search = client.Resources.SearchRelation("test:Group", "12345",
                                         "test:Albums")
err = search.Page(0, &arrRelationData)

Sample with selected ordering.

var arrRelationData []customRelationData

search = client.Resources.SearchRelation("test:Group", "12345",
                                         "test:Albums")
search.Sort.Asc = []string{"_order"}
err = search.Page(0, &arrRelationData)
Get Resource from Response

Searching for resources information does not return the target object itself, it returns a pointer to to plus the custom metadata (if added).

type Album struct {
  Title           string `json:"title"`
  PublicationYear int    `json:"publicationYear"`
}

var anAlbum Album

err = client.Resources.GetFromRelationDefinition(arrRelationData[0].ID, &anAlbum)
Delete a Relation*
err = client.Resources.DeleteRelation("test:Group", "12345",
                                      "test:Albums",
                                      "test:Album", "23456")
Delete all Relations
err = client.Resources.DeleteAllRelations("test:Group", "12345",
                                          "test:Albums")

Contributing
  • Fork it
  • Create your feature branch (git checkout -b my-new-feature)
  • Commit your changes (git commit -am 'Add some feature')
  • Push to the branch (git push origin my-new-feature)
  • Create new Pull Request
  • If applicable, update the README.md

Documentation

Index

Constants

View Source
const (

	// SortAsc used for sorting (ascending)
	SortAsc = "asc"
	// SortDesc used for sorting (descending)
	SortDesc = "desc"
)
View Source
const Version = "0.1.0"

Version of the library

Variables

This section is empty.

Functions

This section is empty.

Types

type AssetsService

type AssetsService struct {
	// contains filtered or unexported fields
}

AssetsService handles communication with the Assets service of Corbel. It takes care of user assets that gives special scopes to the resources.

Full API info: http://docs.silkroadassets.apiary.io/

func (*AssetsService) UpgradeToken

func (a *AssetsService) UpgradeToken() error

UpgradeToken returns the assertion to upgrade the token on IAM to get the 'purchased' scopes

type Client

type Client struct {

	// Endpoint is a structure that stores the uri for each resource
	Endpoints map[string]string

	// ClientName is the name that match the clientID
	// (Optional) The required information is the clientID
	ClientName string

	// ClientID is the application defined client on Corbel.
	ClientID string

	// ClientSecret is the application secret hash that match with clientID.
	ClientSecret string

	// ClientScopes are those scopes the client will ask for to the platform when building the client connection
	// ClientScopes is a string with the scopes delimited by spaces.
	ClientScopes string

	// ClientDomain is the SR domain where to make the operations using the provided credentials.
	// (Optional) Every clientID only maps to one SR domain.
	ClientDomain string

	// ClientJWTSigningMethod defines the signing method configured for the client.
	// Must match with the one configured on the platform since it will understand only that one.
	// Only allowed signing methods at the moment are: HS256 and RSA
	ClientJWTSigningMethod string

	// TokenExpirationTime define the amount of time in seconds that a token must be valid.
	// It must be lower than 3600 seconds, since is the imposed requisite from the platform.
	TokenExpirationTime uint64

	// UserAgent defines the UserAgent to send in the Headers for every request to the platform.
	UserAgent string

	// Token is the actual token to send as Authentication Bearer
	CurrentToken string

	// CurrentTokenExpiresAt is the unix time where the token will expire
	CurrentTokenExpiresAt int64

	// CurrentRefreshToken is the current refresh token received from the IAM service
	CurrentRefreshToken string

	// IAM endpoint struct
	IAM       *IAMService
	Resources *ResourcesService
	Assets    *AssetsService

	// LogLevel for the logger.
	LogLevel string
	// contains filtered or unexported fields
}

Client is the struct that manages communication with the Corbel APIs.

func DefaultClient

func DefaultClient(endpoints map[string]string, clientID, clientName, clientSecret, clientScopes, clientDomain string) (*Client, error)

DefaultClient return a client with most of its values set to the default ones

func NewClient

func NewClient(httpClient *http.Client, endpoints map[string]string, clientID, clientName, clientSecret, clientScopes, clientDomain, clientJWTSigningMethod string, tokenExpirationTime uint64, logLevel string) (*Client, error)

NewClient returns a new Corbel API client. If a nil httpClient is provided, it will return a http.DefaultClient. If a empty environment is provided, it will use production as environment.

func (*Client) NewRequest

func (c *Client) NewRequest(method, endpoint, url string, body interface{}) (*http.Request, error)

NewRequest creates an API request using 'application/json', most common api query. method is the HTTP method to use endpoint is the endpoint of SR to speak with url is the url to query. it must be preceded by a slash. body is, if specified, the value JSON encoded to be used as request body.

func (*Client) NewRequestContentType

func (c *Client) NewRequestContentType(method, endpoint, urlStr, headerContentType, headerAccept string, body interface{}) (*http.Request, error)

NewRequestContentType creates an API request. method is the HTTP method to use endpoint is the endpoint of SR to speak with urlStr is the url to query. it must be preceded by a slash. headerContentType is the header['Content-Type'] of the request. headerAccept is the header['Accept'] of the request. body is, if specified, the value JSON encoded to be used as request body.

func (*Client) Token

func (c *Client) Token() string

Token returns the token to use as bearer. If the token has already expired it refresh it.

func (*Client) URLFor

func (c *Client) URLFor(endpoint, uri string) string

URLFor returns the formated url of the API using the actual url scheme

type IAMAuthConfiguration

type IAMAuthConfiguration struct {
	// Type defined the Auth Configuration type defined
	Type        string `json:"type"`
	RedirectURL string `json:"redirectUri"`
	// ClientId used for Facebook, Google and Corbel Oauth 2.0
	ClientID     string `json:"clientID,omitempty"`
	ClientSecret string `json:"clientSecret,omitempty"`
	// OAuthServerURL is the Oauth URL to use in Corbel Oauth
	OAuthServerURL string `json:"oAuthServerUrl,omitempty"`
	// CounsumerKey used for Twitter Oauth
	ConsumerKey    string `json:"consumerKey,omitempty"`
	ConsumerSecret string `json:"consumerSecret,omitempty"`
}

IAMAuthConfiguration is the representation of an AuthConfiguration object used by IAM

type IAMClient

type IAMClient struct {
	ID                       string   `json:"id,omitempty"`
	Key                      string   `json:"key"`
	Name                     string   `json:"name"`
	Domain                   string   `json:"domain"`
	Version                  string   `json:"version,omitempty"`
	SignatureAlgorithm       string   `json:"signatureAlgorithm,omitempty"`
	Scopes                   []string `json:"scopes,omitempty"`
	ClientSideAuthentication bool     `json:"clientSideAuthentication"`
	ResetURL                 string   `json:"resetUrl,omitempty"`
	ResetNotificationID      string   `json:"resetNotificationId,omitempty"`
}

IAMClient is the representation of a Client object used by IAM

type IAMDomain

type IAMDomain struct {
	ID                 string                          `json:"id"`
	Description        string                          `json:"description,omitempty"`
	AuthURL            string                          `json:"authUrl, omitempty"`
	AllowedDomains     string                          `json:"allowedDomains"`
	Scopes             []string                        `json:"scopes,omitempty"`
	DefaultScopes      []string                        `json:"defaultScopes,omitempty"`
	AuthConfigurations map[string]IAMAuthConfiguration `json:"authConfigurations,omitempty"`
	UserProfileFields  []string                        `json:"userProfileFields,omitempty"`
	CreatedDate        int                             `json:"createdDate,omitempty"`
	CreatedBy          string                          `json:"createdBy,omitempty"`
}

IAMDomain is the representation of an Domain object used by IAM

type IAMGroup

type IAMGroup struct {
	ID     string   `json:"id,omitempty"`
	Name   string   `json:"name"`
	Scopes []string `json:"scopes"` // must be omitempty
}

IAMGroup is the representation of a Group object used by IAM

type IAMRule

type IAMRule struct {
	MediaTypes []string `json:"mediaTypes"`
	Methods    []string `json:"methods"`
	Type       string   `json:"type"`
	URI        string   `json:"uri"`
	TokenType  string   `json:"tokenType"`
}

IAMRule is the representation of a Rule for a Scope object used by IAM

type IAMScope

type IAMScope struct {
	ID         string            `json:"id"`
	Audience   string            `json:"audience"`
	Type       string            `json:"type"`
	Scopes     []string          `json:"scopes,omitempty"`
	Parameters map[string]string `json:"parameters,omitempty"`
	Rules      []IAMRule         `json:"rules,omitempty"`
}

IAMScope is the representation of a Scope object used by IAM

type IAMService

type IAMService struct {
	// contains filtered or unexported fields
}

IAMService handles communication with the IAM service of Corbel. It takes care of all Identity and Authorization Management

Full API info: http://docs.silkroadiam.apiary.io/

func (*IAMService) ClientAdd

func (i *IAMService) ClientAdd(client *IAMClient) (string, error)

ClientAdd adds an Client defined struct to the platform

func (*IAMService) ClientDelete

func (i *IAMService) ClientDelete(domainName, id string) error

ClientDelete deletes the desired client from IAM by id

func (*IAMService) ClientGet

func (i *IAMService) ClientGet(domainName, id string, client *IAMClient) error

ClientGet gets the desired IAMClient

func (*IAMService) ClientSearch

func (i *IAMService) ClientSearch(domainName string) *Search

ClientSearch gets the desired objects in base of a search query

func (*IAMService) ClientUpdate

func (i *IAMService) ClientUpdate(id string, client *IAMClient) error

ClientUpdate updates an client by using IAMClient

func (*IAMService) DomainAdd

func (i *IAMService) DomainAdd(domain *IAMDomain) (string, error)

DomainAdd adds an Domain defined struct to the platform

func (*IAMService) DomainDelete

func (i *IAMService) DomainDelete(id string) error

DomainDelete deletes the desired domain from IAM by id

func (*IAMService) DomainGet

func (i *IAMService) DomainGet(id string, domain *IAMDomain) error

DomainGet gets the desired IAMUdomain from the domain by id

func (*IAMService) DomainSearch

func (i *IAMService) DomainSearch() *Search

DomainSearch gets the desired objects in base of a search query

func (*IAMService) DomainUpdate

func (i *IAMService) DomainUpdate(id string, domain *IAMDomain) error

DomainUpdate updates an domain by using IAMDomain

func (*IAMService) GroupAdd

func (i *IAMService) GroupAdd(group *IAMGroup) (string, error)

GroupAdd adds a new group to iam into the current domain

func (*IAMService) GroupDelete

func (i *IAMService) GroupDelete(id string) error

GroupDelete deletes the desired group from IAM by id

func (*IAMService) GroupDeleteScope

func (i *IAMService) GroupDeleteScope(id string, scope string) error

GroupDeleteScope deletes a scope of a group

func (*IAMService) GroupGet

func (i *IAMService) GroupGet(id string, group *IAMGroup) error

GroupGet gets the desired IAMGroup from the domain by id

func (*IAMService) GroupGetAll

func (i *IAMService) GroupGetAll(groups []*IAMGroup) error

GroupGetAll gets all Groups of the client current domain

func (*IAMService) GroupSetScopes

func (i *IAMService) GroupSetScopes(id string, scopes []string) error

GroupSetScopes set the scopes of a Group

func (*IAMService) OauthToken

func (i *IAMService) OauthToken() error

OauthToken gets an access token

API Docs: http://docs.silkroadiam.apiary.io/#reference/authorization/oauthtoken

func (*IAMService) OauthTokenBasicAuth

func (i *IAMService) OauthTokenBasicAuth(username, password string) error

OauthTokenBasicAuth gets an access token using username/password scheme (basic auth)

API Docs: http://docs.silkroadiam.apiary.io/#reference/authorization/oauthtoken

func (*IAMService) OauthTokenPrn

func (i *IAMService) OauthTokenPrn(username string) error

OauthTokenPrn get user access token to use it

func (*IAMService) OauthTokenUpgrade

func (i *IAMService) OauthTokenUpgrade(assetsToken string) error

OauthTokenUpgrade upgrade the token using the token generated by the module Assets

on /assets/access and adds the scopes assigned at assets level to the current
logged user returning a new token with those additional scopes.

API Docs: http://docs.silkroadiam.apiary.io/#reference/authorization/oauthtokenupgrade

func (*IAMService) RefreshToken

func (i *IAMService) RefreshToken() error

RefreshToken gets an access token

API Docs: http://docs.silkroadiam.apiary.io/#reference/authorization/oauthtoken

func (*IAMService) ScopeAdd

func (i *IAMService) ScopeAdd(scope *IAMScope) (string, error)

ScopeAdd adds an Scope defined struct to the platform

func (*IAMService) ScopeDelete

func (i *IAMService) ScopeDelete(id string) error

ScopeDelete deletes the desired scope from IAM by id

func (*IAMService) ScopeGet

func (i *IAMService) ScopeGet(id string, scope *IAMScope) error

ScopeGet gets the desired IAMScope from the scope by id

func (*IAMService) ScopeUpdate

func (i *IAMService) ScopeUpdate(scope *IAMScope) (string, error)

ScopeUpdate updates an scope by using IAMScope

func (*IAMService) UserAdd

func (i *IAMService) UserAdd(user *IAMUser) (string, error)

UserAdd adds an IAMUser defined struct to the domain of the client

func (*IAMService) UserAddGroups

func (i *IAMService) UserAddGroups(userID string, groupIDs []string) error

UserAddGroups add groups to user's list of groups

func (*IAMService) UserByUsername

func (i *IAMService) UserByUsername(username string) (*IAMUser, error)

UserByUsername allow to find an user based on its username

func (*IAMService) UserDelete

func (i *IAMService) UserDelete(id string) error

UserDelete deletes the desired user from IAM by id

func (*IAMService) UserDeleteGroup

func (i *IAMService) UserDeleteGroup(userID, groupID string) error

UserDeleteGroup deletes a groups from the user group list

func (*IAMService) UserDeleteMe

func (i *IAMService) UserDeleteMe() error

UserDeleteMe deletes the user authenticated by the current token

func (*IAMService) UserExists

func (i *IAMService) UserExists(username string) bool

UserExists checks if an user exists in the domain of the client

func (*IAMService) UserGet

func (i *IAMService) UserGet(id string, user *IAMUser) error

UserGet gets the desired IAMUuser from the domain by id

func (*IAMService) UserGetMe

func (i *IAMService) UserGetMe(user *IAMUser) error

UserGetMe gets the user authenticated by the current token

func (*IAMService) UserSearch

func (i *IAMService) UserSearch() *Search

UserSearch gets the desired objects in base of a search query

func (*IAMService) UserUpdate

func (i *IAMService) UserUpdate(id string, user *IAMUser) error

UserUpdate updates an user by using IAMUser

func (*IAMService) UserUpdateMe

func (i *IAMService) UserUpdateMe(user *IAMUser) error

UserUpdateMe updates the user authenticated by the current token

type IAMUser

type IAMUser struct {
	ID          string                 `json:"id,omitempty"`
	Domain      string                 `json:"domain,omitempty"`
	Username    string                 `json:"username,omitempty"`
	Email       string                 `json:"email,omitempty"`
	Password    string                 `json:"password,omitempty"`
	FirstName   string                 `json:"firstName,omitempty"`
	LastName    string                 `json:"lastName,omitempty"`
	ProfileURL  string                 `json:"profileUrl,omitempty"`
	PhoneNumber string                 `json:"phoneNumber,omitempty"`
	Scopes      []string               `json:"scopes"`
	Properties  map[string]interface{} `json:"properties,omitempty"`
	Country     string                 `json:"country,omitempty"`
	CreatedDate int                    `json:"createdDate,omitempty"`
	CreatedBy   string                 `json:"createdBy,omitempty"`
	Groups      []string               `json:"groups,omitempty"`
}

IAMUser is the representation of an User object used by IAM

type RelationData

type RelationData struct {
	Order float64                  `json:"_order,omitempty"`
	ID    string                   `json:"id,omitempty"`
	Links []map[string]interface{} `json:"links, omitempty"`
}

RelationData is a basic structure of data relations. By default this are the simplest data stored in a relation, but since it's possible to add specific data to the relation you can create your own RelationData struct. You must include ID as minimum if you want to use GetFromRelation func to retrieve the resource itself.

type ResourcesService

type ResourcesService struct {
	// contains filtered or unexported fields
}

ResourcesService handles the interface for retrival resource's representation on Corbel.

Full API info: http://docs.corbelresources.apiary.io/

func (*ResourcesService) AddRelation

func (r *ResourcesService) AddRelation(collectionName, resourceID, relationName, relatedCollectionName, relatedID string, relationInfo interface{}) (string, error)

AddRelation adds the required relation to the resource in the collection with the _related_ resource. Additionally arbitrary information can be passed to as relation data or nil.

func (*ResourcesService) AddToCollection

func (r *ResourcesService) AddToCollection(collectionName string, resource interface{}) (string, error)

AddToCollection add the required struct formated as json to the desired collection resource must have exported variables and optionally its representation as JSON.

func (*ResourcesService) CollectionRequest

func (r *ResourcesService) CollectionRequest(method, accept, collectionName string, send interface{}) (*http.Request, error)

CollectionRequest perform a specific collection request on resources

func (*ResourcesService) DeleteACLCollection

func (r *ResourcesService) DeleteACLCollection(id string) error

DeleteACLCollection is used to delete an acl managed collection

func (*ResourcesService) DeleteAllRelations

func (r *ResourcesService) DeleteAllRelations(collectionName, resourceID, relationName string) error

DeleteAllRelations deletes all the relations by relationName of the desired resource

func (*ResourcesService) DeleteFromCollection

func (r *ResourcesService) DeleteFromCollection(collectionName, id string) error

DeleteFromCollection deletes the desired resource from the platform by id

func (*ResourcesService) DeleteRelation

func (r *ResourcesService) DeleteRelation(collectionName, resourceID, relationName, relatedCollectionName, relatedID string) error

DeleteRelation deletes the desired relation between the origin and the related resource

func (*ResourcesService) GetFromCollection

func (r *ResourcesService) GetFromCollection(collectionName, id string, resource interface{}) error

GetFromCollection gets the desired object from the collection by id

func (*ResourcesService) GetFromRelationDefinition

func (r *ResourcesService) GetFromRelationDefinition(id string, resource interface{}) error

GetFromRelationDefinition gets the desired object from the collection by id

func (*ResourcesService) MarkCollectionAsACL

func (r *ResourcesService) MarkCollectionAsACL(info interface{}) error

MarkCollectionAsACL is used to set a collection as ACL managed

func (*ResourcesService) MoveRelation

func (r *ResourcesService) MoveRelation(collectionName, resourceID, relationName, relatedCollectionName, relatedID string, order int) (string, error)

MoveRelation sets the required order of the related items on the relationship.

func (*ResourcesService) RelationRequest

func (r *ResourcesService) RelationRequest(method, accept, collectionName, resourceID, relationName, relatedCollectionName, relatedID string, send interface{}) (*http.Request, error)

RelationRequest perform a specific relation request on resources

func (*ResourcesService) ResourceRequest

func (r *ResourcesService) ResourceRequest(method, accept, collectionName, id string, send interface{}) (*http.Request, error)

ResourceRequest perform a specific resource request on resources

func (*ResourcesService) SearchCollection

func (r *ResourcesService) SearchCollection(collectionName string) *Search

SearchCollection gets the desired objects in base of a search query

func (*ResourcesService) SearchRelation

func (r *ResourcesService) SearchRelation(collectionName, resourceID, relationName string) *Search

SearchRelation returns an instance to the Search Builder

func (*ResourcesService) SearchSpecificRelation

func (r *ResourcesService) SearchSpecificRelation(collectionName, resourceID, relationName, relatedCollectionName, relatedID string) *Search

SearchSpecificRelation returns a relation between two objects belonging to the relation

func (*ResourcesService) UpdateACLCollection

func (r *ResourcesService) UpdateACLCollection(id string, info interface{}) error

UpdateACLCollection is used to update an acl managed collection

func (*ResourcesService) UpdateInCollection

func (r *ResourcesService) UpdateInCollection(collectionName, id string, resource interface{}) error

UpdateInCollection updates the required struct formated as json to the desired collection resource must have exported variables and optionally its representation as JSON.

func (*ResourcesService) UpdateResourceACL

func (r *ResourcesService) UpdateResourceACL(collectionName, id string, acl interface{}) error

UpdateResourceACL updates the acl of the associated resource. ACL entries will be added if they were not previously there or modified otherwise. Any entries previously added but not passed will be removed.

type Search struct {
	Query    *apiquery
	Sort     *sort
	PageSize int
	// contains filtered or unexported fields
}

Search is the struct used to query every searcheable api in the platform

func NewSearch

func NewSearch(client *Client, endpoint, baseURL string) *Search

NewSearch returns a Search struct that allows to select especific search requirements

func (*Search) Average

func (s *Search) Average(field string) (float64, error)

Average returns the average of an especific field in the search

func (*Search) Count

func (s *Search) Count(field string) (int, error)

Count returns the aggregated count of an especific field in the search

func (*Search) CountAll

func (s *Search) CountAll() (int, error)

CountAll returns the aggregated count of all items in the search. It's an alias of Count("*")

func (*Search) Page

func (s *Search) Page(pageNumber int, result interface{}) error

Page fills the struct array passed as parameter as paged search by pageNumber

func (*Search) Sum

func (s *Search) Sum(field string) (float64, error)

Sum returns the average of an especific field in the search as float

type SearchListOptions

type SearchListOptions struct {
	APIQuery       string `url:"api:query,omitempty"`
	APISort        string `url:"api:sort,omitempty"`
	APIPageSize    int    `url:"api:pageSize,omitempty"`
	APIPage        int    `url:"api:page,omitempty"`
	APIAggregation string `url:"api:aggregation,omitempty"`
}

SearchListOptions specifies the optional parameters for searches supporting paging and aggregation

type UserACL

type UserACL struct {
	Permission string                 `json:"permission"`
	Properties map[string]interface{} `json:"properties"`
}

UserACL defines the content of an ACL for a user

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL